Remove signing htlc transaction from ChannelMonitor
[rust-lightning] / lightning / src / ln / chan_utils.rs
1 //! Various utilities for building scripts and deriving keys related to channels. These are
2 //! largely of interest for those implementing chain::keysinterface::ChannelKeys message signing
3 //! by hand.
4
5 use bitcoin::blockdata::script::{Script,Builder};
6 use bitcoin::blockdata::opcodes;
7 use bitcoin::blockdata::transaction::{TxIn,TxOut,OutPoint,Transaction, SigHashType};
8 use bitcoin::consensus::encode::{self, Decodable, Encodable};
9 use bitcoin::util::bip143;
10
11 use bitcoin_hashes::{Hash, HashEngine};
12 use bitcoin_hashes::sha256::Hash as Sha256;
13 use bitcoin_hashes::ripemd160::Hash as Ripemd160;
14 use bitcoin_hashes::hash160::Hash as Hash160;
15 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
16
17 use ln::channelmanager::PaymentHash;
18 use ln::msgs::DecodeError;
19 use util::ser::{Readable, Writeable, Writer, WriterWriteAdaptor};
20 use util::byte_utils;
21
22 use secp256k1::key::{SecretKey, PublicKey};
23 use secp256k1::{Secp256k1, Signature};
24 use secp256k1;
25
26 pub(super) const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
27 pub(super) const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
28
29 #[derive(PartialEq)]
30 pub(crate) enum HTLCType {
31         AcceptedHTLC,
32         OfferedHTLC
33 }
34
35 impl HTLCType {
36         /// Check if a given tx witnessScript len matchs one of a pre-signed HTLC
37         pub(crate) fn scriptlen_to_htlctype(witness_script_len: usize) ->  Option<HTLCType> {
38                 if witness_script_len == 133 {
39                         Some(HTLCType::OfferedHTLC)
40                 } else if witness_script_len >= 136 && witness_script_len <= 139 {
41                         Some(HTLCType::AcceptedHTLC)
42                 } else {
43                         None
44                 }
45         }
46 }
47
48 // Various functions for key derivation and transaction creation for use within channels. Primarily
49 // used in Channel and ChannelMonitor.
50
51 pub(super) fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
52         let mut res: [u8; 32] = commitment_seed.clone();
53         for i in 0..48 {
54                 let bitpos = 47 - i;
55                 if idx & (1 << bitpos) == (1 << bitpos) {
56                         res[bitpos / 8] ^= 1 << (bitpos & 7);
57                         res = Sha256::hash(&res).into_inner();
58                 }
59         }
60         res
61 }
62
63 /// Implements the per-commitment secret storage scheme from
64 /// [BOLT 3](https://github.com/lightningnetwork/lightning-rfc/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
65 ///
66 /// Allows us to keep track of all of the revocation secrets of counterarties in just 50*32 bytes
67 /// or so.
68 #[derive(Clone)]
69 pub(super) struct CounterpartyCommitmentSecrets {
70         old_secrets: [([u8; 32], u64); 49],
71 }
72
73 impl PartialEq for CounterpartyCommitmentSecrets {
74         fn eq(&self, other: &Self) -> bool {
75                 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
76                         if secret != o_secret || idx != o_idx {
77                                 return false
78                         }
79                 }
80                 true
81         }
82 }
83
84 impl CounterpartyCommitmentSecrets {
85         pub(super) fn new() -> Self {
86                 Self { old_secrets: [([0; 32], 1 << 48); 49], }
87         }
88
89         #[inline]
90         fn place_secret(idx: u64) -> u8 {
91                 for i in 0..48 {
92                         if idx & (1 << i) == (1 << i) {
93                                 return i
94                         }
95                 }
96                 48
97         }
98
99         pub(super) fn get_min_seen_secret(&self) -> u64 {
100                 //TODO This can be optimized?
101                 let mut min = 1 << 48;
102                 for &(_, idx) in self.old_secrets.iter() {
103                         if idx < min {
104                                 min = idx;
105                         }
106                 }
107                 min
108         }
109
110         #[inline]
111         pub(super) fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
112                 let mut res: [u8; 32] = secret;
113                 for i in 0..bits {
114                         let bitpos = bits - 1 - i;
115                         if idx & (1 << bitpos) == (1 << bitpos) {
116                                 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
117                                 res = Sha256::hash(&res).into_inner();
118                         }
119                 }
120                 res
121         }
122
123         pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
124                 let pos = Self::place_secret(idx);
125                 for i in 0..pos {
126                         let (old_secret, old_idx) = self.old_secrets[i as usize];
127                         if Self::derive_secret(secret, pos, old_idx) != old_secret {
128                                 return Err(());
129                         }
130                 }
131                 if self.get_min_seen_secret() <= idx {
132                         return Ok(());
133                 }
134                 self.old_secrets[pos as usize] = (secret, idx);
135                 Ok(())
136         }
137
138         /// Can only fail if idx is < get_min_seen_secret
139         pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
140                 for i in 0..self.old_secrets.len() {
141                         if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
142                                 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
143                         }
144                 }
145                 assert!(idx < self.get_min_seen_secret());
146                 None
147         }
148 }
149
150 impl Writeable for CounterpartyCommitmentSecrets {
151         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
152                 for &(ref secret, ref idx) in self.old_secrets.iter() {
153                         writer.write_all(secret)?;
154                         writer.write_all(&byte_utils::be64_to_array(*idx))?;
155                 }
156                 Ok(())
157         }
158 }
159 impl Readable for CounterpartyCommitmentSecrets {
160         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
161                 let mut old_secrets = [([0; 32], 1 << 48); 49];
162                 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
163                         *secret = Readable::read(reader)?;
164                         *idx = Readable::read(reader)?;
165                 }
166
167                 Ok(Self { old_secrets })
168         }
169 }
170
171 /// Derives a per-commitment-transaction private key (eg an htlc key or payment key) from the base
172 /// private key for that type of key and the per_commitment_point (available in TxCreationKeys)
173 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> Result<SecretKey, secp256k1::Error> {
174         let mut sha = Sha256::engine();
175         sha.input(&per_commitment_point.serialize());
176         sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
177         let res = Sha256::from_engine(sha).into_inner();
178
179         let mut key = base_secret.clone();
180         key.add_assign(&res)?;
181         Ok(key)
182 }
183
184 pub(super) fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> Result<PublicKey, secp256k1::Error> {
185         let mut sha = Sha256::engine();
186         sha.input(&per_commitment_point.serialize());
187         sha.input(&base_point.serialize());
188         let res = Sha256::from_engine(sha).into_inner();
189
190         let hashkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&res)?);
191         base_point.combine(&hashkey)
192 }
193
194 /// Derives a revocation key from its constituent parts.
195 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
196 /// generated (ie our own).
197 pub(super) fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_secret: &SecretKey, revocation_base_secret: &SecretKey) -> Result<SecretKey, secp256k1::Error> {
198         let revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &revocation_base_secret);
199         let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
200
201         let rev_append_commit_hash_key = {
202                 let mut sha = Sha256::engine();
203                 sha.input(&revocation_base_point.serialize());
204                 sha.input(&per_commitment_point.serialize());
205
206                 Sha256::from_engine(sha).into_inner()
207         };
208         let commit_append_rev_hash_key = {
209                 let mut sha = Sha256::engine();
210                 sha.input(&per_commitment_point.serialize());
211                 sha.input(&revocation_base_point.serialize());
212
213                 Sha256::from_engine(sha).into_inner()
214         };
215
216         let mut part_a = revocation_base_secret.clone();
217         part_a.mul_assign(&rev_append_commit_hash_key)?;
218         let mut part_b = per_commitment_secret.clone();
219         part_b.mul_assign(&commit_append_rev_hash_key)?;
220         part_a.add_assign(&part_b[..])?;
221         Ok(part_a)
222 }
223
224 pub(super) fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, revocation_base_point: &PublicKey) -> Result<PublicKey, secp256k1::Error> {
225         let rev_append_commit_hash_key = {
226                 let mut sha = Sha256::engine();
227                 sha.input(&revocation_base_point.serialize());
228                 sha.input(&per_commitment_point.serialize());
229
230                 Sha256::from_engine(sha).into_inner()
231         };
232         let commit_append_rev_hash_key = {
233                 let mut sha = Sha256::engine();
234                 sha.input(&per_commitment_point.serialize());
235                 sha.input(&revocation_base_point.serialize());
236
237                 Sha256::from_engine(sha).into_inner()
238         };
239
240         let mut part_a = revocation_base_point.clone();
241         part_a.mul_assign(&secp_ctx, &rev_append_commit_hash_key)?;
242         let mut part_b = per_commitment_point.clone();
243         part_b.mul_assign(&secp_ctx, &commit_append_rev_hash_key)?;
244         part_a.combine(&part_b)
245 }
246
247 /// The set of public keys which are used in the creation of one commitment transaction.
248 /// These are derived from the channel base keys and per-commitment data.
249 #[derive(PartialEq, Clone)]
250 pub struct TxCreationKeys {
251         /// The per-commitment public key which was used to derive the other keys.
252         pub per_commitment_point: PublicKey,
253         /// The revocation key which is used to allow the owner of the commitment transaction to
254         /// provide their counterparty the ability to punish them if they broadcast an old state.
255         pub(crate) revocation_key: PublicKey,
256         /// A's HTLC Key
257         pub(crate) a_htlc_key: PublicKey,
258         /// B's HTLC Key
259         pub(crate) b_htlc_key: PublicKey,
260         /// A's Payment Key (which isn't allowed to be spent from for some delay)
261         pub(crate) a_delayed_payment_key: PublicKey,
262         /// B's Payment Key
263         pub(crate) b_payment_key: PublicKey,
264 }
265 impl_writeable!(TxCreationKeys, 33*6,
266         { per_commitment_point, revocation_key, a_htlc_key, b_htlc_key, a_delayed_payment_key, b_payment_key });
267
268 /// One counterparty's public keys which do not change over the life of a channel.
269 #[derive(Clone, PartialEq)]
270 pub struct ChannelPublicKeys {
271         /// The public key which is used to sign all commitment transactions, as it appears in the
272         /// on-chain channel lock-in 2-of-2 multisig output.
273         pub funding_pubkey: PublicKey,
274         /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
275         /// revocation keys. The per-commitment revocation private key is then revealed by the owner of
276         /// a commitment transaction so that their counterparty can claim all available funds if they
277         /// broadcast an old state.
278         pub revocation_basepoint: PublicKey,
279         /// The base point which is used (with derive_public_key) to derive a per-commitment payment
280         /// public key which receives immediately-spendable non-HTLC-encumbered funds.
281         pub payment_basepoint: PublicKey,
282         /// The base point which is used (with derive_public_key) to derive a per-commitment payment
283         /// public key which receives non-HTLC-encumbered funds which are only available for spending
284         /// after some delay (or can be claimed via the revocation path).
285         pub delayed_payment_basepoint: PublicKey,
286         /// The base point which is used (with derive_public_key) to derive a per-commitment public key
287         /// which is used to encumber HTLC-in-flight outputs.
288         pub htlc_basepoint: PublicKey,
289 }
290
291 impl_writeable!(ChannelPublicKeys, 33*5, {
292         funding_pubkey,
293         revocation_basepoint,
294         payment_basepoint,
295         delayed_payment_basepoint,
296         htlc_basepoint
297 });
298
299
300 impl TxCreationKeys {
301         pub(crate) fn new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, a_delayed_payment_base: &PublicKey, a_htlc_base: &PublicKey, b_revocation_base: &PublicKey, b_payment_base: &PublicKey, b_htlc_base: &PublicKey) -> Result<TxCreationKeys, secp256k1::Error> {
302                 Ok(TxCreationKeys {
303                         per_commitment_point: per_commitment_point.clone(),
304                         revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &b_revocation_base)?,
305                         a_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_htlc_base)?,
306                         b_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_htlc_base)?,
307                         a_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_delayed_payment_base)?,
308                         b_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_payment_base)?,
309                 })
310         }
311 }
312
313 /// Gets the "to_local" output redeemscript, ie the script which is time-locked or spendable by
314 /// the revocation key
315 pub(super) fn get_revokeable_redeemscript(revocation_key: &PublicKey, to_self_delay: u16, delayed_payment_key: &PublicKey) -> Script {
316         Builder::new().push_opcode(opcodes::all::OP_IF)
317                       .push_slice(&revocation_key.serialize())
318                       .push_opcode(opcodes::all::OP_ELSE)
319                       .push_int(to_self_delay as i64)
320                       .push_opcode(opcodes::all::OP_CSV)
321                       .push_opcode(opcodes::all::OP_DROP)
322                       .push_slice(&delayed_payment_key.serialize())
323                       .push_opcode(opcodes::all::OP_ENDIF)
324                       .push_opcode(opcodes::all::OP_CHECKSIG)
325                       .into_script()
326 }
327
328 #[derive(Clone, PartialEq)]
329 /// Information about an HTLC as it appears in a commitment transaction
330 pub struct HTLCOutputInCommitment {
331         /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
332         /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
333         /// need to compare this value to whether the commitment transaction in question is that of
334         /// the remote party or our own.
335         pub offered: bool,
336         /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
337         /// this divided by 1000.
338         pub amount_msat: u64,
339         /// The CLTV lock-time at which this HTLC expires.
340         pub cltv_expiry: u32,
341         /// The hash of the preimage which unlocks this HTLC.
342         pub payment_hash: PaymentHash,
343         /// The position within the commitment transactions' outputs. This may be None if the value is
344         /// below the dust limit (in which case no output appears in the commitment transaction and the
345         /// value is spent to additional transaction fees).
346         pub transaction_output_index: Option<u32>,
347 }
348
349 impl_writeable!(HTLCOutputInCommitment, 1 + 8 + 4 + 32 + 5, {
350         offered,
351         amount_msat,
352         cltv_expiry,
353         payment_hash,
354         transaction_output_index
355 });
356
357 #[inline]
358 pub(crate) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, a_htlc_key: &PublicKey, b_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
359         let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
360         if htlc.offered {
361                 Builder::new().push_opcode(opcodes::all::OP_DUP)
362                               .push_opcode(opcodes::all::OP_HASH160)
363                               .push_slice(&Hash160::hash(&revocation_key.serialize())[..])
364                               .push_opcode(opcodes::all::OP_EQUAL)
365                               .push_opcode(opcodes::all::OP_IF)
366                               .push_opcode(opcodes::all::OP_CHECKSIG)
367                               .push_opcode(opcodes::all::OP_ELSE)
368                               .push_slice(&b_htlc_key.serialize()[..])
369                               .push_opcode(opcodes::all::OP_SWAP)
370                               .push_opcode(opcodes::all::OP_SIZE)
371                               .push_int(32)
372                               .push_opcode(opcodes::all::OP_EQUAL)
373                               .push_opcode(opcodes::all::OP_NOTIF)
374                               .push_opcode(opcodes::all::OP_DROP)
375                               .push_int(2)
376                               .push_opcode(opcodes::all::OP_SWAP)
377                               .push_slice(&a_htlc_key.serialize()[..])
378                               .push_int(2)
379                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
380                               .push_opcode(opcodes::all::OP_ELSE)
381                               .push_opcode(opcodes::all::OP_HASH160)
382                               .push_slice(&payment_hash160)
383                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
384                               .push_opcode(opcodes::all::OP_CHECKSIG)
385                               .push_opcode(opcodes::all::OP_ENDIF)
386                               .push_opcode(opcodes::all::OP_ENDIF)
387                               .into_script()
388         } else {
389                 Builder::new().push_opcode(opcodes::all::OP_DUP)
390                               .push_opcode(opcodes::all::OP_HASH160)
391                               .push_slice(&Hash160::hash(&revocation_key.serialize())[..])
392                               .push_opcode(opcodes::all::OP_EQUAL)
393                               .push_opcode(opcodes::all::OP_IF)
394                               .push_opcode(opcodes::all::OP_CHECKSIG)
395                               .push_opcode(opcodes::all::OP_ELSE)
396                               .push_slice(&b_htlc_key.serialize()[..])
397                               .push_opcode(opcodes::all::OP_SWAP)
398                               .push_opcode(opcodes::all::OP_SIZE)
399                               .push_int(32)
400                               .push_opcode(opcodes::all::OP_EQUAL)
401                               .push_opcode(opcodes::all::OP_IF)
402                               .push_opcode(opcodes::all::OP_HASH160)
403                               .push_slice(&payment_hash160)
404                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
405                               .push_int(2)
406                               .push_opcode(opcodes::all::OP_SWAP)
407                               .push_slice(&a_htlc_key.serialize()[..])
408                               .push_int(2)
409                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
410                               .push_opcode(opcodes::all::OP_ELSE)
411                               .push_opcode(opcodes::all::OP_DROP)
412                               .push_int(htlc.cltv_expiry as i64)
413                               .push_opcode(opcodes::all::OP_CLTV)
414                               .push_opcode(opcodes::all::OP_DROP)
415                               .push_opcode(opcodes::all::OP_CHECKSIG)
416                               .push_opcode(opcodes::all::OP_ENDIF)
417                               .push_opcode(opcodes::all::OP_ENDIF)
418                               .into_script()
419         }
420 }
421
422 /// note here that 'a_revocation_key' is generated using b_revocation_basepoint and a's
423 /// commitment secret. 'htlc' does *not* need to have its previous_output_index filled.
424 #[inline]
425 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, keys: &TxCreationKeys) -> Script {
426         get_htlc_redeemscript_with_explicit_keys(htlc, &keys.a_htlc_key, &keys.b_htlc_key, &keys.revocation_key)
427 }
428
429 /// Gets the redeemscript for a funding output from the two funding public keys.
430 /// Note that the order of funding public keys does not matter.
431 pub fn make_funding_redeemscript(a: &PublicKey, b: &PublicKey) -> Script {
432         let our_funding_key = a.serialize();
433         let their_funding_key = b.serialize();
434
435         let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
436         if our_funding_key[..] < their_funding_key[..] {
437                 builder.push_slice(&our_funding_key)
438                         .push_slice(&their_funding_key)
439         } else {
440                 builder.push_slice(&their_funding_key)
441                         .push_slice(&our_funding_key)
442         }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
443 }
444
445 /// panics if htlc.transaction_output_index.is_none()!
446 pub fn build_htlc_transaction(prev_hash: &Sha256dHash, feerate_per_kw: u64, to_self_delay: u16, htlc: &HTLCOutputInCommitment, a_delayed_payment_key: &PublicKey, revocation_key: &PublicKey) -> Transaction {
447         let mut txins: Vec<TxIn> = Vec::new();
448         txins.push(TxIn {
449                 previous_output: OutPoint {
450                         txid: prev_hash.clone(),
451                         vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
452                 },
453                 script_sig: Script::new(),
454                 sequence: 0,
455                 witness: Vec::new(),
456         });
457
458         let total_fee = if htlc.offered {
459                         feerate_per_kw * HTLC_TIMEOUT_TX_WEIGHT / 1000
460                 } else {
461                         feerate_per_kw * HTLC_SUCCESS_TX_WEIGHT / 1000
462                 };
463
464         let mut txouts: Vec<TxOut> = Vec::new();
465         txouts.push(TxOut {
466                 script_pubkey: get_revokeable_redeemscript(revocation_key, to_self_delay, a_delayed_payment_key).to_v0_p2wsh(),
467                 value: htlc.amount_msat / 1000 - total_fee //TODO: BOLT 3 does not specify if we should add amount_msat before dividing or if we should divide by 1000 before subtracting (as we do here)
468         });
469
470         Transaction {
471                 version: 2,
472                 lock_time: if htlc.offered { htlc.cltv_expiry } else { 0 },
473                 input: txins,
474                 output: txouts,
475         }
476 }
477
478 #[derive(Clone)]
479 /// We use this to track local commitment transactions and put off signing them until we are ready
480 /// to broadcast. Eventually this will require a signer which is possibly external, but for now we
481 /// just pass in the SecretKeys required.
482 pub struct LocalCommitmentTransaction {
483         tx: Transaction
484 }
485 impl LocalCommitmentTransaction {
486         #[cfg(test)]
487         pub fn dummy() -> Self {
488                 let dummy_input = TxIn {
489                         previous_output: OutPoint {
490                                 txid: Default::default(),
491                                 vout: 0,
492                         },
493                         script_sig: Default::default(),
494                         sequence: 0,
495                         witness: vec![vec![], vec![], vec![]]
496                 };
497                 Self { tx: Transaction {
498                         version: 2,
499                         input: vec![dummy_input],
500                         output: Vec::new(),
501                         lock_time: 0,
502                 } }
503         }
504
505         /// Generate a new LocalCommitmentTransaction based on a raw commitment transaction,
506         /// remote signature and both parties keys
507         pub(crate) fn new_missing_local_sig(mut tx: Transaction, their_sig: &Signature, our_funding_key: &PublicKey, their_funding_key: &PublicKey) -> LocalCommitmentTransaction {
508                 if tx.input.len() != 1 { panic!("Tried to store a commitment transaction that had input count != 1!"); }
509                 if tx.input[0].witness.len() != 0 { panic!("Tried to store a signed commitment transaction?"); }
510
511                 tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
512
513                 if our_funding_key.serialize()[..] < their_funding_key.serialize()[..] {
514                         tx.input[0].witness.push(Vec::new());
515                         tx.input[0].witness.push(their_sig.serialize_der().to_vec());
516                         tx.input[0].witness[2].push(SigHashType::All as u8);
517                 } else {
518                         tx.input[0].witness.push(their_sig.serialize_der().to_vec());
519                         tx.input[0].witness[1].push(SigHashType::All as u8);
520                         tx.input[0].witness.push(Vec::new());
521                 }
522
523                 Self { tx }
524         }
525
526         /// Get the txid of the local commitment transaction contained in this
527         /// LocalCommitmentTransaction
528         pub fn txid(&self) -> Sha256dHash {
529                 self.tx.txid()
530         }
531
532         /// Check if LocalCommitmentTransaction has already been signed by us
533         pub fn has_local_sig(&self) -> bool {
534                 if self.tx.input.len() != 1 { panic!("Commitment transactions must have input count == 1!"); }
535                 if self.tx.input[0].witness.len() == 4 {
536                         assert!(!self.tx.input[0].witness[1].is_empty());
537                         assert!(!self.tx.input[0].witness[2].is_empty());
538                         true
539                 } else {
540                         assert_eq!(self.tx.input[0].witness.len(), 3);
541                         assert!(self.tx.input[0].witness[0].is_empty());
542                         assert!(self.tx.input[0].witness[1].is_empty() || self.tx.input[0].witness[2].is_empty());
543                         false
544                 }
545         }
546
547         /// Add local signature for LocalCommitmentTransaction, do nothing if signature is already
548         /// present
549         ///
550         /// Funding key is your key included in the 2-2 funding_outpoint lock. Should be provided
551         /// by your ChannelKeys.
552         /// Funding redeemscript is script locking funding_outpoint. This is the mutlsig script
553         /// between your own funding key and your counterparty's. Currently, this is provided in
554         /// ChannelKeys::sign_local_commitment() calls directly.
555         /// Channel value is amount locked in funding_outpoint.
556         pub fn add_local_sig<T: secp256k1::Signing>(&mut self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) {
557                 if self.has_local_sig() { return; }
558                 let sighash = hash_to_message!(&bip143::SighashComponents::new(&self.tx)
559                         .sighash_all(&self.tx.input[0], funding_redeemscript, channel_value_satoshis)[..]);
560                 let our_sig = secp_ctx.sign(&sighash, funding_key);
561
562                 if self.tx.input[0].witness[1].is_empty() {
563                         self.tx.input[0].witness[1] = our_sig.serialize_der().to_vec();
564                         self.tx.input[0].witness[1].push(SigHashType::All as u8);
565                 } else {
566                         self.tx.input[0].witness[2] = our_sig.serialize_der().to_vec();
567                         self.tx.input[0].witness[2].push(SigHashType::All as u8);
568                 }
569
570                 self.tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
571         }
572
573         /// Get raw transaction without asserting if witness is complete
574         pub(crate) fn without_valid_witness(&self) -> &Transaction { &self.tx }
575         /// Get raw transaction with panics if witness is incomplete
576         pub fn with_valid_witness(&self) -> &Transaction {
577                 assert!(self.has_local_sig());
578                 &self.tx
579         }
580 }
581 impl PartialEq for LocalCommitmentTransaction {
582         // We dont care whether we are signed in equality comparison
583         fn eq(&self, o: &Self) -> bool {
584                 self.txid() == o.txid()
585         }
586 }
587 impl Writeable for LocalCommitmentTransaction {
588         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
589                 if let Err(e) = self.tx.consensus_encode(&mut WriterWriteAdaptor(writer)) {
590                         match e {
591                                 encode::Error::Io(e) => return Err(e),
592                                 _ => panic!("local tx must have been well-formed!"),
593                         }
594                 }
595                 Ok(())
596         }
597 }
598 impl Readable for LocalCommitmentTransaction {
599         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
600                 let tx = match Transaction::consensus_decode(reader.by_ref()) {
601                         Ok(tx) => tx,
602                         Err(e) => match e {
603                                 encode::Error::Io(ioe) => return Err(DecodeError::Io(ioe)),
604                                 _ => return Err(DecodeError::InvalidValue),
605                         },
606                 };
607
608                 if tx.input.len() != 1 {
609                         // Ensure tx didn't hit the 0-input ambiguity case.
610                         return Err(DecodeError::InvalidValue);
611                 }
612                 Ok(Self { tx })
613         }
614 }
615
616 #[cfg(test)]
617 mod tests {
618         use super::CounterpartyCommitmentSecrets;
619         use hex;
620
621         #[test]
622         fn test_per_commitment_storage() {
623                 // Test vectors from BOLT 3:
624                 let mut secrets: Vec<[u8; 32]> = Vec::new();
625                 let mut monitor;
626
627                 macro_rules! test_secrets {
628                         () => {
629                                 let mut idx = 281474976710655;
630                                 for secret in secrets.iter() {
631                                         assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
632                                         idx -= 1;
633                                 }
634                                 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
635                                 assert!(monitor.get_secret(idx).is_none());
636                         };
637                 }
638
639                 {
640                         // insert_secret correct sequence
641                         monitor = CounterpartyCommitmentSecrets::new();
642                         secrets.clear();
643
644                         secrets.push([0; 32]);
645                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
646                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
647                         test_secrets!();
648
649                         secrets.push([0; 32]);
650                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
651                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
652                         test_secrets!();
653
654                         secrets.push([0; 32]);
655                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
656                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
657                         test_secrets!();
658
659                         secrets.push([0; 32]);
660                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
661                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
662                         test_secrets!();
663
664                         secrets.push([0; 32]);
665                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
666                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
667                         test_secrets!();
668
669                         secrets.push([0; 32]);
670                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
671                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
672                         test_secrets!();
673
674                         secrets.push([0; 32]);
675                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
676                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
677                         test_secrets!();
678
679                         secrets.push([0; 32]);
680                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
681                         monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
682                         test_secrets!();
683                 }
684
685                 {
686                         // insert_secret #1 incorrect
687                         monitor = CounterpartyCommitmentSecrets::new();
688                         secrets.clear();
689
690                         secrets.push([0; 32]);
691                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
692                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
693                         test_secrets!();
694
695                         secrets.push([0; 32]);
696                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
697                         assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
698                 }
699
700                 {
701                         // insert_secret #2 incorrect (#1 derived from incorrect)
702                         monitor = CounterpartyCommitmentSecrets::new();
703                         secrets.clear();
704
705                         secrets.push([0; 32]);
706                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
707                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
708                         test_secrets!();
709
710                         secrets.push([0; 32]);
711                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
712                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
713                         test_secrets!();
714
715                         secrets.push([0; 32]);
716                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
717                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
718                         test_secrets!();
719
720                         secrets.push([0; 32]);
721                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
722                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
723                 }
724
725                 {
726                         // insert_secret #3 incorrect
727                         monitor = CounterpartyCommitmentSecrets::new();
728                         secrets.clear();
729
730                         secrets.push([0; 32]);
731                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
732                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
733                         test_secrets!();
734
735                         secrets.push([0; 32]);
736                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
737                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
738                         test_secrets!();
739
740                         secrets.push([0; 32]);
741                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
742                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
743                         test_secrets!();
744
745                         secrets.push([0; 32]);
746                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
747                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
748                 }
749
750                 {
751                         // insert_secret #4 incorrect (1,2,3 derived from incorrect)
752                         monitor = CounterpartyCommitmentSecrets::new();
753                         secrets.clear();
754
755                         secrets.push([0; 32]);
756                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
757                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
758                         test_secrets!();
759
760                         secrets.push([0; 32]);
761                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
762                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
763                         test_secrets!();
764
765                         secrets.push([0; 32]);
766                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
767                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
768                         test_secrets!();
769
770                         secrets.push([0; 32]);
771                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
772                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
773                         test_secrets!();
774
775                         secrets.push([0; 32]);
776                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
777                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
778                         test_secrets!();
779
780                         secrets.push([0; 32]);
781                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
782                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
783                         test_secrets!();
784
785                         secrets.push([0; 32]);
786                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
787                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
788                         test_secrets!();
789
790                         secrets.push([0; 32]);
791                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
792                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
793                 }
794
795                 {
796                         // insert_secret #5 incorrect
797                         monitor = CounterpartyCommitmentSecrets::new();
798                         secrets.clear();
799
800                         secrets.push([0; 32]);
801                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
802                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
803                         test_secrets!();
804
805                         secrets.push([0; 32]);
806                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
807                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
808                         test_secrets!();
809
810                         secrets.push([0; 32]);
811                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
812                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
813                         test_secrets!();
814
815                         secrets.push([0; 32]);
816                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
817                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
818                         test_secrets!();
819
820                         secrets.push([0; 32]);
821                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
822                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
823                         test_secrets!();
824
825                         secrets.push([0; 32]);
826                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
827                         assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
828                 }
829
830                 {
831                         // insert_secret #6 incorrect (5 derived from incorrect)
832                         monitor = CounterpartyCommitmentSecrets::new();
833                         secrets.clear();
834
835                         secrets.push([0; 32]);
836                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
837                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
838                         test_secrets!();
839
840                         secrets.push([0; 32]);
841                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
842                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
843                         test_secrets!();
844
845                         secrets.push([0; 32]);
846                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
847                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
848                         test_secrets!();
849
850                         secrets.push([0; 32]);
851                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
852                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
853                         test_secrets!();
854
855                         secrets.push([0; 32]);
856                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
857                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
858                         test_secrets!();
859
860                         secrets.push([0; 32]);
861                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
862                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
863                         test_secrets!();
864
865                         secrets.push([0; 32]);
866                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
867                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
868                         test_secrets!();
869
870                         secrets.push([0; 32]);
871                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
872                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
873                 }
874
875                 {
876                         // insert_secret #7 incorrect
877                         monitor = CounterpartyCommitmentSecrets::new();
878                         secrets.clear();
879
880                         secrets.push([0; 32]);
881                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
882                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
883                         test_secrets!();
884
885                         secrets.push([0; 32]);
886                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
887                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
888                         test_secrets!();
889
890                         secrets.push([0; 32]);
891                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
892                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
893                         test_secrets!();
894
895                         secrets.push([0; 32]);
896                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
897                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
898                         test_secrets!();
899
900                         secrets.push([0; 32]);
901                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
902                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
903                         test_secrets!();
904
905                         secrets.push([0; 32]);
906                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
907                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
908                         test_secrets!();
909
910                         secrets.push([0; 32]);
911                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
912                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
913                         test_secrets!();
914
915                         secrets.push([0; 32]);
916                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
917                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
918                 }
919
920                 {
921                         // insert_secret #8 incorrect
922                         monitor = CounterpartyCommitmentSecrets::new();
923                         secrets.clear();
924
925                         secrets.push([0; 32]);
926                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
927                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
928                         test_secrets!();
929
930                         secrets.push([0; 32]);
931                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
932                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
933                         test_secrets!();
934
935                         secrets.push([0; 32]);
936                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
937                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
938                         test_secrets!();
939
940                         secrets.push([0; 32]);
941                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
942                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
943                         test_secrets!();
944
945                         secrets.push([0; 32]);
946                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
947                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
948                         test_secrets!();
949
950                         secrets.push([0; 32]);
951                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
952                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
953                         test_secrets!();
954
955                         secrets.push([0; 32]);
956                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
957                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
958                         test_secrets!();
959
960                         secrets.push([0; 32]);
961                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
962                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
963                 }
964         }
965 }