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