b899fe49407c60f24c8c362fa033c30a57ce420a
[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_hashes::hash160::Hash as Hash160;
15 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
16
17 use ln::channelmanager::{PaymentHash, PaymentPreimage};
18 use ln::msgs::DecodeError;
19 use util::ser::{Readable, Writeable, Writer, WriterWriteAdaptor};
20 use util::byte_utils;
21
22 use secp256k1::key::{SecretKey, PublicKey};
23 use secp256k1::{Secp256k1, Signature};
24 use secp256k1;
25
26 use std::{cmp, mem};
27
28 const MAX_ALLOC_SIZE: usize = 64*1024;
29
30 pub(super) const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
31 pub(super) const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
32
33 #[derive(PartialEq)]
34 pub(crate) enum HTLCType {
35         AcceptedHTLC,
36         OfferedHTLC
37 }
38
39 impl HTLCType {
40         /// Check if a given tx witnessScript len matchs one of a pre-signed HTLC
41         pub(crate) fn scriptlen_to_htlctype(witness_script_len: usize) ->  Option<HTLCType> {
42                 if witness_script_len == 133 {
43                         Some(HTLCType::OfferedHTLC)
44                 } else if witness_script_len >= 136 && witness_script_len <= 139 {
45                         Some(HTLCType::AcceptedHTLC)
46                 } else {
47                         None
48                 }
49         }
50 }
51
52 // Various functions for key derivation and transaction creation for use within channels. Primarily
53 // used in Channel and ChannelMonitor.
54
55 pub(super) fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
56         let mut res: [u8; 32] = commitment_seed.clone();
57         for i in 0..48 {
58                 let bitpos = 47 - i;
59                 if idx & (1 << bitpos) == (1 << bitpos) {
60                         res[bitpos / 8] ^= 1 << (bitpos & 7);
61                         res = Sha256::hash(&res).into_inner();
62                 }
63         }
64         res
65 }
66
67 /// Implements the per-commitment secret storage scheme from
68 /// [BOLT 3](https://github.com/lightningnetwork/lightning-rfc/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
69 ///
70 /// Allows us to keep track of all of the revocation secrets of counterarties in just 50*32 bytes
71 /// or so.
72 #[derive(Clone)]
73 pub(super) struct CounterpartyCommitmentSecrets {
74         old_secrets: [([u8; 32], u64); 49],
75 }
76
77 impl PartialEq for CounterpartyCommitmentSecrets {
78         fn eq(&self, other: &Self) -> bool {
79                 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
80                         if secret != o_secret || idx != o_idx {
81                                 return false
82                         }
83                 }
84                 true
85         }
86 }
87
88 impl CounterpartyCommitmentSecrets {
89         pub(super) fn new() -> Self {
90                 Self { old_secrets: [([0; 32], 1 << 48); 49], }
91         }
92
93         #[inline]
94         fn place_secret(idx: u64) -> u8 {
95                 for i in 0..48 {
96                         if idx & (1 << i) == (1 << i) {
97                                 return i
98                         }
99                 }
100                 48
101         }
102
103         pub(super) fn get_min_seen_secret(&self) -> u64 {
104                 //TODO This can be optimized?
105                 let mut min = 1 << 48;
106                 for &(_, idx) in self.old_secrets.iter() {
107                         if idx < min {
108                                 min = idx;
109                         }
110                 }
111                 min
112         }
113
114         #[inline]
115         pub(super) fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
116                 let mut res: [u8; 32] = secret;
117                 for i in 0..bits {
118                         let bitpos = bits - 1 - i;
119                         if idx & (1 << bitpos) == (1 << bitpos) {
120                                 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
121                                 res = Sha256::hash(&res).into_inner();
122                         }
123                 }
124                 res
125         }
126
127         pub(super) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
128                 let pos = Self::place_secret(idx);
129                 for i in 0..pos {
130                         let (old_secret, old_idx) = self.old_secrets[i as usize];
131                         if Self::derive_secret(secret, pos, old_idx) != old_secret {
132                                 return Err(());
133                         }
134                 }
135                 if self.get_min_seen_secret() <= idx {
136                         return Ok(());
137                 }
138                 self.old_secrets[pos as usize] = (secret, idx);
139                 Ok(())
140         }
141
142         /// Can only fail if idx is < get_min_seen_secret
143         pub(super) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
144                 for i in 0..self.old_secrets.len() {
145                         if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
146                                 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
147                         }
148                 }
149                 assert!(idx < self.get_min_seen_secret());
150                 None
151         }
152 }
153
154 impl Writeable for CounterpartyCommitmentSecrets {
155         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
156                 for &(ref secret, ref idx) in self.old_secrets.iter() {
157                         writer.write_all(secret)?;
158                         writer.write_all(&byte_utils::be64_to_array(*idx))?;
159                 }
160                 Ok(())
161         }
162 }
163 impl Readable for CounterpartyCommitmentSecrets {
164         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
165                 let mut old_secrets = [([0; 32], 1 << 48); 49];
166                 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
167                         *secret = Readable::read(reader)?;
168                         *idx = Readable::read(reader)?;
169                 }
170
171                 Ok(Self { old_secrets })
172         }
173 }
174
175 /// Derives a per-commitment-transaction private key (eg an htlc key or payment 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(super) 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(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> {
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(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> {
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         /// B's Payment Key
267         pub(crate) b_payment_key: PublicKey,
268 }
269 impl_writeable!(TxCreationKeys, 33*6,
270         { per_commitment_point, revocation_key, a_htlc_key, b_htlc_key, a_delayed_payment_key, b_payment_key });
271
272 /// One counterparty's public keys which do not change over the life of a channel.
273 #[derive(Clone, PartialEq)]
274 pub struct ChannelPublicKeys {
275         /// The public key which is used to sign all commitment transactions, as it appears in the
276         /// on-chain channel lock-in 2-of-2 multisig output.
277         pub funding_pubkey: PublicKey,
278         /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
279         /// revocation keys. The per-commitment revocation private key is then revealed by the owner of
280         /// a commitment transaction so that their counterparty can claim all available funds if they
281         /// broadcast an old state.
282         pub revocation_basepoint: PublicKey,
283         /// The base point which is used (with derive_public_key) to derive a per-commitment payment
284         /// public key which receives immediately-spendable non-HTLC-encumbered funds.
285         pub payment_basepoint: PublicKey,
286         /// The base point which is used (with derive_public_key) to derive a per-commitment payment
287         /// public key which receives non-HTLC-encumbered funds which are only available for spending
288         /// after some delay (or can be claimed via the revocation path).
289         pub delayed_payment_basepoint: PublicKey,
290         /// The base point which is used (with derive_public_key) to derive a per-commitment public key
291         /// which is used to encumber HTLC-in-flight outputs.
292         pub htlc_basepoint: PublicKey,
293 }
294
295 impl_writeable!(ChannelPublicKeys, 33*5, {
296         funding_pubkey,
297         revocation_basepoint,
298         payment_basepoint,
299         delayed_payment_basepoint,
300         htlc_basepoint
301 });
302
303
304 impl TxCreationKeys {
305         pub(crate) fn new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, a_delayed_payment_base: &PublicKey, a_htlc_base: &PublicKey, b_revocation_base: &PublicKey, b_payment_base: &PublicKey, b_htlc_base: &PublicKey) -> Result<TxCreationKeys, secp256k1::Error> {
306                 Ok(TxCreationKeys {
307                         per_commitment_point: per_commitment_point.clone(),
308                         revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &b_revocation_base)?,
309                         a_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_htlc_base)?,
310                         b_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_htlc_base)?,
311                         a_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_delayed_payment_base)?,
312                         b_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_payment_base)?,
313                 })
314         }
315 }
316
317 /// Gets the "to_local" output redeemscript, ie the script which is time-locked or spendable by
318 /// the revocation key
319 pub(super) fn get_revokeable_redeemscript(revocation_key: &PublicKey, to_self_delay: u16, delayed_payment_key: &PublicKey) -> Script {
320         Builder::new().push_opcode(opcodes::all::OP_IF)
321                       .push_slice(&revocation_key.serialize())
322                       .push_opcode(opcodes::all::OP_ELSE)
323                       .push_int(to_self_delay as i64)
324                       .push_opcode(opcodes::all::OP_CSV)
325                       .push_opcode(opcodes::all::OP_DROP)
326                       .push_slice(&delayed_payment_key.serialize())
327                       .push_opcode(opcodes::all::OP_ENDIF)
328                       .push_opcode(opcodes::all::OP_CHECKSIG)
329                       .into_script()
330 }
331
332 #[derive(Clone, PartialEq)]
333 /// Information about an HTLC as it appears in a commitment transaction
334 pub struct HTLCOutputInCommitment {
335         /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
336         /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
337         /// need to compare this value to whether the commitment transaction in question is that of
338         /// the remote party or our own.
339         pub offered: bool,
340         /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
341         /// this divided by 1000.
342         pub amount_msat: u64,
343         /// The CLTV lock-time at which this HTLC expires.
344         pub cltv_expiry: u32,
345         /// The hash of the preimage which unlocks this HTLC.
346         pub payment_hash: PaymentHash,
347         /// The position within the commitment transactions' outputs. This may be None if the value is
348         /// below the dust limit (in which case no output appears in the commitment transaction and the
349         /// value is spent to additional transaction fees).
350         pub transaction_output_index: Option<u32>,
351 }
352
353 impl_writeable!(HTLCOutputInCommitment, 1 + 8 + 4 + 32 + 5, {
354         offered,
355         amount_msat,
356         cltv_expiry,
357         payment_hash,
358         transaction_output_index
359 });
360
361 #[inline]
362 pub(crate) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, a_htlc_key: &PublicKey, b_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
363         let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
364         if htlc.offered {
365                 Builder::new().push_opcode(opcodes::all::OP_DUP)
366                               .push_opcode(opcodes::all::OP_HASH160)
367                               .push_slice(&Hash160::hash(&revocation_key.serialize())[..])
368                               .push_opcode(opcodes::all::OP_EQUAL)
369                               .push_opcode(opcodes::all::OP_IF)
370                               .push_opcode(opcodes::all::OP_CHECKSIG)
371                               .push_opcode(opcodes::all::OP_ELSE)
372                               .push_slice(&b_htlc_key.serialize()[..])
373                               .push_opcode(opcodes::all::OP_SWAP)
374                               .push_opcode(opcodes::all::OP_SIZE)
375                               .push_int(32)
376                               .push_opcode(opcodes::all::OP_EQUAL)
377                               .push_opcode(opcodes::all::OP_NOTIF)
378                               .push_opcode(opcodes::all::OP_DROP)
379                               .push_int(2)
380                               .push_opcode(opcodes::all::OP_SWAP)
381                               .push_slice(&a_htlc_key.serialize()[..])
382                               .push_int(2)
383                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
384                               .push_opcode(opcodes::all::OP_ELSE)
385                               .push_opcode(opcodes::all::OP_HASH160)
386                               .push_slice(&payment_hash160)
387                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
388                               .push_opcode(opcodes::all::OP_CHECKSIG)
389                               .push_opcode(opcodes::all::OP_ENDIF)
390                               .push_opcode(opcodes::all::OP_ENDIF)
391                               .into_script()
392         } else {
393                 Builder::new().push_opcode(opcodes::all::OP_DUP)
394                               .push_opcode(opcodes::all::OP_HASH160)
395                               .push_slice(&Hash160::hash(&revocation_key.serialize())[..])
396                               .push_opcode(opcodes::all::OP_EQUAL)
397                               .push_opcode(opcodes::all::OP_IF)
398                               .push_opcode(opcodes::all::OP_CHECKSIG)
399                               .push_opcode(opcodes::all::OP_ELSE)
400                               .push_slice(&b_htlc_key.serialize()[..])
401                               .push_opcode(opcodes::all::OP_SWAP)
402                               .push_opcode(opcodes::all::OP_SIZE)
403                               .push_int(32)
404                               .push_opcode(opcodes::all::OP_EQUAL)
405                               .push_opcode(opcodes::all::OP_IF)
406                               .push_opcode(opcodes::all::OP_HASH160)
407                               .push_slice(&payment_hash160)
408                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
409                               .push_int(2)
410                               .push_opcode(opcodes::all::OP_SWAP)
411                               .push_slice(&a_htlc_key.serialize()[..])
412                               .push_int(2)
413                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
414                               .push_opcode(opcodes::all::OP_ELSE)
415                               .push_opcode(opcodes::all::OP_DROP)
416                               .push_int(htlc.cltv_expiry as i64)
417                               .push_opcode(opcodes::all::OP_CLTV)
418                               .push_opcode(opcodes::all::OP_DROP)
419                               .push_opcode(opcodes::all::OP_CHECKSIG)
420                               .push_opcode(opcodes::all::OP_ENDIF)
421                               .push_opcode(opcodes::all::OP_ENDIF)
422                               .into_script()
423         }
424 }
425
426 /// note here that 'a_revocation_key' is generated using b_revocation_basepoint and a's
427 /// commitment secret. 'htlc' does *not* need to have its previous_output_index filled.
428 #[inline]
429 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, keys: &TxCreationKeys) -> Script {
430         get_htlc_redeemscript_with_explicit_keys(htlc, &keys.a_htlc_key, &keys.b_htlc_key, &keys.revocation_key)
431 }
432
433 /// Gets the redeemscript for a funding output from the two funding public keys.
434 /// Note that the order of funding public keys does not matter.
435 pub fn make_funding_redeemscript(a: &PublicKey, b: &PublicKey) -> Script {
436         let our_funding_key = a.serialize();
437         let their_funding_key = b.serialize();
438
439         let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
440         if our_funding_key[..] < their_funding_key[..] {
441                 builder.push_slice(&our_funding_key)
442                         .push_slice(&their_funding_key)
443         } else {
444                 builder.push_slice(&their_funding_key)
445                         .push_slice(&our_funding_key)
446         }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
447 }
448
449 /// panics if htlc.transaction_output_index.is_none()!
450 pub fn build_htlc_transaction(prev_hash: &Sha256dHash, feerate_per_kw: u64, to_self_delay: u16, htlc: &HTLCOutputInCommitment, a_delayed_payment_key: &PublicKey, revocation_key: &PublicKey) -> Transaction {
451         let mut txins: Vec<TxIn> = Vec::new();
452         txins.push(TxIn {
453                 previous_output: OutPoint {
454                         txid: prev_hash.clone(),
455                         vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
456                 },
457                 script_sig: Script::new(),
458                 sequence: 0,
459                 witness: Vec::new(),
460         });
461
462         let total_fee = if htlc.offered {
463                         feerate_per_kw * HTLC_TIMEOUT_TX_WEIGHT / 1000
464                 } else {
465                         feerate_per_kw * HTLC_SUCCESS_TX_WEIGHT / 1000
466                 };
467
468         let mut txouts: Vec<TxOut> = Vec::new();
469         txouts.push(TxOut {
470                 script_pubkey: get_revokeable_redeemscript(revocation_key, to_self_delay, a_delayed_payment_key).to_v0_p2wsh(),
471                 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)
472         });
473
474         Transaction {
475                 version: 2,
476                 lock_time: if htlc.offered { htlc.cltv_expiry } else { 0 },
477                 input: txins,
478                 output: txouts,
479         }
480 }
481
482 #[derive(Clone)]
483 /// We use this to track local commitment transactions and put off signing them until we are ready
484 /// to broadcast. Eventually this will require a signer which is possibly external, but for now we
485 /// just pass in the SecretKeys required.
486 pub struct LocalCommitmentTransaction {
487         tx: Transaction,
488         pub(crate) local_keys: TxCreationKeys,
489         pub(crate) feerate_per_kw: u64,
490         per_htlc: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<Transaction>)>
491 }
492 impl LocalCommitmentTransaction {
493         #[cfg(test)]
494         pub fn dummy() -> Self {
495                 let dummy_input = TxIn {
496                         previous_output: OutPoint {
497                                 txid: Default::default(),
498                                 vout: 0,
499                         },
500                         script_sig: Default::default(),
501                         sequence: 0,
502                         witness: vec![vec![], vec![], vec![]]
503                 };
504                 let dummy_key = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&[42; 32]).unwrap());
505                 Self {
506                         tx: Transaction {
507                                 version: 2,
508                                 input: vec![dummy_input],
509                                 output: Vec::new(),
510                                 lock_time: 0,
511                         },
512                         local_keys: TxCreationKeys {
513                                         per_commitment_point: dummy_key.clone(),
514                                         revocation_key: dummy_key.clone(),
515                                         a_htlc_key: dummy_key.clone(),
516                                         b_htlc_key: dummy_key.clone(),
517                                         a_delayed_payment_key: dummy_key.clone(),
518                                         b_payment_key: dummy_key.clone(),
519                                 },
520                         feerate_per_kw: 0,
521                         per_htlc: Vec::new()
522                 }
523         }
524
525         /// Generate a new LocalCommitmentTransaction based on a raw commitment transaction,
526         /// remote signature and both parties keys
527         pub(crate) fn new_missing_local_sig(mut tx: Transaction, their_sig: &Signature, our_funding_key: &PublicKey, their_funding_key: &PublicKey, local_keys: TxCreationKeys, feerate_per_kw: u64, mut htlc_data: Vec<(HTLCOutputInCommitment, Option<Signature>)>) -> LocalCommitmentTransaction {
528                 if tx.input.len() != 1 { panic!("Tried to store a commitment transaction that had input count != 1!"); }
529                 if tx.input[0].witness.len() != 0 { panic!("Tried to store a signed commitment transaction?"); }
530
531                 tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
532
533                 if our_funding_key.serialize()[..] < their_funding_key.serialize()[..] {
534                         tx.input[0].witness.push(Vec::new());
535                         tx.input[0].witness.push(their_sig.serialize_der().to_vec());
536                         tx.input[0].witness[2].push(SigHashType::All as u8);
537                 } else {
538                         tx.input[0].witness.push(their_sig.serialize_der().to_vec());
539                         tx.input[0].witness[1].push(SigHashType::All as u8);
540                         tx.input[0].witness.push(Vec::new());
541                 }
542
543                 Self { tx,
544                         local_keys,
545                         feerate_per_kw,
546                         // TODO: Avoid the conversion of a Vec created likely just for this:
547                         per_htlc: htlc_data.drain(..).map(|(a, b)| (a, b, None)).collect(),
548                 }
549         }
550
551         /// Get the txid of the local commitment transaction contained in this
552         /// LocalCommitmentTransaction
553         pub fn txid(&self) -> Sha256dHash {
554                 self.tx.txid()
555         }
556
557         /// Check if LocalCommitmentTransaction has already been signed by us
558         pub(crate) fn has_local_sig(&self) -> bool {
559                 if self.tx.input.len() != 1 { panic!("Commitment transactions must have input count == 1!"); }
560                 if self.tx.input[0].witness.len() == 4 {
561                         assert!(!self.tx.input[0].witness[1].is_empty());
562                         assert!(!self.tx.input[0].witness[2].is_empty());
563                         true
564                 } else {
565                         assert_eq!(self.tx.input[0].witness.len(), 3);
566                         assert!(self.tx.input[0].witness[0].is_empty());
567                         assert!(self.tx.input[0].witness[1].is_empty() || self.tx.input[0].witness[2].is_empty());
568                         false
569                 }
570         }
571
572         /// Gets our signature for the contained commitment transaction given our funding private key.
573         ///
574         /// Funding key is your key included in the 2-2 funding_outpoint lock. Should be provided
575         /// by your ChannelKeys.
576         /// Funding redeemscript is script locking funding_outpoint. This is the mutlsig script
577         /// between your own funding key and your counterparty's. Currently, this is provided in
578         /// ChannelKeys::sign_local_commitment() calls directly.
579         /// Channel value is amount locked in funding_outpoint.
580         pub fn get_local_sig<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
581                 let sighash = hash_to_message!(&bip143::SighashComponents::new(&self.tx)
582                         .sighash_all(&self.tx.input[0], funding_redeemscript, channel_value_satoshis)[..]);
583                 secp_ctx.sign(&sighash, funding_key)
584         }
585
586
587         pub(crate) fn add_local_sig(&mut self, funding_redeemscript: &Script, our_sig: Signature) {
588                 if self.has_local_sig() { return; }
589
590                 if self.tx.input[0].witness[1].is_empty() {
591                         self.tx.input[0].witness[1] = our_sig.serialize_der().to_vec();
592                         self.tx.input[0].witness[1].push(SigHashType::All as u8);
593                 } else {
594                         self.tx.input[0].witness[2] = our_sig.serialize_der().to_vec();
595                         self.tx.input[0].witness[2].push(SigHashType::All as u8);
596                 }
597
598                 self.tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
599         }
600
601         /// Get raw transaction without asserting if witness is complete
602         pub(crate) fn without_valid_witness(&self) -> &Transaction { &self.tx }
603         /// Get raw transaction with panics if witness is incomplete
604         pub(crate) fn with_valid_witness(&self) -> &Transaction {
605                 assert!(self.has_local_sig());
606                 &self.tx
607         }
608
609         /// Add local signature for a htlc transaction, do nothing if a cached signed transaction is
610         /// already present
611         pub fn add_htlc_sig<T: secp256k1::Signing>(&mut self, htlc_base_key: &SecretKey, htlc_index: u32, preimage: Option<PaymentPreimage>, local_csv: u16, secp_ctx: &Secp256k1<T>) {
612                 let txid = self.txid();
613                 for this_htlc in self.per_htlc.iter_mut() {
614                         if this_htlc.0.transaction_output_index == Some(htlc_index) {
615                                 if this_htlc.2.is_some() { return; } // we already have a cached htlc transaction at provided index
616                                 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);
617                                 if !this_htlc.0.offered && preimage.is_none() { return; } // if we don't have preimage for HTLC-Success, don't try to generate
618                                 let htlc_secret = if !this_htlc.0.offered { preimage } else { None }; // if we have a preimage for HTLC-Timeout, don't use it that's likely a duplicate HTLC hash
619                                 if this_htlc.1.is_none() { return; } // we don't have any remote signature for this htlc
620                                 if htlc_tx.input.len() != 1 { return; }
621                                 if htlc_tx.input[0].witness.len() != 0 { return; }
622
623                                 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);
624
625                                 if let Ok(our_htlc_key) = derive_private_key(secp_ctx, &self.local_keys.per_commitment_point, htlc_base_key) {
626                                         let sighash = hash_to_message!(&bip143::SighashComponents::new(&htlc_tx).sighash_all(&htlc_tx.input[0], &htlc_redeemscript, this_htlc.0.amount_msat / 1000)[..]);
627                                         let our_sig = secp_ctx.sign(&sighash, &our_htlc_key);
628
629                                         htlc_tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
630
631                                         htlc_tx.input[0].witness.push(this_htlc.1.unwrap().serialize_der().to_vec());
632                                         htlc_tx.input[0].witness.push(our_sig.serialize_der().to_vec());
633                                         htlc_tx.input[0].witness[1].push(SigHashType::All as u8);
634                                         htlc_tx.input[0].witness[2].push(SigHashType::All as u8);
635
636                                         if this_htlc.0.offered {
637                                                 htlc_tx.input[0].witness.push(Vec::new());
638                                                 assert!(htlc_secret.is_none());
639                                         } else {
640                                                 htlc_tx.input[0].witness.push(htlc_secret.unwrap().0.to_vec());
641                                         }
642
643                                         htlc_tx.input[0].witness.push(htlc_redeemscript.as_bytes().to_vec());
644
645                                         this_htlc.2 = Some(htlc_tx);
646                                 } else { return; }
647                         }
648                 }
649         }
650         /// Expose raw htlc transaction, guarante witness is complete if non-empty
651         pub fn htlc_with_valid_witness(&self, htlc_index: u32) -> &Option<Transaction> {
652                 for this_htlc in self.per_htlc.iter() {
653                         if this_htlc.0.transaction_output_index.unwrap() == htlc_index {
654                                 return &this_htlc.2;
655                         }
656                 }
657                 &None
658         }
659 }
660 impl PartialEq for LocalCommitmentTransaction {
661         // We dont care whether we are signed in equality comparison
662         fn eq(&self, o: &Self) -> bool {
663                 self.txid() == o.txid()
664         }
665 }
666 impl Writeable for LocalCommitmentTransaction {
667         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
668                 if let Err(e) = self.tx.consensus_encode(&mut WriterWriteAdaptor(writer)) {
669                         match e {
670                                 encode::Error::Io(e) => return Err(e),
671                                 _ => panic!("local tx must have been well-formed!"),
672                         }
673                 }
674                 self.local_keys.write(writer)?;
675                 self.feerate_per_kw.write(writer)?;
676                 writer.write_all(&byte_utils::be64_to_array(self.per_htlc.len() as u64))?;
677                 for &(ref htlc, ref sig, ref htlc_tx) in self.per_htlc.iter() {
678                         htlc.write(writer)?;
679                         sig.write(writer)?;
680                         htlc_tx.write(writer)?;
681                 }
682                 Ok(())
683         }
684 }
685 impl Readable for LocalCommitmentTransaction {
686         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
687                 let tx = match Transaction::consensus_decode(reader.by_ref()) {
688                         Ok(tx) => tx,
689                         Err(e) => match e {
690                                 encode::Error::Io(ioe) => return Err(DecodeError::Io(ioe)),
691                                 _ => return Err(DecodeError::InvalidValue),
692                         },
693                 };
694                 let local_keys = Readable::read(reader)?;
695                 let feerate_per_kw = Readable::read(reader)?;
696                 let htlcs_count: u64 = Readable::read(reader)?;
697                 let mut per_htlc = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / mem::size_of::<(HTLCOutputInCommitment, Option<Signature>, Option<Transaction>)>()));
698                 for _ in 0..htlcs_count {
699                         let htlc: HTLCOutputInCommitment = Readable::read(reader)?;
700                         let sigs = Readable::read(reader)?;
701                         let htlc_tx = Readable::read(reader)?;
702                         per_htlc.push((htlc, sigs, htlc_tx));
703                 }
704
705                 if tx.input.len() != 1 {
706                         // Ensure tx didn't hit the 0-input ambiguity case.
707                         return Err(DecodeError::InvalidValue);
708                 }
709                 Ok(Self {
710                         tx,
711                         local_keys,
712                         feerate_per_kw,
713                         per_htlc,
714                 })
715         }
716 }
717
718 #[cfg(test)]
719 mod tests {
720         use super::CounterpartyCommitmentSecrets;
721         use hex;
722
723         #[test]
724         fn test_per_commitment_storage() {
725                 // Test vectors from BOLT 3:
726                 let mut secrets: Vec<[u8; 32]> = Vec::new();
727                 let mut monitor;
728
729                 macro_rules! test_secrets {
730                         () => {
731                                 let mut idx = 281474976710655;
732                                 for secret in secrets.iter() {
733                                         assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
734                                         idx -= 1;
735                                 }
736                                 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
737                                 assert!(monitor.get_secret(idx).is_none());
738                         };
739                 }
740
741                 {
742                         // insert_secret correct sequence
743                         monitor = CounterpartyCommitmentSecrets::new();
744                         secrets.clear();
745
746                         secrets.push([0; 32]);
747                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
748                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
749                         test_secrets!();
750
751                         secrets.push([0; 32]);
752                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
753                         monitor.provide_secret(281474976710654, 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("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
758                         monitor.provide_secret(281474976710653, 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("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
763                         monitor.provide_secret(281474976710652, 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("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
768                         monitor.provide_secret(281474976710651, 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("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
773                         monitor.provide_secret(281474976710650, 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("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
778                         monitor.provide_secret(281474976710649, 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("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
783                         monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
784                         test_secrets!();
785                 }
786
787                 {
788                         // insert_secret #1 incorrect
789                         monitor = CounterpartyCommitmentSecrets::new();
790                         secrets.clear();
791
792                         secrets.push([0; 32]);
793                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
794                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
795                         test_secrets!();
796
797                         secrets.push([0; 32]);
798                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
799                         assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
800                 }
801
802                 {
803                         // insert_secret #2 incorrect (#1 derived from incorrect)
804                         monitor = CounterpartyCommitmentSecrets::new();
805                         secrets.clear();
806
807                         secrets.push([0; 32]);
808                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
809                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
810                         test_secrets!();
811
812                         secrets.push([0; 32]);
813                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
814                         monitor.provide_secret(281474976710654, 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("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
819                         monitor.provide_secret(281474976710653, 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("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
824                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
825                 }
826
827                 {
828                         // insert_secret #3 incorrect
829                         monitor = CounterpartyCommitmentSecrets::new();
830                         secrets.clear();
831
832                         secrets.push([0; 32]);
833                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
834                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
835                         test_secrets!();
836
837                         secrets.push([0; 32]);
838                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
839                         monitor.provide_secret(281474976710654, 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("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
844                         monitor.provide_secret(281474976710653, 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("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
849                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
850                 }
851
852                 {
853                         // insert_secret #4 incorrect (1,2,3 derived from incorrect)
854                         monitor = CounterpartyCommitmentSecrets::new();
855                         secrets.clear();
856
857                         secrets.push([0; 32]);
858                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
859                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
860                         test_secrets!();
861
862                         secrets.push([0; 32]);
863                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
864                         monitor.provide_secret(281474976710654, 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("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
869                         monitor.provide_secret(281474976710653, 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("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
874                         monitor.provide_secret(281474976710652, 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("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
879                         monitor.provide_secret(281474976710651, 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("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
884                         monitor.provide_secret(281474976710650, 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("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
889                         monitor.provide_secret(281474976710649, 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("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
894                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
895                 }
896
897                 {
898                         // insert_secret #5 incorrect
899                         monitor = CounterpartyCommitmentSecrets::new();
900                         secrets.clear();
901
902                         secrets.push([0; 32]);
903                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
904                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
905                         test_secrets!();
906
907                         secrets.push([0; 32]);
908                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
909                         monitor.provide_secret(281474976710654, 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("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
914                         monitor.provide_secret(281474976710653, 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("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
919                         monitor.provide_secret(281474976710652, 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("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
924                         monitor.provide_secret(281474976710651, 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("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
929                         assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
930                 }
931
932                 {
933                         // insert_secret #6 incorrect (5 derived from incorrect)
934                         monitor = CounterpartyCommitmentSecrets::new();
935                         secrets.clear();
936
937                         secrets.push([0; 32]);
938                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
939                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
940                         test_secrets!();
941
942                         secrets.push([0; 32]);
943                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
944                         monitor.provide_secret(281474976710654, 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("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
949                         monitor.provide_secret(281474976710653, 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("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
954                         monitor.provide_secret(281474976710652, 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("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
959                         monitor.provide_secret(281474976710651, 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("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
964                         monitor.provide_secret(281474976710650, 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("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
969                         monitor.provide_secret(281474976710649, 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("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
974                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
975                 }
976
977                 {
978                         // insert_secret #7 incorrect
979                         monitor = CounterpartyCommitmentSecrets::new();
980                         secrets.clear();
981
982                         secrets.push([0; 32]);
983                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
984                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
985                         test_secrets!();
986
987                         secrets.push([0; 32]);
988                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
989                         monitor.provide_secret(281474976710654, 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("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
994                         monitor.provide_secret(281474976710653, 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("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
999                         monitor.provide_secret(281474976710652, 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("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1004                         monitor.provide_secret(281474976710651, 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("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1009                         monitor.provide_secret(281474976710650, 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("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
1014                         monitor.provide_secret(281474976710649, 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("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1019                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1020                 }
1021
1022                 {
1023                         // insert_secret #8 incorrect
1024                         monitor = CounterpartyCommitmentSecrets::new();
1025                         secrets.clear();
1026
1027                         secrets.push([0; 32]);
1028                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1029                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1030                         test_secrets!();
1031
1032                         secrets.push([0; 32]);
1033                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1034                         monitor.provide_secret(281474976710654, 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("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1039                         monitor.provide_secret(281474976710653, 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("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1044                         monitor.provide_secret(281474976710652, 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("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1049                         monitor.provide_secret(281474976710651, 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("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1054                         monitor.provide_secret(281474976710650, 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("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1059                         monitor.provide_secret(281474976710649, 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("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
1064                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1065                 }
1066         }
1067 }