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