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