Adopting (W)PubkeyHash types
[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 payment key) from the base
175 /// private key for that type of key and the per_commitment_point (available in TxCreationKeys)
176 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> Result<SecretKey, secp256k1::Error> {
177         let mut sha = Sha256::engine();
178         sha.input(&per_commitment_point.serialize());
179         sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
180         let res = Sha256::from_engine(sha).into_inner();
181
182         let mut key = base_secret.clone();
183         key.add_assign(&res)?;
184         Ok(key)
185 }
186
187 pub(super) fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> Result<PublicKey, secp256k1::Error> {
188         let mut sha = Sha256::engine();
189         sha.input(&per_commitment_point.serialize());
190         sha.input(&base_point.serialize());
191         let res = Sha256::from_engine(sha).into_inner();
192
193         let hashkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&res)?);
194         base_point.combine(&hashkey)
195 }
196
197 /// Derives a revocation key from its constituent parts.
198 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
199 /// generated (ie our own).
200 pub(super) fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_secret: &SecretKey, revocation_base_secret: &SecretKey) -> Result<SecretKey, secp256k1::Error> {
201         let revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &revocation_base_secret);
202         let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
203
204         let rev_append_commit_hash_key = {
205                 let mut sha = Sha256::engine();
206                 sha.input(&revocation_base_point.serialize());
207                 sha.input(&per_commitment_point.serialize());
208
209                 Sha256::from_engine(sha).into_inner()
210         };
211         let commit_append_rev_hash_key = {
212                 let mut sha = Sha256::engine();
213                 sha.input(&per_commitment_point.serialize());
214                 sha.input(&revocation_base_point.serialize());
215
216                 Sha256::from_engine(sha).into_inner()
217         };
218
219         let mut part_a = revocation_base_secret.clone();
220         part_a.mul_assign(&rev_append_commit_hash_key)?;
221         let mut part_b = per_commitment_secret.clone();
222         part_b.mul_assign(&commit_append_rev_hash_key)?;
223         part_a.add_assign(&part_b[..])?;
224         Ok(part_a)
225 }
226
227 pub(super) fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, revocation_base_point: &PublicKey) -> Result<PublicKey, secp256k1::Error> {
228         let rev_append_commit_hash_key = {
229                 let mut sha = Sha256::engine();
230                 sha.input(&revocation_base_point.serialize());
231                 sha.input(&per_commitment_point.serialize());
232
233                 Sha256::from_engine(sha).into_inner()
234         };
235         let commit_append_rev_hash_key = {
236                 let mut sha = Sha256::engine();
237                 sha.input(&per_commitment_point.serialize());
238                 sha.input(&revocation_base_point.serialize());
239
240                 Sha256::from_engine(sha).into_inner()
241         };
242
243         let mut part_a = revocation_base_point.clone();
244         part_a.mul_assign(&secp_ctx, &rev_append_commit_hash_key)?;
245         let mut part_b = per_commitment_point.clone();
246         part_b.mul_assign(&secp_ctx, &commit_append_rev_hash_key)?;
247         part_a.combine(&part_b)
248 }
249
250 /// The set of public keys which are used in the creation of one commitment transaction.
251 /// These are derived from the channel base keys and per-commitment data.
252 #[derive(PartialEq, Clone)]
253 pub struct TxCreationKeys {
254         /// The per-commitment public key which was used to derive the other keys.
255         pub per_commitment_point: PublicKey,
256         /// The revocation key which is used to allow the owner of the commitment transaction to
257         /// provide their counterparty the ability to punish them if they broadcast an old state.
258         pub(crate) revocation_key: PublicKey,
259         /// A's HTLC Key
260         pub(crate) a_htlc_key: PublicKey,
261         /// B's HTLC Key
262         pub(crate) b_htlc_key: PublicKey,
263         /// A's Payment Key (which isn't allowed to be spent from for some delay)
264         pub(crate) a_delayed_payment_key: PublicKey,
265         /// B's Payment Key
266         pub(crate) b_payment_key: PublicKey,
267 }
268 impl_writeable!(TxCreationKeys, 33*6,
269         { per_commitment_point, revocation_key, a_htlc_key, b_htlc_key, a_delayed_payment_key, b_payment_key });
270
271 /// One counterparty's public keys which do not change over the life of a channel.
272 #[derive(Clone, PartialEq)]
273 pub struct ChannelPublicKeys {
274         /// The public key which is used to sign all commitment transactions, as it appears in the
275         /// on-chain channel lock-in 2-of-2 multisig output.
276         pub funding_pubkey: PublicKey,
277         /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
278         /// revocation keys. The per-commitment revocation private key is then revealed by the owner of
279         /// a commitment transaction so that their counterparty can claim all available funds if they
280         /// broadcast an old state.
281         pub revocation_basepoint: PublicKey,
282         /// The base point which is used (with derive_public_key) to derive a per-commitment payment
283         /// public key which receives immediately-spendable non-HTLC-encumbered funds.
284         pub payment_basepoint: PublicKey,
285         /// The base point which is used (with derive_public_key) to derive a per-commitment payment
286         /// public key which receives non-HTLC-encumbered funds which are only available for spending
287         /// after some delay (or can be claimed via the revocation path).
288         pub delayed_payment_basepoint: PublicKey,
289         /// The base point which is used (with derive_public_key) to derive a per-commitment public key
290         /// which is used to encumber HTLC-in-flight outputs.
291         pub htlc_basepoint: PublicKey,
292 }
293
294 impl_writeable!(ChannelPublicKeys, 33*5, {
295         funding_pubkey,
296         revocation_basepoint,
297         payment_basepoint,
298         delayed_payment_basepoint,
299         htlc_basepoint
300 });
301
302
303 impl TxCreationKeys {
304         pub(crate) fn new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, a_delayed_payment_base: &PublicKey, a_htlc_base: &PublicKey, b_revocation_base: &PublicKey, b_payment_base: &PublicKey, b_htlc_base: &PublicKey) -> Result<TxCreationKeys, secp256k1::Error> {
305                 Ok(TxCreationKeys {
306                         per_commitment_point: per_commitment_point.clone(),
307                         revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &b_revocation_base)?,
308                         a_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_htlc_base)?,
309                         b_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_htlc_base)?,
310                         a_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_delayed_payment_base)?,
311                         b_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_payment_base)?,
312                 })
313         }
314 }
315
316 /// Gets the "to_local" output redeemscript, ie the script which is time-locked or spendable by
317 /// the revocation key
318 pub(super) fn get_revokeable_redeemscript(revocation_key: &PublicKey, to_self_delay: u16, delayed_payment_key: &PublicKey) -> Script {
319         Builder::new().push_opcode(opcodes::all::OP_IF)
320                       .push_slice(&revocation_key.serialize())
321                       .push_opcode(opcodes::all::OP_ELSE)
322                       .push_int(to_self_delay as i64)
323                       .push_opcode(opcodes::all::OP_CSV)
324                       .push_opcode(opcodes::all::OP_DROP)
325                       .push_slice(&delayed_payment_key.serialize())
326                       .push_opcode(opcodes::all::OP_ENDIF)
327                       .push_opcode(opcodes::all::OP_CHECKSIG)
328                       .into_script()
329 }
330
331 #[derive(Clone, PartialEq)]
332 /// Information about an HTLC as it appears in a commitment transaction
333 pub struct HTLCOutputInCommitment {
334         /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
335         /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
336         /// need to compare this value to whether the commitment transaction in question is that of
337         /// the remote party or our own.
338         pub offered: bool,
339         /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
340         /// this divided by 1000.
341         pub amount_msat: u64,
342         /// The CLTV lock-time at which this HTLC expires.
343         pub cltv_expiry: u32,
344         /// The hash of the preimage which unlocks this HTLC.
345         pub payment_hash: PaymentHash,
346         /// The position within the commitment transactions' outputs. This may be None if the value is
347         /// below the dust limit (in which case no output appears in the commitment transaction and the
348         /// value is spent to additional transaction fees).
349         pub transaction_output_index: Option<u32>,
350 }
351
352 impl_writeable!(HTLCOutputInCommitment, 1 + 8 + 4 + 32 + 5, {
353         offered,
354         amount_msat,
355         cltv_expiry,
356         payment_hash,
357         transaction_output_index
358 });
359
360 #[inline]
361 pub(crate) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, a_htlc_key: &PublicKey, b_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
362         let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
363         if htlc.offered {
364                 Builder::new().push_opcode(opcodes::all::OP_DUP)
365                               .push_opcode(opcodes::all::OP_HASH160)
366                               .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
367                               .push_opcode(opcodes::all::OP_EQUAL)
368                               .push_opcode(opcodes::all::OP_IF)
369                               .push_opcode(opcodes::all::OP_CHECKSIG)
370                               .push_opcode(opcodes::all::OP_ELSE)
371                               .push_slice(&b_htlc_key.serialize()[..])
372                               .push_opcode(opcodes::all::OP_SWAP)
373                               .push_opcode(opcodes::all::OP_SIZE)
374                               .push_int(32)
375                               .push_opcode(opcodes::all::OP_EQUAL)
376                               .push_opcode(opcodes::all::OP_NOTIF)
377                               .push_opcode(opcodes::all::OP_DROP)
378                               .push_int(2)
379                               .push_opcode(opcodes::all::OP_SWAP)
380                               .push_slice(&a_htlc_key.serialize()[..])
381                               .push_int(2)
382                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
383                               .push_opcode(opcodes::all::OP_ELSE)
384                               .push_opcode(opcodes::all::OP_HASH160)
385                               .push_slice(&payment_hash160)
386                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
387                               .push_opcode(opcodes::all::OP_CHECKSIG)
388                               .push_opcode(opcodes::all::OP_ENDIF)
389                               .push_opcode(opcodes::all::OP_ENDIF)
390                               .into_script()
391         } else {
392                 Builder::new().push_opcode(opcodes::all::OP_DUP)
393                               .push_opcode(opcodes::all::OP_HASH160)
394                               .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
395                               .push_opcode(opcodes::all::OP_EQUAL)
396                               .push_opcode(opcodes::all::OP_IF)
397                               .push_opcode(opcodes::all::OP_CHECKSIG)
398                               .push_opcode(opcodes::all::OP_ELSE)
399                               .push_slice(&b_htlc_key.serialize()[..])
400                               .push_opcode(opcodes::all::OP_SWAP)
401                               .push_opcode(opcodes::all::OP_SIZE)
402                               .push_int(32)
403                               .push_opcode(opcodes::all::OP_EQUAL)
404                               .push_opcode(opcodes::all::OP_IF)
405                               .push_opcode(opcodes::all::OP_HASH160)
406                               .push_slice(&payment_hash160)
407                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
408                               .push_int(2)
409                               .push_opcode(opcodes::all::OP_SWAP)
410                               .push_slice(&a_htlc_key.serialize()[..])
411                               .push_int(2)
412                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
413                               .push_opcode(opcodes::all::OP_ELSE)
414                               .push_opcode(opcodes::all::OP_DROP)
415                               .push_int(htlc.cltv_expiry as i64)
416                               .push_opcode(opcodes::all::OP_CLTV)
417                               .push_opcode(opcodes::all::OP_DROP)
418                               .push_opcode(opcodes::all::OP_CHECKSIG)
419                               .push_opcode(opcodes::all::OP_ENDIF)
420                               .push_opcode(opcodes::all::OP_ENDIF)
421                               .into_script()
422         }
423 }
424
425 /// note here that 'a_revocation_key' is generated using b_revocation_basepoint and a's
426 /// commitment secret. 'htlc' does *not* need to have its previous_output_index filled.
427 #[inline]
428 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, keys: &TxCreationKeys) -> Script {
429         get_htlc_redeemscript_with_explicit_keys(htlc, &keys.a_htlc_key, &keys.b_htlc_key, &keys.revocation_key)
430 }
431
432 /// Gets the redeemscript for a funding output from the two funding public keys.
433 /// Note that the order of funding public keys does not matter.
434 pub fn make_funding_redeemscript(a: &PublicKey, b: &PublicKey) -> Script {
435         let our_funding_key = a.serialize();
436         let their_funding_key = b.serialize();
437
438         let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
439         if our_funding_key[..] < their_funding_key[..] {
440                 builder.push_slice(&our_funding_key)
441                         .push_slice(&their_funding_key)
442         } else {
443                 builder.push_slice(&their_funding_key)
444                         .push_slice(&our_funding_key)
445         }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
446 }
447
448 /// panics if htlc.transaction_output_index.is_none()!
449 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 {
450         let mut txins: Vec<TxIn> = Vec::new();
451         txins.push(TxIn {
452                 previous_output: OutPoint {
453                         txid: prev_hash.clone(),
454                         vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
455                 },
456                 script_sig: Script::new(),
457                 sequence: 0,
458                 witness: Vec::new(),
459         });
460
461         let total_fee = if htlc.offered {
462                         feerate_per_kw * HTLC_TIMEOUT_TX_WEIGHT / 1000
463                 } else {
464                         feerate_per_kw * HTLC_SUCCESS_TX_WEIGHT / 1000
465                 };
466
467         let mut txouts: Vec<TxOut> = Vec::new();
468         txouts.push(TxOut {
469                 script_pubkey: get_revokeable_redeemscript(revocation_key, to_self_delay, a_delayed_payment_key).to_v0_p2wsh(),
470                 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)
471         });
472
473         Transaction {
474                 version: 2,
475                 lock_time: if htlc.offered { htlc.cltv_expiry } else { 0 },
476                 input: txins,
477                 output: txouts,
478         }
479 }
480
481 #[derive(Clone)]
482 /// We use this to track local commitment transactions and put off signing them until we are ready
483 /// to broadcast. Eventually this will require a signer which is possibly external, but for now we
484 /// just pass in the SecretKeys required.
485 pub struct LocalCommitmentTransaction {
486         // TODO: We should migrate away from providing the transaction, instead providing enough to
487         // allow the ChannelKeys to construct it from scratch. Luckily we already have HTLC data here,
488         // so we're probably most of the way there.
489         /// The commitment transaction itself, in unsigned form.
490         pub unsigned_tx: Transaction,
491         /// Our counterparty's signature for the transaction, above.
492         pub their_sig: Signature,
493         // Which order the signatures should go in when constructing the final commitment tx witness.
494         // The user should be able to reconstruc this themselves, so we don't bother to expose it.
495         our_sig_first: bool,
496         /// The key derivation parameters for this commitment transaction
497         pub local_keys: TxCreationKeys,
498         /// The feerate paid per 1000-weight-unit in this commitment transaction. This value is
499         /// controlled by the channel initiator.
500         pub feerate_per_kw: u64,
501         /// The HTLCs and remote htlc signatures which were included in this commitment transaction.
502         ///
503         /// Note that this includes all HTLCs, including ones which were considered dust and not
504         /// actually included in the transaction as it appears on-chain, but who's value is burned as
505         /// fees and not included in the to_local or to_remote outputs.
506         ///
507         /// The remote HTLC signatures in the second element will always be set for non-dust HTLCs, ie
508         /// those for which transaction_output_index.is_some().
509         pub per_htlc: Vec<(HTLCOutputInCommitment, Option<Signature>)>,
510 }
511 impl LocalCommitmentTransaction {
512         #[cfg(test)]
513         pub fn dummy() -> Self {
514                 let dummy_input = TxIn {
515                         previous_output: OutPoint {
516                                 txid: Default::default(),
517                                 vout: 0,
518                         },
519                         script_sig: Default::default(),
520                         sequence: 0,
521                         witness: vec![]
522                 };
523                 let dummy_key = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&[42; 32]).unwrap());
524                 let dummy_sig = Secp256k1::new().sign(&secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
525                 Self {
526                         unsigned_tx: Transaction {
527                                 version: 2,
528                                 input: vec![dummy_input],
529                                 output: Vec::new(),
530                                 lock_time: 0,
531                         },
532                         their_sig: dummy_sig,
533                         our_sig_first: false,
534                         local_keys: TxCreationKeys {
535                                         per_commitment_point: dummy_key.clone(),
536                                         revocation_key: dummy_key.clone(),
537                                         a_htlc_key: dummy_key.clone(),
538                                         b_htlc_key: dummy_key.clone(),
539                                         a_delayed_payment_key: dummy_key.clone(),
540                                         b_payment_key: dummy_key.clone(),
541                                 },
542                         feerate_per_kw: 0,
543                         per_htlc: Vec::new()
544                 }
545         }
546
547         /// Generate a new LocalCommitmentTransaction based on a raw commitment transaction,
548         /// remote signature and both parties keys
549         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 {
550                 if unsigned_tx.input.len() != 1 { panic!("Tried to store a commitment transaction that had input count != 1!"); }
551                 if unsigned_tx.input[0].witness.len() != 0 { panic!("Tried to store a signed commitment transaction?"); }
552
553                 Self {
554                         unsigned_tx,
555                         their_sig,
556                         our_sig_first: our_funding_key.serialize()[..] < their_funding_key.serialize()[..],
557                         local_keys,
558                         feerate_per_kw,
559                         per_htlc: htlc_data,
560                 }
561         }
562
563         /// Get the txid of the local commitment transaction contained in this
564         /// LocalCommitmentTransaction
565         pub fn txid(&self) -> Txid {
566                 self.unsigned_tx.txid()
567         }
568
569         /// Gets our signature for the contained commitment transaction given our funding private key.
570         ///
571         /// Funding key is your key included in the 2-2 funding_outpoint lock. Should be provided
572         /// by your ChannelKeys.
573         /// Funding redeemscript is script locking funding_outpoint. This is the mutlsig script
574         /// between your own funding key and your counterparty's. Currently, this is provided in
575         /// ChannelKeys::sign_local_commitment() calls directly.
576         /// Channel value is amount locked in funding_outpoint.
577         pub fn get_local_sig<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
578                 let sighash = hash_to_message!(&bip143::SighashComponents::new(&self.unsigned_tx)
579                         .sighash_all(&self.unsigned_tx.input[0], funding_redeemscript, channel_value_satoshis)[..]);
580                 secp_ctx.sign(&sighash, funding_key)
581         }
582
583         pub(crate) fn add_local_sig(&self, funding_redeemscript: &Script, our_sig: Signature) -> Transaction {
584                 let mut tx = self.unsigned_tx.clone();
585                 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
586                 tx.input[0].witness.push(Vec::new());
587
588                 if self.our_sig_first {
589                         tx.input[0].witness.push(our_sig.serialize_der().to_vec());
590                         tx.input[0].witness.push(self.their_sig.serialize_der().to_vec());
591                 } else {
592                         tx.input[0].witness.push(self.their_sig.serialize_der().to_vec());
593                         tx.input[0].witness.push(our_sig.serialize_der().to_vec());
594                 }
595                 tx.input[0].witness[1].push(SigHashType::All as u8);
596                 tx.input[0].witness[2].push(SigHashType::All as u8);
597
598                 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
599                 tx
600         }
601
602         /// Get a signature for each HTLC which was included in the commitment transaction (ie for
603         /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
604         ///
605         /// The returned Vec has one entry for each HTLC, and in the same order. For HTLCs which were
606         /// considered dust and not included, a None entry exists, for all others a signature is
607         /// included.
608         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>>, ()> {
609                 let txid = self.txid();
610                 let mut ret = Vec::with_capacity(self.per_htlc.len());
611                 let our_htlc_key = derive_private_key(secp_ctx, &self.local_keys.per_commitment_point, htlc_base_key).map_err(|_| ())?;
612
613                 for this_htlc in self.per_htlc.iter() {
614                         if this_htlc.0.transaction_output_index.is_some() {
615                                 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);
616
617                                 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);
618
619                                 let sighash = hash_to_message!(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, this_htlc.0.amount_msat / 1000)[..]);
620                                 ret.push(Some(secp_ctx.sign(&sighash, &our_htlc_key)));
621                         } else {
622                                 ret.push(None);
623                         }
624                 }
625                 Ok(ret)
626         }
627
628         /// Gets a signed HTLC transaction given a preimage (for !htlc.offered) and the local HTLC transaction signature.
629         pub(crate) fn get_signed_htlc_tx(&self, htlc_index: usize, signature: &Signature, preimage: &Option<PaymentPreimage>, local_csv: u16) -> Transaction {
630                 let txid = self.txid();
631                 let this_htlc = &self.per_htlc[htlc_index];
632                 assert!(this_htlc.0.transaction_output_index.is_some());
633                 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
634                 if !this_htlc.0.offered && preimage.is_none() { unreachable!(); }
635                 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
636                 if  this_htlc.0.offered && preimage.is_some() { unreachable!(); }
637
638                 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);
639                 // Channel should have checked that we have a remote signature for this HTLC at
640                 // creation, and we should have a sensible htlc transaction:
641                 assert!(this_htlc.1.is_some());
642
643                 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);
644
645                 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
646                 htlc_tx.input[0].witness.push(Vec::new());
647
648                 htlc_tx.input[0].witness.push(this_htlc.1.unwrap().serialize_der().to_vec());
649                 htlc_tx.input[0].witness.push(signature.serialize_der().to_vec());
650                 htlc_tx.input[0].witness[1].push(SigHashType::All as u8);
651                 htlc_tx.input[0].witness[2].push(SigHashType::All as u8);
652
653                 if this_htlc.0.offered {
654                         // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
655                         htlc_tx.input[0].witness.push(Vec::new());
656                 } else {
657                         htlc_tx.input[0].witness.push(preimage.unwrap().0.to_vec());
658                 }
659
660                 htlc_tx.input[0].witness.push(htlc_redeemscript.as_bytes().to_vec());
661                 htlc_tx
662         }
663 }
664 impl PartialEq for LocalCommitmentTransaction {
665         // We dont care whether we are signed in equality comparison
666         fn eq(&self, o: &Self) -> bool {
667                 self.txid() == o.txid()
668         }
669 }
670 impl Writeable for LocalCommitmentTransaction {
671         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
672                 if let Err(e) = self.unsigned_tx.consensus_encode(&mut WriterWriteAdaptor(writer)) {
673                         match e {
674                                 encode::Error::Io(e) => return Err(e),
675                                 _ => panic!("local tx must have been well-formed!"),
676                         }
677                 }
678                 self.their_sig.write(writer)?;
679                 self.our_sig_first.write(writer)?;
680                 self.local_keys.write(writer)?;
681                 self.feerate_per_kw.write(writer)?;
682                 writer.write_all(&byte_utils::be64_to_array(self.per_htlc.len() as u64))?;
683                 for &(ref htlc, ref sig) in self.per_htlc.iter() {
684                         htlc.write(writer)?;
685                         sig.write(writer)?;
686                 }
687                 Ok(())
688         }
689 }
690 impl Readable for LocalCommitmentTransaction {
691         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
692                 let unsigned_tx = match Transaction::consensus_decode(reader.by_ref()) {
693                         Ok(tx) => tx,
694                         Err(e) => match e {
695                                 encode::Error::Io(ioe) => return Err(DecodeError::Io(ioe)),
696                                 _ => return Err(DecodeError::InvalidValue),
697                         },
698                 };
699                 let their_sig = Readable::read(reader)?;
700                 let our_sig_first = Readable::read(reader)?;
701                 let local_keys = Readable::read(reader)?;
702                 let feerate_per_kw = Readable::read(reader)?;
703                 let htlcs_count: u64 = Readable::read(reader)?;
704                 let mut per_htlc = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / mem::size_of::<(HTLCOutputInCommitment, Option<Signature>)>()));
705                 for _ in 0..htlcs_count {
706                         let htlc: HTLCOutputInCommitment = Readable::read(reader)?;
707                         let sigs = Readable::read(reader)?;
708                         per_htlc.push((htlc, sigs));
709                 }
710
711                 if unsigned_tx.input.len() != 1 {
712                         // Ensure tx didn't hit the 0-input ambiguity case.
713                         return Err(DecodeError::InvalidValue);
714                 }
715                 Ok(Self {
716                         unsigned_tx,
717                         their_sig,
718                         our_sig_first,
719                         local_keys,
720                         feerate_per_kw,
721                         per_htlc,
722                 })
723         }
724 }
725
726 #[cfg(test)]
727 mod tests {
728         use super::CounterpartyCommitmentSecrets;
729         use hex;
730
731         #[test]
732         fn test_per_commitment_storage() {
733                 // Test vectors from BOLT 3:
734                 let mut secrets: Vec<[u8; 32]> = Vec::new();
735                 let mut monitor;
736
737                 macro_rules! test_secrets {
738                         () => {
739                                 let mut idx = 281474976710655;
740                                 for secret in secrets.iter() {
741                                         assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
742                                         idx -= 1;
743                                 }
744                                 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
745                                 assert!(monitor.get_secret(idx).is_none());
746                         };
747                 }
748
749                 {
750                         // insert_secret correct sequence
751                         monitor = CounterpartyCommitmentSecrets::new();
752                         secrets.clear();
753
754                         secrets.push([0; 32]);
755                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
756                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
757                         test_secrets!();
758
759                         secrets.push([0; 32]);
760                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
761                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
762                         test_secrets!();
763
764                         secrets.push([0; 32]);
765                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
766                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
767                         test_secrets!();
768
769                         secrets.push([0; 32]);
770                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
771                         monitor.provide_secret(281474976710652, 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("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
776                         monitor.provide_secret(281474976710651, 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("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
781                         monitor.provide_secret(281474976710650, 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("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
786                         monitor.provide_secret(281474976710649, 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("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
791                         monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
792                         test_secrets!();
793                 }
794
795                 {
796                         // insert_secret #1 incorrect
797                         monitor = CounterpartyCommitmentSecrets::new();
798                         secrets.clear();
799
800                         secrets.push([0; 32]);
801                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
802                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
803                         test_secrets!();
804
805                         secrets.push([0; 32]);
806                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
807                         assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
808                 }
809
810                 {
811                         // insert_secret #2 incorrect (#1 derived from 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("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
822                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
823                         test_secrets!();
824
825                         secrets.push([0; 32]);
826                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
827                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
828                         test_secrets!();
829
830                         secrets.push([0; 32]);
831                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
832                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
833                 }
834
835                 {
836                         // insert_secret #3 incorrect
837                         monitor = CounterpartyCommitmentSecrets::new();
838                         secrets.clear();
839
840                         secrets.push([0; 32]);
841                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
842                         monitor.provide_secret(281474976710655, 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("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
847                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
848                         test_secrets!();
849
850                         secrets.push([0; 32]);
851                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
852                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
853                         test_secrets!();
854
855                         secrets.push([0; 32]);
856                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
857                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
858                 }
859
860                 {
861                         // insert_secret #4 incorrect (1,2,3 derived from incorrect)
862                         monitor = CounterpartyCommitmentSecrets::new();
863                         secrets.clear();
864
865                         secrets.push([0; 32]);
866                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
867                         monitor.provide_secret(281474976710655, 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("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
872                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
873                         test_secrets!();
874
875                         secrets.push([0; 32]);
876                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
877                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
878                         test_secrets!();
879
880                         secrets.push([0; 32]);
881                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
882                         monitor.provide_secret(281474976710652, 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("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
887                         monitor.provide_secret(281474976710651, 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("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
892                         monitor.provide_secret(281474976710650, 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("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
897                         monitor.provide_secret(281474976710649, 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("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
902                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
903                 }
904
905                 {
906                         // insert_secret #5 incorrect
907                         monitor = CounterpartyCommitmentSecrets::new();
908                         secrets.clear();
909
910                         secrets.push([0; 32]);
911                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
912                         monitor.provide_secret(281474976710655, 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("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
917                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
918                         test_secrets!();
919
920                         secrets.push([0; 32]);
921                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
922                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
923                         test_secrets!();
924
925                         secrets.push([0; 32]);
926                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
927                         monitor.provide_secret(281474976710652, 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("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
932                         monitor.provide_secret(281474976710651, 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("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
937                         assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
938                 }
939
940                 {
941                         // insert_secret #6 incorrect (5 derived from incorrect)
942                         monitor = CounterpartyCommitmentSecrets::new();
943                         secrets.clear();
944
945                         secrets.push([0; 32]);
946                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
947                         monitor.provide_secret(281474976710655, 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("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
952                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
953                         test_secrets!();
954
955                         secrets.push([0; 32]);
956                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
957                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
958                         test_secrets!();
959
960                         secrets.push([0; 32]);
961                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
962                         monitor.provide_secret(281474976710652, 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("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
967                         monitor.provide_secret(281474976710651, 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("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
972                         monitor.provide_secret(281474976710650, 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("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
977                         monitor.provide_secret(281474976710649, 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("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
982                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
983                 }
984
985                 {
986                         // insert_secret #7 incorrect
987                         monitor = CounterpartyCommitmentSecrets::new();
988                         secrets.clear();
989
990                         secrets.push([0; 32]);
991                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
992                         monitor.provide_secret(281474976710655, 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("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
997                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
998                         test_secrets!();
999
1000                         secrets.push([0; 32]);
1001                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1002                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1003                         test_secrets!();
1004
1005                         secrets.push([0; 32]);
1006                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1007                         monitor.provide_secret(281474976710652, 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("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1012                         monitor.provide_secret(281474976710651, 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("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1017                         monitor.provide_secret(281474976710650, 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("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
1022                         monitor.provide_secret(281474976710649, 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("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1027                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1028                 }
1029
1030                 {
1031                         // insert_secret #8 incorrect
1032                         monitor = CounterpartyCommitmentSecrets::new();
1033                         secrets.clear();
1034
1035                         secrets.push([0; 32]);
1036                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1037                         monitor.provide_secret(281474976710655, 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("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1042                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1043                         test_secrets!();
1044
1045                         secrets.push([0; 32]);
1046                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1047                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1048                         test_secrets!();
1049
1050                         secrets.push([0; 32]);
1051                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1052                         monitor.provide_secret(281474976710652, 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("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1057                         monitor.provide_secret(281474976710651, 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("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1062                         monitor.provide_secret(281474976710650, 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("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1067                         monitor.provide_secret(281474976710649, 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("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
1072                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1073                 }
1074         }
1075 }