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