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