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