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