]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/chan_utils.rs
Add anchor support to commitment HTLC outputs
[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::Sign message signing by hand.
12
13 use bitcoin::blockdata::script::{Script,Builder};
14 use bitcoin::blockdata::opcodes;
15 use bitcoin::blockdata::transaction::{TxIn,TxOut,OutPoint,Transaction, SigHashType};
16 use bitcoin::util::bip143;
17
18 use bitcoin::hashes::{Hash, HashEngine};
19 use bitcoin::hashes::sha256::Hash as Sha256;
20 use bitcoin::hashes::ripemd160::Hash as Ripemd160;
21 use bitcoin::hash_types::{Txid, PubkeyHash};
22
23 use ln::{PaymentHash, PaymentPreimage};
24 use ln::msgs::DecodeError;
25 use util::ser::{Readable, Writeable, Writer};
26 use util::{byte_utils, transaction_utils};
27
28 use bitcoin::hash_types::WPubkeyHash;
29 use bitcoin::secp256k1::key::{SecretKey, PublicKey};
30 use bitcoin::secp256k1::{Secp256k1, Signature, Message};
31 use bitcoin::secp256k1::Error as SecpError;
32 use bitcoin::secp256k1;
33
34 use io;
35 use prelude::*;
36 use core::cmp;
37 use ln::chan_utils;
38 use util::transaction_utils::sort_outputs;
39 use ln::channel::{INITIAL_COMMITMENT_NUMBER, ANCHOR_OUTPUT_VALUE_SATOSHI};
40 use core::ops::Deref;
41 use chain;
42
43 pub(crate) const MAX_HTLCS: u16 = 483;
44
45 pub(super) const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
46 pub(super) const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
47
48 #[derive(PartialEq)]
49 pub(crate) enum HTLCType {
50         AcceptedHTLC,
51         OfferedHTLC
52 }
53
54 impl HTLCType {
55         /// Check if a given tx witnessScript len matchs one of a pre-signed HTLC
56         pub(crate) fn scriptlen_to_htlctype(witness_script_len: usize) ->  Option<HTLCType> {
57                 if witness_script_len == 133 {
58                         Some(HTLCType::OfferedHTLC)
59                 } else if witness_script_len >= 136 && witness_script_len <= 139 {
60                         Some(HTLCType::AcceptedHTLC)
61                 } else {
62                         None
63                 }
64         }
65 }
66
67 // Various functions for key derivation and transaction creation for use within channels. Primarily
68 // used in Channel and ChannelMonitor.
69
70 /// Build the commitment secret from the seed and the commitment number
71 pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
72         let mut res: [u8; 32] = commitment_seed.clone();
73         for i in 0..48 {
74                 let bitpos = 47 - i;
75                 if idx & (1 << bitpos) == (1 << bitpos) {
76                         res[bitpos / 8] ^= 1 << (bitpos & 7);
77                         res = Sha256::hash(&res).into_inner();
78                 }
79         }
80         res
81 }
82
83 /// Build a closing transaction
84 pub fn build_closing_transaction(to_holder_value_sat: u64, to_counterparty_value_sat: u64, to_holder_script: Script, to_counterparty_script: Script, funding_outpoint: OutPoint) -> Transaction {
85         let txins = {
86                 let mut ins: Vec<TxIn> = Vec::new();
87                 ins.push(TxIn {
88                         previous_output: funding_outpoint,
89                         script_sig: Script::new(),
90                         sequence: 0xffffffff,
91                         witness: Vec::new(),
92                 });
93                 ins
94         };
95
96         let mut txouts: Vec<(TxOut, ())> = Vec::new();
97
98         if to_counterparty_value_sat > 0 {
99                 txouts.push((TxOut {
100                         script_pubkey: to_counterparty_script,
101                         value: to_counterparty_value_sat
102                 }, ()));
103         }
104
105         if to_holder_value_sat > 0 {
106                 txouts.push((TxOut {
107                         script_pubkey: to_holder_script,
108                         value: to_holder_value_sat
109                 }, ()));
110         }
111
112         transaction_utils::sort_outputs(&mut txouts, |_, _| { cmp::Ordering::Equal }); // Ordering doesnt matter if they used our pubkey...
113
114         let mut outputs: Vec<TxOut> = Vec::new();
115         for out in txouts.drain(..) {
116                 outputs.push(out.0);
117         }
118
119         Transaction {
120                 version: 2,
121                 lock_time: 0,
122                 input: txins,
123                 output: outputs,
124         }
125 }
126
127 /// Implements the per-commitment secret storage scheme from
128 /// [BOLT 3](https://github.com/lightningnetwork/lightning-rfc/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
129 ///
130 /// Allows us to keep track of all of the revocation secrets of counterarties in just 50*32 bytes
131 /// or so.
132 #[derive(Clone)]
133 pub(crate) struct CounterpartyCommitmentSecrets {
134         old_secrets: [([u8; 32], u64); 49],
135 }
136
137 impl PartialEq for CounterpartyCommitmentSecrets {
138         fn eq(&self, other: &Self) -> bool {
139                 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
140                         if secret != o_secret || idx != o_idx {
141                                 return false
142                         }
143                 }
144                 true
145         }
146 }
147
148 impl CounterpartyCommitmentSecrets {
149         pub(crate) fn new() -> Self {
150                 Self { old_secrets: [([0; 32], 1 << 48); 49], }
151         }
152
153         #[inline]
154         fn place_secret(idx: u64) -> u8 {
155                 for i in 0..48 {
156                         if idx & (1 << i) == (1 << i) {
157                                 return i
158                         }
159                 }
160                 48
161         }
162
163         pub(crate) fn get_min_seen_secret(&self) -> u64 {
164                 //TODO This can be optimized?
165                 let mut min = 1 << 48;
166                 for &(_, idx) in self.old_secrets.iter() {
167                         if idx < min {
168                                 min = idx;
169                         }
170                 }
171                 min
172         }
173
174         #[inline]
175         fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
176                 let mut res: [u8; 32] = secret;
177                 for i in 0..bits {
178                         let bitpos = bits - 1 - i;
179                         if idx & (1 << bitpos) == (1 << bitpos) {
180                                 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
181                                 res = Sha256::hash(&res).into_inner();
182                         }
183                 }
184                 res
185         }
186
187         pub(crate) fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
188                 let pos = Self::place_secret(idx);
189                 for i in 0..pos {
190                         let (old_secret, old_idx) = self.old_secrets[i as usize];
191                         if Self::derive_secret(secret, pos, old_idx) != old_secret {
192                                 return Err(());
193                         }
194                 }
195                 if self.get_min_seen_secret() <= idx {
196                         return Ok(());
197                 }
198                 self.old_secrets[pos as usize] = (secret, idx);
199                 Ok(())
200         }
201
202         /// Can only fail if idx is < get_min_seen_secret
203         pub(crate) fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
204                 for i in 0..self.old_secrets.len() {
205                         if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
206                                 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
207                         }
208                 }
209                 assert!(idx < self.get_min_seen_secret());
210                 None
211         }
212 }
213
214 impl Writeable for CounterpartyCommitmentSecrets {
215         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
216                 for &(ref secret, ref idx) in self.old_secrets.iter() {
217                         writer.write_all(secret)?;
218                         writer.write_all(&byte_utils::be64_to_array(*idx))?;
219                 }
220                 write_tlv_fields!(writer, {});
221                 Ok(())
222         }
223 }
224 impl Readable for CounterpartyCommitmentSecrets {
225         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
226                 let mut old_secrets = [([0; 32], 1 << 48); 49];
227                 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
228                         *secret = Readable::read(reader)?;
229                         *idx = Readable::read(reader)?;
230                 }
231                 read_tlv_fields!(reader, {});
232                 Ok(Self { old_secrets })
233         }
234 }
235
236 /// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
237 /// from the base secret and the per_commitment_point.
238 ///
239 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
240 /// generated (ie our own).
241 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> Result<SecretKey, SecpError> {
242         let mut sha = Sha256::engine();
243         sha.input(&per_commitment_point.serialize());
244         sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
245         let res = Sha256::from_engine(sha).into_inner();
246
247         let mut key = base_secret.clone();
248         key.add_assign(&res)?;
249         Ok(key)
250 }
251
252 /// Derives a per-commitment-transaction public key (eg an htlc key or a delayed_payment key)
253 /// from the base point and the per_commitment_key. This is the public equivalent of
254 /// derive_private_key - using only public keys to derive a public key instead of private keys.
255 ///
256 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
257 /// generated (ie our own).
258 pub fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> Result<PublicKey, SecpError> {
259         let mut sha = Sha256::engine();
260         sha.input(&per_commitment_point.serialize());
261         sha.input(&base_point.serialize());
262         let res = Sha256::from_engine(sha).into_inner();
263
264         let hashkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&res)?);
265         base_point.combine(&hashkey)
266 }
267
268 /// Derives a per-commitment-transaction revocation key from its constituent parts.
269 ///
270 /// Only the cheating participant owns a valid witness to propagate a revoked 
271 /// commitment transaction, thus per_commitment_secret always come from cheater
272 /// and revocation_base_secret always come from punisher, which is the broadcaster
273 /// of the transaction spending with this key knowledge.
274 ///
275 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
276 /// generated (ie our own).
277 pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_secret: &SecretKey, countersignatory_revocation_base_secret: &SecretKey) -> Result<SecretKey, SecpError> {
278         let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
279         let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
280
281         let rev_append_commit_hash_key = {
282                 let mut sha = Sha256::engine();
283                 sha.input(&countersignatory_revocation_base_point.serialize());
284                 sha.input(&per_commitment_point.serialize());
285
286                 Sha256::from_engine(sha).into_inner()
287         };
288         let commit_append_rev_hash_key = {
289                 let mut sha = Sha256::engine();
290                 sha.input(&per_commitment_point.serialize());
291                 sha.input(&countersignatory_revocation_base_point.serialize());
292
293                 Sha256::from_engine(sha).into_inner()
294         };
295
296         let mut countersignatory_contrib = countersignatory_revocation_base_secret.clone();
297         countersignatory_contrib.mul_assign(&rev_append_commit_hash_key)?;
298         let mut broadcaster_contrib = per_commitment_secret.clone();
299         broadcaster_contrib.mul_assign(&commit_append_rev_hash_key)?;
300         countersignatory_contrib.add_assign(&broadcaster_contrib[..])?;
301         Ok(countersignatory_contrib)
302 }
303
304 /// Derives a per-commitment-transaction revocation public key from its constituent parts. This is
305 /// the public equivalend of derive_private_revocation_key - using only public keys to derive a
306 /// public key instead of private keys.
307 ///
308 /// Only the cheating participant owns a valid witness to propagate a revoked 
309 /// commitment transaction, thus per_commitment_point always come from cheater
310 /// and revocation_base_point always come from punisher, which is the broadcaster
311 /// of the transaction spending with this key knowledge.
312 ///
313 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
314 /// generated (ie our own).
315 pub fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, countersignatory_revocation_base_point: &PublicKey) -> Result<PublicKey, SecpError> {
316         let rev_append_commit_hash_key = {
317                 let mut sha = Sha256::engine();
318                 sha.input(&countersignatory_revocation_base_point.serialize());
319                 sha.input(&per_commitment_point.serialize());
320
321                 Sha256::from_engine(sha).into_inner()
322         };
323         let commit_append_rev_hash_key = {
324                 let mut sha = Sha256::engine();
325                 sha.input(&per_commitment_point.serialize());
326                 sha.input(&countersignatory_revocation_base_point.serialize());
327
328                 Sha256::from_engine(sha).into_inner()
329         };
330
331         let mut countersignatory_contrib = countersignatory_revocation_base_point.clone();
332         countersignatory_contrib.mul_assign(&secp_ctx, &rev_append_commit_hash_key)?;
333         let mut broadcaster_contrib = per_commitment_point.clone();
334         broadcaster_contrib.mul_assign(&secp_ctx, &commit_append_rev_hash_key)?;
335         countersignatory_contrib.combine(&broadcaster_contrib)
336 }
337
338 /// The set of public keys which are used in the creation of one commitment transaction.
339 /// These are derived from the channel base keys and per-commitment data.
340 ///
341 /// A broadcaster key is provided from potential broadcaster of the computed transaction.
342 /// A countersignatory key is coming from a protocol participant unable to broadcast the
343 /// transaction.
344 ///
345 /// These keys are assumed to be good, either because the code derived them from
346 /// channel basepoints via the new function, or they were obtained via
347 /// CommitmentTransaction.trust().keys() because we trusted the source of the
348 /// pre-calculated keys.
349 #[derive(PartialEq, Clone)]
350 pub struct TxCreationKeys {
351         /// The broadcaster's per-commitment public key which was used to derive the other keys.
352         pub per_commitment_point: PublicKey,
353         /// The revocation key which is used to allow the broadcaster of the commitment
354         /// transaction to provide their counterparty the ability to punish them if they broadcast
355         /// an old state.
356         pub revocation_key: PublicKey,
357         /// Broadcaster's HTLC Key
358         pub broadcaster_htlc_key: PublicKey,
359         /// Countersignatory's HTLC Key
360         pub countersignatory_htlc_key: PublicKey,
361         /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
362         pub broadcaster_delayed_payment_key: PublicKey,
363 }
364
365 impl_writeable_tlv_based!(TxCreationKeys, {
366         (0, per_commitment_point, required),
367         (2, revocation_key, required),
368         (4, broadcaster_htlc_key, required),
369         (6, countersignatory_htlc_key, required),
370         (8, broadcaster_delayed_payment_key, required),
371 });
372
373 /// One counterparty's public keys which do not change over the life of a channel.
374 #[derive(Clone, PartialEq)]
375 pub struct ChannelPublicKeys {
376         /// The public key which is used to sign all commitment transactions, as it appears in the
377         /// on-chain channel lock-in 2-of-2 multisig output.
378         pub funding_pubkey: PublicKey,
379         /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
380         /// revocation keys. This is combined with the per-commitment-secret generated by the
381         /// counterparty to create a secret which the counterparty can reveal to revoke previous
382         /// states.
383         pub revocation_basepoint: PublicKey,
384         /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
385         /// spendable primary channel balance on the broadcaster's commitment transaction. This key is
386         /// static across every commitment transaction.
387         pub payment_point: PublicKey,
388         /// The base point which is used (with derive_public_key) to derive a per-commitment payment
389         /// public key which receives non-HTLC-encumbered funds which are only available for spending
390         /// after some delay (or can be claimed via the revocation path).
391         pub delayed_payment_basepoint: PublicKey,
392         /// The base point which is used (with derive_public_key) to derive a per-commitment public key
393         /// which is used to encumber HTLC-in-flight outputs.
394         pub htlc_basepoint: PublicKey,
395 }
396
397 impl_writeable_tlv_based!(ChannelPublicKeys, {
398         (0, funding_pubkey, required),
399         (2, revocation_basepoint, required),
400         (4, payment_point, required),
401         (6, delayed_payment_basepoint, required),
402         (8, htlc_basepoint, required),
403 });
404
405 impl TxCreationKeys {
406         /// Create per-state keys from channel base points and the per-commitment point.
407         /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
408         pub fn derive_new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, broadcaster_delayed_payment_base: &PublicKey, broadcaster_htlc_base: &PublicKey, countersignatory_revocation_base: &PublicKey, countersignatory_htlc_base: &PublicKey) -> Result<TxCreationKeys, SecpError> {
409                 Ok(TxCreationKeys {
410                         per_commitment_point: per_commitment_point.clone(),
411                         revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &countersignatory_revocation_base)?,
412                         broadcaster_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_htlc_base)?,
413                         countersignatory_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &countersignatory_htlc_base)?,
414                         broadcaster_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_delayed_payment_base)?,
415                 })
416         }
417
418         /// Generate per-state keys from channel static keys.
419         /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
420         pub fn from_channel_static_keys<T: secp256k1::Signing + secp256k1::Verification>(per_commitment_point: &PublicKey, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TxCreationKeys, SecpError> {
421                 TxCreationKeys::derive_new(
422                         &secp_ctx,
423                         &per_commitment_point,
424                         &broadcaster_keys.delayed_payment_basepoint,
425                         &broadcaster_keys.htlc_basepoint,
426                         &countersignatory_keys.revocation_basepoint,
427                         &countersignatory_keys.htlc_basepoint,
428                 )
429         }
430 }
431
432 /// The maximum length of a script returned by get_revokeable_redeemscript.
433 // Calculated as 6 bytes of opcodes, 1 byte push plus 2 bytes for contest_delay, and two public
434 // keys of 33 bytes (+ 1 push).
435 pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 3 + 34*2;
436
437 /// A script either spendable by the revocation
438 /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
439 /// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
440 pub fn get_revokeable_redeemscript(revocation_key: &PublicKey, contest_delay: u16, broadcaster_delayed_payment_key: &PublicKey) -> Script {
441         let res = Builder::new().push_opcode(opcodes::all::OP_IF)
442                       .push_slice(&revocation_key.serialize())
443                       .push_opcode(opcodes::all::OP_ELSE)
444                       .push_int(contest_delay as i64)
445                       .push_opcode(opcodes::all::OP_CSV)
446                       .push_opcode(opcodes::all::OP_DROP)
447                       .push_slice(&broadcaster_delayed_payment_key.serialize())
448                       .push_opcode(opcodes::all::OP_ENDIF)
449                       .push_opcode(opcodes::all::OP_CHECKSIG)
450                       .into_script();
451         debug_assert!(res.len() <= REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH);
452         res
453 }
454
455 #[derive(Clone, PartialEq)]
456 /// Information about an HTLC as it appears in a commitment transaction
457 pub struct HTLCOutputInCommitment {
458         /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
459         /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
460         /// need to compare this value to whether the commitment transaction in question is that of
461         /// the counterparty or our own.
462         pub offered: bool,
463         /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
464         /// this divided by 1000.
465         pub amount_msat: u64,
466         /// The CLTV lock-time at which this HTLC expires.
467         pub cltv_expiry: u32,
468         /// The hash of the preimage which unlocks this HTLC.
469         pub payment_hash: PaymentHash,
470         /// The position within the commitment transactions' outputs. This may be None if the value is
471         /// below the dust limit (in which case no output appears in the commitment transaction and the
472         /// value is spent to additional transaction fees).
473         pub transaction_output_index: Option<u32>,
474 }
475
476 impl_writeable_tlv_based!(HTLCOutputInCommitment, {
477         (0, offered, required),
478         (2, amount_msat, required),
479         (4, cltv_expiry, required),
480         (6, payment_hash, required),
481         (8, transaction_output_index, option),
482 });
483
484 #[inline]
485 pub(crate) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, opt_anchors: bool, broadcaster_htlc_key: &PublicKey, countersignatory_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
486         let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
487         if htlc.offered {
488                 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
489                               .push_opcode(opcodes::all::OP_HASH160)
490                               .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
491                               .push_opcode(opcodes::all::OP_EQUAL)
492                               .push_opcode(opcodes::all::OP_IF)
493                               .push_opcode(opcodes::all::OP_CHECKSIG)
494                               .push_opcode(opcodes::all::OP_ELSE)
495                               .push_slice(&countersignatory_htlc_key.serialize()[..])
496                               .push_opcode(opcodes::all::OP_SWAP)
497                               .push_opcode(opcodes::all::OP_SIZE)
498                               .push_int(32)
499                               .push_opcode(opcodes::all::OP_EQUAL)
500                               .push_opcode(opcodes::all::OP_NOTIF)
501                               .push_opcode(opcodes::all::OP_DROP)
502                               .push_int(2)
503                               .push_opcode(opcodes::all::OP_SWAP)
504                               .push_slice(&broadcaster_htlc_key.serialize()[..])
505                               .push_int(2)
506                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
507                               .push_opcode(opcodes::all::OP_ELSE)
508                               .push_opcode(opcodes::all::OP_HASH160)
509                               .push_slice(&payment_hash160)
510                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
511                               .push_opcode(opcodes::all::OP_CHECKSIG)
512                               .push_opcode(opcodes::all::OP_ENDIF);
513                 if opt_anchors {
514                         bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
515                                 .push_opcode(opcodes::all::OP_CSV)
516                                 .push_opcode(opcodes::all::OP_DROP);
517                 }
518                 bldr.push_opcode(opcodes::all::OP_ENDIF)
519                         .into_script()
520         } else {
521                         let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
522                               .push_opcode(opcodes::all::OP_HASH160)
523                               .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
524                               .push_opcode(opcodes::all::OP_EQUAL)
525                               .push_opcode(opcodes::all::OP_IF)
526                               .push_opcode(opcodes::all::OP_CHECKSIG)
527                               .push_opcode(opcodes::all::OP_ELSE)
528                               .push_slice(&countersignatory_htlc_key.serialize()[..])
529                               .push_opcode(opcodes::all::OP_SWAP)
530                               .push_opcode(opcodes::all::OP_SIZE)
531                               .push_int(32)
532                               .push_opcode(opcodes::all::OP_EQUAL)
533                               .push_opcode(opcodes::all::OP_IF)
534                               .push_opcode(opcodes::all::OP_HASH160)
535                               .push_slice(&payment_hash160)
536                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
537                               .push_int(2)
538                               .push_opcode(opcodes::all::OP_SWAP)
539                               .push_slice(&broadcaster_htlc_key.serialize()[..])
540                               .push_int(2)
541                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
542                               .push_opcode(opcodes::all::OP_ELSE)
543                               .push_opcode(opcodes::all::OP_DROP)
544                               .push_int(htlc.cltv_expiry as i64)
545                               .push_opcode(opcodes::all::OP_CLTV)
546                               .push_opcode(opcodes::all::OP_DROP)
547                               .push_opcode(opcodes::all::OP_CHECKSIG)
548                               .push_opcode(opcodes::all::OP_ENDIF);
549                 if opt_anchors {
550                         bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
551                                 .push_opcode(opcodes::all::OP_CSV)
552                                 .push_opcode(opcodes::all::OP_DROP);
553                 }
554                 bldr.push_opcode(opcodes::all::OP_ENDIF)
555                         .into_script()
556         }
557 }
558
559 /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
560 /// does not need to have its previous_output_index filled.
561 #[inline]
562 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, opt_anchors: bool, keys: &TxCreationKeys) -> Script {
563         get_htlc_redeemscript_with_explicit_keys(htlc, opt_anchors, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
564 }
565
566 /// Gets the redeemscript for a funding output from the two funding public keys.
567 /// Note that the order of funding public keys does not matter.
568 pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> Script {
569         let broadcaster_funding_key = broadcaster.serialize();
570         let countersignatory_funding_key = countersignatory.serialize();
571
572         let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
573         if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
574                 builder.push_slice(&broadcaster_funding_key)
575                         .push_slice(&countersignatory_funding_key)
576         } else {
577                 builder.push_slice(&countersignatory_funding_key)
578                         .push_slice(&broadcaster_funding_key)
579         }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
580 }
581
582 /// Builds an unsigned HTLC-Success or HTLC-Timeout transaction from the given channel and HTLC
583 /// parameters. This is used by [`TrustedCommitmentTransaction::get_htlc_sigs`] to fetch the
584 /// transaction which needs signing, and can be used to construct an HTLC transaction which is
585 /// broadcastable given a counterparty HTLC signature.
586 ///
587 /// Panics if htlc.transaction_output_index.is_none() (as such HTLCs do not appear in the
588 /// commitment transaction).
589 pub fn build_htlc_transaction(commitment_txid: &Txid, feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, broadcaster_delayed_payment_key: &PublicKey, revocation_key: &PublicKey) -> Transaction {
590         let mut txins: Vec<TxIn> = Vec::new();
591         txins.push(TxIn {
592                 previous_output: OutPoint {
593                         txid: commitment_txid.clone(),
594                         vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
595                 },
596                 script_sig: Script::new(),
597                 sequence: 0,
598                 witness: Vec::new(),
599         });
600
601         let total_fee = if htlc.offered {
602                         feerate_per_kw as u64 * HTLC_TIMEOUT_TX_WEIGHT / 1000
603                 } else {
604                         feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000
605                 };
606
607         let mut txouts: Vec<TxOut> = Vec::new();
608         txouts.push(TxOut {
609                 script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_v0_p2wsh(),
610                 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)
611         });
612
613         Transaction {
614                 version: 2,
615                 lock_time: if htlc.offered { htlc.cltv_expiry } else { 0 },
616                 input: txins,
617                 output: txouts,
618         }
619 }
620
621 /// Gets the witnessScript for the to_remote output when anchors are enabled.
622 #[inline]
623 pub(crate) fn get_to_countersignatory_with_anchors_redeemscript(payment_point: &PublicKey) -> Script {
624         Builder::new()
625                 .push_slice(&payment_point.serialize()[..])
626                 .push_opcode(opcodes::all::OP_CHECKSIGVERIFY)
627                 .push_int(1)
628                 .push_opcode(opcodes::all::OP_CSV)
629                 .into_script()
630 }
631
632 /// Gets the witnessScript for an anchor output from the funding public key.
633 /// The witness in the spending input must be:
634 /// <BIP 143 funding_signature>
635 /// After 16 blocks of confirmation, an alternative satisfying witness could be:
636 /// <>
637 /// (empty vector required to satisfy compliance with MINIMALIF-standard rule)
638 #[inline]
639 pub(crate) fn get_anchor_redeemscript(funding_pubkey: &PublicKey) -> Script {
640         Builder::new().push_slice(&funding_pubkey.serialize()[..])
641                 .push_opcode(opcodes::all::OP_CHECKSIG)
642                 .push_opcode(opcodes::all::OP_IFDUP)
643                 .push_opcode(opcodes::all::OP_NOTIF)
644                 .push_int(16)
645                 .push_opcode(opcodes::all::OP_CSV)
646                 .push_opcode(opcodes::all::OP_ENDIF)
647                 .into_script()
648 }
649
650 /// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
651 /// The fields are organized by holder/counterparty.
652 ///
653 /// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
654 /// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
655 #[derive(Clone)]
656 pub struct ChannelTransactionParameters {
657         /// Holder public keys
658         pub holder_pubkeys: ChannelPublicKeys,
659         /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
660         pub holder_selected_contest_delay: u16,
661         /// Whether the holder is the initiator of this channel.
662         /// This is an input to the commitment number obscure factor computation.
663         pub is_outbound_from_holder: bool,
664         /// The late-bound counterparty channel transaction parameters.
665         /// These parameters are populated at the point in the protocol where the counterparty provides them.
666         pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
667         /// The late-bound funding outpoint
668         pub funding_outpoint: Option<chain::transaction::OutPoint>,
669         /// Are anchors used for this channel.  Boolean is serialization backwards-compatible
670         pub opt_anchors: Option<()>
671 }
672
673 /// Late-bound per-channel counterparty data used to build transactions.
674 #[derive(Clone)]
675 pub struct CounterpartyChannelTransactionParameters {
676         /// Counter-party public keys
677         pub pubkeys: ChannelPublicKeys,
678         /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
679         pub selected_contest_delay: u16,
680 }
681
682 impl ChannelTransactionParameters {
683         /// Whether the late bound parameters are populated.
684         pub fn is_populated(&self) -> bool {
685                 self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
686         }
687
688         /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
689         /// given that the holder is the broadcaster.
690         ///
691         /// self.is_populated() must be true before calling this function.
692         pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
693                 assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
694                 DirectedChannelTransactionParameters {
695                         inner: self,
696                         holder_is_broadcaster: true
697                 }
698         }
699
700         /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
701         /// given that the counterparty is the broadcaster.
702         ///
703         /// self.is_populated() must be true before calling this function.
704         pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
705                 assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
706                 DirectedChannelTransactionParameters {
707                         inner: self,
708                         holder_is_broadcaster: false
709                 }
710         }
711 }
712
713 impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, {
714         (0, pubkeys, required),
715         (2, selected_contest_delay, required),
716 });
717
718 impl_writeable_tlv_based!(ChannelTransactionParameters, {
719         (0, holder_pubkeys, required),
720         (2, holder_selected_contest_delay, required),
721         (4, is_outbound_from_holder, required),
722         (6, counterparty_parameters, option),
723         (8, funding_outpoint, option),
724         (10, opt_anchors, option),
725 });
726
727 /// Static channel fields used to build transactions given per-commitment fields, organized by
728 /// broadcaster/countersignatory.
729 ///
730 /// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
731 /// as_holder_broadcastable and as_counterparty_broadcastable functions.
732 pub struct DirectedChannelTransactionParameters<'a> {
733         /// The holder's channel static parameters
734         inner: &'a ChannelTransactionParameters,
735         /// Whether the holder is the broadcaster
736         holder_is_broadcaster: bool,
737 }
738
739 impl<'a> DirectedChannelTransactionParameters<'a> {
740         /// Get the channel pubkeys for the broadcaster
741         pub fn broadcaster_pubkeys(&self) -> &ChannelPublicKeys {
742                 if self.holder_is_broadcaster {
743                         &self.inner.holder_pubkeys
744                 } else {
745                         &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
746                 }
747         }
748
749         /// Get the channel pubkeys for the countersignatory
750         pub fn countersignatory_pubkeys(&self) -> &ChannelPublicKeys {
751                 if self.holder_is_broadcaster {
752                         &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
753                 } else {
754                         &self.inner.holder_pubkeys
755                 }
756         }
757
758         /// Get the contest delay applicable to the transactions.
759         /// Note that the contest delay was selected by the countersignatory.
760         pub fn contest_delay(&self) -> u16 {
761                 let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
762                 if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
763         }
764
765         /// Whether the channel is outbound from the broadcaster.
766         ///
767         /// The boolean representing the side that initiated the channel is
768         /// an input to the commitment number obscure factor computation.
769         pub fn is_outbound(&self) -> bool {
770                 if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
771         }
772
773         /// The funding outpoint
774         pub fn funding_outpoint(&self) -> OutPoint {
775                 self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
776         }
777 }
778
779 /// Information needed to build and sign a holder's commitment transaction.
780 ///
781 /// The transaction is only signed once we are ready to broadcast.
782 #[derive(Clone)]
783 pub struct HolderCommitmentTransaction {
784         inner: CommitmentTransaction,
785         /// Our counterparty's signature for the transaction
786         pub counterparty_sig: Signature,
787         /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
788         pub counterparty_htlc_sigs: Vec<Signature>,
789         // Which order the signatures should go in when constructing the final commitment tx witness.
790         // The user should be able to reconstruct this themselves, so we don't bother to expose it.
791         holder_sig_first: bool,
792 }
793
794 impl Deref for HolderCommitmentTransaction {
795         type Target = CommitmentTransaction;
796
797         fn deref(&self) -> &Self::Target { &self.inner }
798 }
799
800 impl PartialEq for HolderCommitmentTransaction {
801         // We dont care whether we are signed in equality comparison
802         fn eq(&self, o: &Self) -> bool {
803                 self.inner == o.inner
804         }
805 }
806
807 impl_writeable_tlv_based!(HolderCommitmentTransaction, {
808         (0, inner, required),
809         (2, counterparty_sig, required),
810         (4, holder_sig_first, required),
811         (6, counterparty_htlc_sigs, vec_type),
812 });
813
814 impl HolderCommitmentTransaction {
815         #[cfg(test)]
816         pub fn dummy() -> Self {
817                 let secp_ctx = Secp256k1::new();
818                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
819                 let dummy_sig = secp_ctx.sign(&secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
820
821                 let keys = TxCreationKeys {
822                         per_commitment_point: dummy_key.clone(),
823                         revocation_key: dummy_key.clone(),
824                         broadcaster_htlc_key: dummy_key.clone(),
825                         countersignatory_htlc_key: dummy_key.clone(),
826                         broadcaster_delayed_payment_key: dummy_key.clone(),
827                 };
828                 let channel_pubkeys = ChannelPublicKeys {
829                         funding_pubkey: dummy_key.clone(),
830                         revocation_basepoint: dummy_key.clone(),
831                         payment_point: dummy_key.clone(),
832                         delayed_payment_basepoint: dummy_key.clone(),
833                         htlc_basepoint: dummy_key.clone()
834                 };
835                 let channel_parameters = ChannelTransactionParameters {
836                         holder_pubkeys: channel_pubkeys.clone(),
837                         holder_selected_contest_delay: 0,
838                         is_outbound_from_holder: false,
839                         counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
840                         funding_outpoint: Some(chain::transaction::OutPoint { txid: Default::default(), index: 0 }),
841                         opt_anchors: None
842                 };
843                 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
844                 let inner = CommitmentTransaction::new_with_auxiliary_htlc_data(0, 0, 0, false, dummy_key.clone(), dummy_key.clone(), keys, 0, &mut htlcs_with_aux, &channel_parameters.as_counterparty_broadcastable());
845                 HolderCommitmentTransaction {
846                         inner,
847                         counterparty_sig: dummy_sig,
848                         counterparty_htlc_sigs: Vec::new(),
849                         holder_sig_first: false
850                 }
851         }
852
853         /// Create a new holder transaction with the given counterparty signatures.
854         /// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
855         pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
856                 Self {
857                         inner: commitment_tx,
858                         counterparty_sig,
859                         counterparty_htlc_sigs,
860                         holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
861                 }
862         }
863
864         pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
865                 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
866                 let mut tx = self.inner.built.transaction.clone();
867                 tx.input[0].witness.push(Vec::new());
868
869                 if self.holder_sig_first {
870                         tx.input[0].witness.push(holder_sig.serialize_der().to_vec());
871                         tx.input[0].witness.push(self.counterparty_sig.serialize_der().to_vec());
872                 } else {
873                         tx.input[0].witness.push(self.counterparty_sig.serialize_der().to_vec());
874                         tx.input[0].witness.push(holder_sig.serialize_der().to_vec());
875                 }
876                 tx.input[0].witness[1].push(SigHashType::All as u8);
877                 tx.input[0].witness[2].push(SigHashType::All as u8);
878
879                 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
880                 tx
881         }
882 }
883
884 /// A pre-built Bitcoin commitment transaction and its txid.
885 #[derive(Clone)]
886 pub struct BuiltCommitmentTransaction {
887         /// The commitment transaction
888         pub transaction: Transaction,
889         /// The txid for the commitment transaction.
890         ///
891         /// This is provided as a performance optimization, instead of calling transaction.txid()
892         /// multiple times.
893         pub txid: Txid,
894 }
895
896 impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
897         (0, transaction, required),
898         (2, txid, required),
899 });
900
901 impl BuiltCommitmentTransaction {
902         /// Get the SIGHASH_ALL sighash value of the transaction.
903         ///
904         /// This can be used to verify a signature.
905         pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
906                 let sighash = &bip143::SigHashCache::new(&self.transaction).signature_hash(0, funding_redeemscript, channel_value_satoshis, SigHashType::All)[..];
907                 hash_to_message!(sighash)
908         }
909
910         /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
911         /// because we are about to broadcast a holder transaction.
912         pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
913                 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
914                 secp_ctx.sign(&sighash, funding_key)
915         }
916 }
917
918 /// This class tracks the per-transaction information needed to build a closing transaction and will
919 /// actually build it and sign.
920 ///
921 /// This class can be used inside a signer implementation to generate a signature given the relevant
922 /// secret key.
923 pub struct ClosingTransaction {
924         to_holder_value_sat: u64,
925         to_counterparty_value_sat: u64,
926         to_holder_script: Script,
927         to_counterparty_script: Script,
928         built: Transaction,
929 }
930
931 impl ClosingTransaction {
932         /// Construct an object of the class
933         pub fn new(
934                 to_holder_value_sat: u64,
935                 to_counterparty_value_sat: u64,
936                 to_holder_script: Script,
937                 to_counterparty_script: Script,
938                 funding_outpoint: OutPoint,
939         ) -> Self {
940                 let built = build_closing_transaction(
941                         to_holder_value_sat, to_counterparty_value_sat,
942                         to_holder_script.clone(), to_counterparty_script.clone(),
943                         funding_outpoint
944                 );
945                 ClosingTransaction {
946                         to_holder_value_sat,
947                         to_counterparty_value_sat,
948                         to_holder_script,
949                         to_counterparty_script,
950                         built
951                 }
952         }
953
954         /// Trust our pre-built transaction.
955         ///
956         /// Applies a wrapper which allows access to the transaction.
957         ///
958         /// This should only be used if you fully trust the builder of this object. It should not
959         /// be used by an external signer - instead use the verify function.
960         pub fn trust(&self) -> TrustedClosingTransaction {
961                 TrustedClosingTransaction { inner: self }
962         }
963
964         /// Verify our pre-built transaction.
965         ///
966         /// Applies a wrapper which allows access to the transaction.
967         ///
968         /// An external validating signer must call this method before signing
969         /// or using the built transaction.
970         pub fn verify(&self, funding_outpoint: OutPoint) -> Result<TrustedClosingTransaction, ()> {
971                 let built = build_closing_transaction(
972                         self.to_holder_value_sat, self.to_counterparty_value_sat,
973                         self.to_holder_script.clone(), self.to_counterparty_script.clone(),
974                         funding_outpoint
975                 );
976                 if self.built != built {
977                         return Err(())
978                 }
979                 Ok(TrustedClosingTransaction { inner: self })
980         }
981
982         /// The value to be sent to the holder, or zero if the output will be omitted
983         pub fn to_holder_value_sat(&self) -> u64 {
984                 self.to_holder_value_sat
985         }
986
987         /// The value to be sent to the counterparty, or zero if the output will be omitted
988         pub fn to_counterparty_value_sat(&self) -> u64 {
989                 self.to_counterparty_value_sat
990         }
991
992         /// The destination of the holder's output
993         pub fn to_holder_script(&self) -> &Script {
994                 &self.to_holder_script
995         }
996
997         /// The destination of the counterparty's output
998         pub fn to_counterparty_script(&self) -> &Script {
999                 &self.to_counterparty_script
1000         }
1001 }
1002
1003 /// A wrapper on ClosingTransaction indicating that the built bitcoin
1004 /// transaction is trusted.
1005 ///
1006 /// See trust() and verify() functions on CommitmentTransaction.
1007 ///
1008 /// This structure implements Deref.
1009 pub struct TrustedClosingTransaction<'a> {
1010         inner: &'a ClosingTransaction,
1011 }
1012
1013 impl<'a> Deref for TrustedClosingTransaction<'a> {
1014         type Target = ClosingTransaction;
1015
1016         fn deref(&self) -> &Self::Target { self.inner }
1017 }
1018
1019 impl<'a> TrustedClosingTransaction<'a> {
1020         /// The pre-built Bitcoin commitment transaction
1021         pub fn built_transaction(&self) -> &Transaction {
1022                 &self.inner.built
1023         }
1024
1025         /// Get the SIGHASH_ALL sighash value of the transaction.
1026         ///
1027         /// This can be used to verify a signature.
1028         pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1029                 let sighash = &bip143::SigHashCache::new(&self.inner.built).signature_hash(0, funding_redeemscript, channel_value_satoshis, SigHashType::All)[..];
1030                 hash_to_message!(sighash)
1031         }
1032
1033         /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1034         /// because we are about to broadcast a holder transaction.
1035         pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1036                 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1037                 secp_ctx.sign(&sighash, funding_key)
1038         }
1039 }
1040
1041 /// This class tracks the per-transaction information needed to build a commitment transaction and will
1042 /// actually build it and sign.  It is used for holder transactions that we sign only when needed
1043 /// and for transactions we sign for the counterparty.
1044 ///
1045 /// This class can be used inside a signer implementation to generate a signature given the relevant
1046 /// secret key.
1047 #[derive(Clone)]
1048 pub struct CommitmentTransaction {
1049         commitment_number: u64,
1050         to_broadcaster_value_sat: u64,
1051         to_countersignatory_value_sat: u64,
1052         feerate_per_kw: u32,
1053         htlcs: Vec<HTLCOutputInCommitment>,
1054         // A boolean that is serialization backwards-compatible
1055         opt_anchors: Option<()>,
1056         // A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
1057         keys: TxCreationKeys,
1058         // For access to the pre-built transaction, see doc for trust()
1059         built: BuiltCommitmentTransaction,
1060 }
1061
1062 impl PartialEq for CommitmentTransaction {
1063         fn eq(&self, o: &Self) -> bool {
1064                 let eq = self.commitment_number == o.commitment_number &&
1065                         self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
1066                         self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
1067                         self.feerate_per_kw == o.feerate_per_kw &&
1068                         self.htlcs == o.htlcs &&
1069                         self.opt_anchors == o.opt_anchors &&
1070                         self.keys == o.keys;
1071                 if eq {
1072                         debug_assert_eq!(self.built.transaction, o.built.transaction);
1073                         debug_assert_eq!(self.built.txid, o.built.txid);
1074                 }
1075                 eq
1076         }
1077 }
1078
1079 impl_writeable_tlv_based!(CommitmentTransaction, {
1080         (0, commitment_number, required),
1081         (2, to_broadcaster_value_sat, required),
1082         (4, to_countersignatory_value_sat, required),
1083         (6, feerate_per_kw, required),
1084         (8, keys, required),
1085         (10, built, required),
1086         (12, htlcs, vec_type),
1087         (14, opt_anchors, option),
1088 });
1089
1090 impl CommitmentTransaction {
1091         /// Construct an object of the class while assigning transaction output indices to HTLCs.
1092         ///
1093         /// Populates HTLCOutputInCommitment.transaction_output_index in htlcs_with_aux.
1094         ///
1095         /// The generic T allows the caller to match the HTLC output index with auxiliary data.
1096         /// This auxiliary data is not stored in this object.
1097         ///
1098         /// Only include HTLCs that are above the dust limit for the channel.
1099         ///
1100         /// (C-not exported) due to the generic though we likely should expose a version without
1101         pub fn new_with_auxiliary_htlc_data<T>(commitment_number: u64, to_broadcaster_value_sat: u64, to_countersignatory_value_sat: u64, opt_anchors: bool, broadcaster_funding_key: PublicKey, countersignatory_funding_key: PublicKey, keys: TxCreationKeys, feerate_per_kw: u32, htlcs_with_aux: &mut Vec<(HTLCOutputInCommitment, T)>, channel_parameters: &DirectedChannelTransactionParameters) -> CommitmentTransaction {
1102                 // Sort outputs and populate output indices while keeping track of the auxiliary data
1103                 let (outputs, htlcs) = Self::internal_build_outputs(&keys, to_broadcaster_value_sat, to_countersignatory_value_sat, htlcs_with_aux, channel_parameters, opt_anchors, &broadcaster_funding_key, &countersignatory_funding_key).unwrap();
1104
1105                 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
1106                 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1107                 let txid = transaction.txid();
1108                 CommitmentTransaction {
1109                         commitment_number,
1110                         to_broadcaster_value_sat,
1111                         to_countersignatory_value_sat,
1112                         feerate_per_kw,
1113                         htlcs,
1114                         opt_anchors: if opt_anchors { Some(()) } else { None },
1115                         keys,
1116                         built: BuiltCommitmentTransaction {
1117                                 transaction,
1118                                 txid
1119                         },
1120                 }
1121         }
1122
1123         fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<BuiltCommitmentTransaction, ()> {
1124                 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
1125
1126                 let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
1127                 let (outputs, _) = Self::internal_build_outputs(keys, self.to_broadcaster_value_sat, self.to_countersignatory_value_sat, &mut htlcs_with_aux, channel_parameters, self.opt_anchors.is_some(), broadcaster_funding_key, countersignatory_funding_key)?;
1128
1129                 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1130                 let txid = transaction.txid();
1131                 let built_transaction = BuiltCommitmentTransaction {
1132                         transaction,
1133                         txid
1134                 };
1135                 Ok(built_transaction)
1136         }
1137
1138         fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
1139                 Transaction {
1140                         version: 2,
1141                         lock_time: ((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32),
1142                         input: txins,
1143                         output: outputs,
1144                 }
1145         }
1146
1147         // This is used in two cases:
1148         // - initial sorting of outputs / HTLCs in the constructor, in which case T is auxiliary data the
1149         //   caller needs to have sorted together with the HTLCs so it can keep track of the output index
1150         // - building of a bitcoin transaction during a verify() call, in which case T is just ()
1151         fn internal_build_outputs<T>(keys: &TxCreationKeys, to_broadcaster_value_sat: u64, to_countersignatory_value_sat: u64, htlcs_with_aux: &mut Vec<(HTLCOutputInCommitment, T)>, channel_parameters: &DirectedChannelTransactionParameters, opt_anchors: bool, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<(Vec<TxOut>, Vec<HTLCOutputInCommitment>), ()> {
1152                 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1153                 let contest_delay = channel_parameters.contest_delay();
1154
1155                 let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
1156
1157                 if to_countersignatory_value_sat > 0 {
1158                         let script = if opt_anchors {
1159                             get_to_countersignatory_with_anchors_redeemscript(&countersignatory_pubkeys.payment_point).to_v0_p2wsh()
1160                         } else {
1161                             get_p2wpkh_redeemscript(&countersignatory_pubkeys.payment_point)
1162                         };
1163                         txouts.push((
1164                                 TxOut {
1165                                         script_pubkey: script.clone(),
1166                                         value: to_countersignatory_value_sat,
1167                                 },
1168                                 None,
1169                         ))
1170                 }
1171
1172                 if to_broadcaster_value_sat > 0 {
1173                         let redeem_script = get_revokeable_redeemscript(
1174                                 &keys.revocation_key,
1175                                 contest_delay,
1176                                 &keys.broadcaster_delayed_payment_key,
1177                         );
1178                         txouts.push((
1179                                 TxOut {
1180                                         script_pubkey: redeem_script.to_v0_p2wsh(),
1181                                         value: to_broadcaster_value_sat,
1182                                 },
1183                                 None,
1184                         ));
1185                 }
1186
1187                 if opt_anchors {
1188                         if to_broadcaster_value_sat > 0 || !htlcs_with_aux.is_empty() {
1189                                 let anchor_script = get_anchor_redeemscript(broadcaster_funding_key);
1190                                 txouts.push((
1191                                         TxOut {
1192                                                 script_pubkey: anchor_script.to_v0_p2wsh(),
1193                                                 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1194                                         },
1195                                         None,
1196                                 ));
1197                         }
1198
1199                         if to_countersignatory_value_sat > 0 || !htlcs_with_aux.is_empty() {
1200                                 let anchor_script = get_anchor_redeemscript(countersignatory_funding_key);
1201                                 txouts.push((
1202                                         TxOut {
1203                                                 script_pubkey: anchor_script.to_v0_p2wsh(),
1204                                                 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1205                                         },
1206                                         None,
1207                                 ));
1208                         }
1209                 }
1210
1211                 let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
1212                 for (htlc, _) in htlcs_with_aux {
1213                         let script = chan_utils::get_htlc_redeemscript(&htlc, opt_anchors, &keys);
1214                         let txout = TxOut {
1215                                 script_pubkey: script.to_v0_p2wsh(),
1216                                 value: htlc.amount_msat / 1000,
1217                         };
1218                         txouts.push((txout, Some(htlc)));
1219                 }
1220
1221                 // Sort output in BIP-69 order (amount, scriptPubkey).  Tie-breaks based on HTLC
1222                 // CLTV expiration height.
1223                 sort_outputs(&mut txouts, |a, b| {
1224                         if let &Some(ref a_htlcout) = a {
1225                                 if let &Some(ref b_htlcout) = b {
1226                                         a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
1227                                                 // Note that due to hash collisions, we have to have a fallback comparison
1228                                                 // here for fuzztarget mode (otherwise at least chanmon_fail_consistency
1229                                                 // may fail)!
1230                                                 .then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
1231                                 // For non-HTLC outputs, if they're copying our SPK we don't really care if we
1232                                 // close the channel due to mismatches - they're doing something dumb:
1233                                 } else { cmp::Ordering::Equal }
1234                         } else { cmp::Ordering::Equal }
1235                 });
1236
1237                 let mut outputs = Vec::with_capacity(txouts.len());
1238                 for (idx, out) in txouts.drain(..).enumerate() {
1239                         if let Some(htlc) = out.1 {
1240                                 htlc.transaction_output_index = Some(idx as u32);
1241                                 htlcs.push(htlc.clone());
1242                         }
1243                         outputs.push(out.0);
1244                 }
1245                 Ok((outputs, htlcs))
1246         }
1247
1248         fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
1249                 let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
1250                 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1251                 let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
1252                         &broadcaster_pubkeys.payment_point,
1253                         &countersignatory_pubkeys.payment_point,
1254                         channel_parameters.is_outbound(),
1255                 );
1256
1257                 let obscured_commitment_transaction_number =
1258                         commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
1259
1260                 let txins = {
1261                         let mut ins: Vec<TxIn> = Vec::new();
1262                         ins.push(TxIn {
1263                                 previous_output: channel_parameters.funding_outpoint(),
1264                                 script_sig: Script::new(),
1265                                 sequence: ((0x80 as u32) << 8 * 3)
1266                                         | ((obscured_commitment_transaction_number >> 3 * 8) as u32),
1267                                 witness: Vec::new(),
1268                         });
1269                         ins
1270                 };
1271                 (obscured_commitment_transaction_number, txins)
1272         }
1273
1274         /// The backwards-counting commitment number
1275         pub fn commitment_number(&self) -> u64 {
1276                 self.commitment_number
1277         }
1278
1279         /// The value to be sent to the broadcaster
1280         pub fn to_broadcaster_value_sat(&self) -> u64 {
1281                 self.to_broadcaster_value_sat
1282         }
1283
1284         /// The value to be sent to the counterparty
1285         pub fn to_countersignatory_value_sat(&self) -> u64 {
1286                 self.to_countersignatory_value_sat
1287         }
1288
1289         /// The feerate paid per 1000-weight-unit in this commitment transaction.
1290         pub fn feerate_per_kw(&self) -> u32 {
1291                 self.feerate_per_kw
1292         }
1293
1294         /// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
1295         /// which were included in this commitment transaction in output order.
1296         /// The transaction index is always populated.
1297         ///
1298         /// (C-not exported) as we cannot currently convert Vec references to/from C, though we should
1299         /// expose a less effecient version which creates a Vec of references in the future.
1300         pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
1301                 &self.htlcs
1302         }
1303
1304         /// Trust our pre-built transaction and derived transaction creation public keys.
1305         ///
1306         /// Applies a wrapper which allows access to these fields.
1307         ///
1308         /// This should only be used if you fully trust the builder of this object.  It should not
1309         /// be used by an external signer - instead use the verify function.
1310         pub fn trust(&self) -> TrustedCommitmentTransaction {
1311                 TrustedCommitmentTransaction { inner: self }
1312         }
1313
1314         /// Verify our pre-built transaction and derived transaction creation public keys.
1315         ///
1316         /// Applies a wrapper which allows access to these fields.
1317         ///
1318         /// An external validating signer must call this method before signing
1319         /// or using the built transaction.
1320         pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
1321                 // This is the only field of the key cache that we trust
1322                 let per_commitment_point = self.keys.per_commitment_point;
1323                 let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx).unwrap();
1324                 if keys != self.keys {
1325                         return Err(());
1326                 }
1327                 let tx = self.internal_rebuild_transaction(&keys, channel_parameters, &broadcaster_keys.funding_pubkey, &countersignatory_keys.funding_pubkey)?;
1328                 if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
1329                         return Err(());
1330                 }
1331                 Ok(TrustedCommitmentTransaction { inner: self })
1332         }
1333 }
1334
1335 /// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
1336 /// transaction and the transaction creation keys) are trusted.
1337 ///
1338 /// See trust() and verify() functions on CommitmentTransaction.
1339 ///
1340 /// This structure implements Deref.
1341 pub struct TrustedCommitmentTransaction<'a> {
1342         inner: &'a CommitmentTransaction,
1343 }
1344
1345 impl<'a> Deref for TrustedCommitmentTransaction<'a> {
1346         type Target = CommitmentTransaction;
1347
1348         fn deref(&self) -> &Self::Target { self.inner }
1349 }
1350
1351 impl<'a> TrustedCommitmentTransaction<'a> {
1352         /// The transaction ID of the built Bitcoin transaction
1353         pub fn txid(&self) -> Txid {
1354                 self.inner.built.txid
1355         }
1356
1357         /// The pre-built Bitcoin commitment transaction
1358         pub fn built_transaction(&self) -> &BuiltCommitmentTransaction {
1359                 &self.inner.built
1360         }
1361
1362         /// The pre-calculated transaction creation public keys.
1363         pub fn keys(&self) -> &TxCreationKeys {
1364                 &self.inner.keys
1365         }
1366
1367         /// Should anchors be used.
1368         pub fn opt_anchors(&self) -> bool {
1369                 self.opt_anchors.is_some()
1370         }
1371
1372         /// Get a signature for each HTLC which was included in the commitment transaction (ie for
1373         /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
1374         ///
1375         /// The returned Vec has one entry for each HTLC, and in the same order.
1376         pub fn get_htlc_sigs<T: secp256k1::Signing>(&self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters, secp_ctx: &Secp256k1<T>) -> Result<Vec<Signature>, ()> {
1377                 let inner = self.inner;
1378                 let keys = &inner.keys;
1379                 let txid = inner.built.txid;
1380                 let mut ret = Vec::with_capacity(inner.htlcs.len());
1381                 let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key).map_err(|_| ())?;
1382
1383                 for this_htlc in inner.htlcs.iter() {
1384                         assert!(this_htlc.transaction_output_index.is_some());
1385                         let htlc_tx = build_htlc_transaction(&txid, inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc, &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
1386
1387                         let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc, self.opt_anchors(), &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key);
1388
1389                         let sighash = hash_to_message!(&bip143::SigHashCache::new(&htlc_tx).signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, SigHashType::All)[..]);
1390                         ret.push(secp_ctx.sign(&sighash, &holder_htlc_key));
1391                 }
1392                 Ok(ret)
1393         }
1394
1395         /// Gets a signed HTLC transaction given a preimage (for !htlc.offered) and the holder HTLC transaction signature.
1396         pub(crate) fn get_signed_htlc_tx(&self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature, preimage: &Option<PaymentPreimage>) -> Transaction {
1397                 let inner = self.inner;
1398                 let keys = &inner.keys;
1399                 let txid = inner.built.txid;
1400                 let this_htlc = &inner.htlcs[htlc_index];
1401                 assert!(this_htlc.transaction_output_index.is_some());
1402                 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
1403                 if !this_htlc.offered && preimage.is_none() { unreachable!(); }
1404                 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
1405                 if  this_htlc.offered && preimage.is_some() { unreachable!(); }
1406
1407                 let mut htlc_tx = build_htlc_transaction(&txid, inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc, &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
1408
1409                 let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc, self.opt_anchors(), &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key);
1410
1411                 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
1412                 htlc_tx.input[0].witness.push(Vec::new());
1413
1414                 htlc_tx.input[0].witness.push(counterparty_signature.serialize_der().to_vec());
1415                 htlc_tx.input[0].witness.push(signature.serialize_der().to_vec());
1416                 htlc_tx.input[0].witness[1].push(SigHashType::All as u8);
1417                 htlc_tx.input[0].witness[2].push(SigHashType::All as u8);
1418
1419                 if this_htlc.offered {
1420                         // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
1421                         htlc_tx.input[0].witness.push(Vec::new());
1422                 } else {
1423                         htlc_tx.input[0].witness.push(preimage.unwrap().0.to_vec());
1424                 }
1425
1426                 htlc_tx.input[0].witness.push(htlc_redeemscript.as_bytes().to_vec());
1427                 htlc_tx
1428         }
1429 }
1430
1431 /// Commitment transaction numbers which appear in the transactions themselves are XOR'd with a
1432 /// shared secret first. This prevents on-chain observers from discovering how many commitment
1433 /// transactions occurred in a channel before it was closed.
1434 ///
1435 /// This function gets the shared secret from relevant channel public keys and can be used to
1436 /// "decrypt" the commitment transaction number given a commitment transaction on-chain.
1437 pub fn get_commitment_transaction_number_obscure_factor(
1438         broadcaster_payment_basepoint: &PublicKey,
1439         countersignatory_payment_basepoint: &PublicKey,
1440         outbound_from_broadcaster: bool,
1441 ) -> u64 {
1442         let mut sha = Sha256::engine();
1443
1444         if outbound_from_broadcaster {
1445                 sha.input(&broadcaster_payment_basepoint.serialize());
1446                 sha.input(&countersignatory_payment_basepoint.serialize());
1447         } else {
1448                 sha.input(&countersignatory_payment_basepoint.serialize());
1449                 sha.input(&broadcaster_payment_basepoint.serialize());
1450         }
1451         let res = Sha256::from_engine(sha).into_inner();
1452
1453         ((res[26] as u64) << 5 * 8)
1454                 | ((res[27] as u64) << 4 * 8)
1455                 | ((res[28] as u64) << 3 * 8)
1456                 | ((res[29] as u64) << 2 * 8)
1457                 | ((res[30] as u64) << 1 * 8)
1458                 | ((res[31] as u64) << 0 * 8)
1459 }
1460
1461 fn get_p2wpkh_redeemscript(key: &PublicKey) -> Script {
1462         Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1463                 .push_slice(&WPubkeyHash::hash(&key.serialize())[..])
1464                 .into_script()
1465 }
1466
1467 #[cfg(test)]
1468 mod tests {
1469         use super::CounterpartyCommitmentSecrets;
1470         use ::{hex, chain};
1471         use prelude::*;
1472         use ln::chan_utils::{get_htlc_redeemscript, get_to_countersignatory_with_anchors_redeemscript, get_p2wpkh_redeemscript, CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
1473         use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
1474         use util::test_utils;
1475         use chain::keysinterface::{KeysInterface, BaseSign};
1476         use bitcoin::Network;
1477         use ln::PaymentHash;
1478
1479         #[test]
1480         fn test_anchors() {
1481                 let secp_ctx = Secp256k1::new();
1482
1483                 let seed = [42; 32];
1484                 let network = Network::Testnet;
1485                 let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
1486                 let signer = keys_provider.get_channel_signer(false, 3000);
1487                 let counterparty_signer = keys_provider.get_channel_signer(false, 3000);
1488                 let delayed_payment_base = &signer.pubkeys().delayed_payment_basepoint;
1489                 let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
1490                 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
1491                 let htlc_basepoint = &signer.pubkeys().htlc_basepoint;
1492                 let holder_pubkeys = signer.pubkeys();
1493                 let counterparty_pubkeys = counterparty_signer.pubkeys();
1494                 let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint).unwrap();
1495                 let mut channel_parameters = ChannelTransactionParameters {
1496                         holder_pubkeys: holder_pubkeys.clone(),
1497                         holder_selected_contest_delay: 0,
1498                         is_outbound_from_holder: false,
1499                         counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: counterparty_pubkeys.clone(), selected_contest_delay: 0 }),
1500                         funding_outpoint: Some(chain::transaction::OutPoint { txid: Default::default(), index: 0 }),
1501                         opt_anchors: None
1502                 };
1503
1504                 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
1505
1506                 // Generate broadcaster and counterparty outputs
1507                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1508                         0, 1000, 2000,
1509                         false,
1510                         holder_pubkeys.funding_pubkey,
1511                         counterparty_pubkeys.funding_pubkey,
1512                         keys.clone(), 1,
1513                         &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1514                 );
1515                 assert_eq!(tx.built.transaction.output.len(), 2);
1516                 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_p2wpkh_redeemscript(&counterparty_pubkeys.payment_point));
1517
1518                 // Generate broadcaster and counterparty outputs as well as two anchors
1519                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1520                         0, 1000, 2000,
1521                         true,
1522                         holder_pubkeys.funding_pubkey,
1523                         counterparty_pubkeys.funding_pubkey,
1524                         keys.clone(), 1,
1525                         &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1526                 );
1527                 assert_eq!(tx.built.transaction.output.len(), 4);
1528                 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_to_countersignatory_with_anchors_redeemscript(&counterparty_pubkeys.payment_point).to_v0_p2wsh());
1529
1530                 // Generate broadcaster output and anchor
1531                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1532                         0, 3000, 0,
1533                         true,
1534                         holder_pubkeys.funding_pubkey,
1535                         counterparty_pubkeys.funding_pubkey,
1536                         keys.clone(), 1,
1537                         &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1538                 );
1539                 assert_eq!(tx.built.transaction.output.len(), 2);
1540
1541                 // Generate counterparty output and anchor
1542                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1543                         0, 0, 3000,
1544                         true,
1545                         holder_pubkeys.funding_pubkey,
1546                         counterparty_pubkeys.funding_pubkey,
1547                         keys.clone(), 1,
1548                         &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1549                 );
1550                 assert_eq!(tx.built.transaction.output.len(), 2);
1551
1552                 let received_htlc = HTLCOutputInCommitment {
1553                         offered: false,
1554                         amount_msat: 400000,
1555                         cltv_expiry: 100,
1556                         payment_hash: PaymentHash([42; 32]),
1557                         transaction_output_index: None,
1558                 };
1559
1560                 let offered_htlc = HTLCOutputInCommitment {
1561                         offered: true,
1562                         amount_msat: 600000,
1563                         cltv_expiry: 100,
1564                         payment_hash: PaymentHash([43; 32]),
1565                         transaction_output_index: None,
1566                 };
1567
1568                 // Generate broadcaster output and received and offered HTLC outputs,  w/o anchors
1569                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1570                         0, 3000, 0,
1571                         false,
1572                         holder_pubkeys.funding_pubkey,
1573                         counterparty_pubkeys.funding_pubkey,
1574                         keys.clone(), 1,
1575                         &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1576                         &channel_parameters.as_holder_broadcastable()
1577                 );
1578                 assert_eq!(tx.built.transaction.output.len(), 3);
1579                 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_htlc_redeemscript(&received_htlc, false, &keys).to_v0_p2wsh());
1580                 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&offered_htlc, false, &keys).to_v0_p2wsh());
1581
1582                 // Generate broadcaster output and received and offered HTLC outputs,  with anchors
1583                 channel_parameters.opt_anchors = Some(());
1584                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1585                         0, 3000, 0,
1586                         true,
1587                         holder_pubkeys.funding_pubkey,
1588                         counterparty_pubkeys.funding_pubkey,
1589                         keys.clone(), 1,
1590                         &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1591                         &channel_parameters.as_holder_broadcastable()
1592                 );
1593                 assert_eq!(tx.built.transaction.output.len(), 5);
1594                 assert_eq!(tx.built.transaction.output[2].script_pubkey, get_htlc_redeemscript(&received_htlc, true, &keys).to_v0_p2wsh());
1595                 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_htlc_redeemscript(&offered_htlc, true, &keys).to_v0_p2wsh());
1596         }
1597
1598         #[test]
1599         fn test_per_commitment_storage() {
1600                 // Test vectors from BOLT 3:
1601                 let mut secrets: Vec<[u8; 32]> = Vec::new();
1602                 let mut monitor;
1603
1604                 macro_rules! test_secrets {
1605                         () => {
1606                                 let mut idx = 281474976710655;
1607                                 for secret in secrets.iter() {
1608                                         assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1609                                         idx -= 1;
1610                                 }
1611                                 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1612                                 assert!(monitor.get_secret(idx).is_none());
1613                         };
1614                 }
1615
1616                 {
1617                         // insert_secret correct sequence
1618                         monitor = CounterpartyCommitmentSecrets::new();
1619                         secrets.clear();
1620
1621                         secrets.push([0; 32]);
1622                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1623                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1624                         test_secrets!();
1625
1626                         secrets.push([0; 32]);
1627                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1628                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1629                         test_secrets!();
1630
1631                         secrets.push([0; 32]);
1632                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1633                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1634                         test_secrets!();
1635
1636                         secrets.push([0; 32]);
1637                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1638                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1639                         test_secrets!();
1640
1641                         secrets.push([0; 32]);
1642                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1643                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1644                         test_secrets!();
1645
1646                         secrets.push([0; 32]);
1647                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1648                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1649                         test_secrets!();
1650
1651                         secrets.push([0; 32]);
1652                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1653                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1654                         test_secrets!();
1655
1656                         secrets.push([0; 32]);
1657                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1658                         monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
1659                         test_secrets!();
1660                 }
1661
1662                 {
1663                         // insert_secret #1 incorrect
1664                         monitor = CounterpartyCommitmentSecrets::new();
1665                         secrets.clear();
1666
1667                         secrets.push([0; 32]);
1668                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1669                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1670                         test_secrets!();
1671
1672                         secrets.push([0; 32]);
1673                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1674                         assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
1675                 }
1676
1677                 {
1678                         // insert_secret #2 incorrect (#1 derived from incorrect)
1679                         monitor = CounterpartyCommitmentSecrets::new();
1680                         secrets.clear();
1681
1682                         secrets.push([0; 32]);
1683                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1684                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1685                         test_secrets!();
1686
1687                         secrets.push([0; 32]);
1688                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1689                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1690                         test_secrets!();
1691
1692                         secrets.push([0; 32]);
1693                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1694                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1695                         test_secrets!();
1696
1697                         secrets.push([0; 32]);
1698                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1699                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1700                 }
1701
1702                 {
1703                         // insert_secret #3 incorrect
1704                         monitor = CounterpartyCommitmentSecrets::new();
1705                         secrets.clear();
1706
1707                         secrets.push([0; 32]);
1708                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1709                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1710                         test_secrets!();
1711
1712                         secrets.push([0; 32]);
1713                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1714                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1715                         test_secrets!();
1716
1717                         secrets.push([0; 32]);
1718                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1719                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1720                         test_secrets!();
1721
1722                         secrets.push([0; 32]);
1723                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1724                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1725                 }
1726
1727                 {
1728                         // insert_secret #4 incorrect (1,2,3 derived from incorrect)
1729                         monitor = CounterpartyCommitmentSecrets::new();
1730                         secrets.clear();
1731
1732                         secrets.push([0; 32]);
1733                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1734                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1735                         test_secrets!();
1736
1737                         secrets.push([0; 32]);
1738                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1739                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1740                         test_secrets!();
1741
1742                         secrets.push([0; 32]);
1743                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1744                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1745                         test_secrets!();
1746
1747                         secrets.push([0; 32]);
1748                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
1749                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1750                         test_secrets!();
1751
1752                         secrets.push([0; 32]);
1753                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1754                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1755                         test_secrets!();
1756
1757                         secrets.push([0; 32]);
1758                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1759                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1760                         test_secrets!();
1761
1762                         secrets.push([0; 32]);
1763                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1764                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1765                         test_secrets!();
1766
1767                         secrets.push([0; 32]);
1768                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1769                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1770                 }
1771
1772                 {
1773                         // insert_secret #5 incorrect
1774                         monitor = CounterpartyCommitmentSecrets::new();
1775                         secrets.clear();
1776
1777                         secrets.push([0; 32]);
1778                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1779                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1780                         test_secrets!();
1781
1782                         secrets.push([0; 32]);
1783                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1784                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1785                         test_secrets!();
1786
1787                         secrets.push([0; 32]);
1788                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1789                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1790                         test_secrets!();
1791
1792                         secrets.push([0; 32]);
1793                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1794                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1795                         test_secrets!();
1796
1797                         secrets.push([0; 32]);
1798                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1799                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1800                         test_secrets!();
1801
1802                         secrets.push([0; 32]);
1803                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1804                         assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
1805                 }
1806
1807                 {
1808                         // insert_secret #6 incorrect (5 derived from incorrect)
1809                         monitor = CounterpartyCommitmentSecrets::new();
1810                         secrets.clear();
1811
1812                         secrets.push([0; 32]);
1813                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1814                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1815                         test_secrets!();
1816
1817                         secrets.push([0; 32]);
1818                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1819                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1820                         test_secrets!();
1821
1822                         secrets.push([0; 32]);
1823                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1824                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1825                         test_secrets!();
1826
1827                         secrets.push([0; 32]);
1828                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1829                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1830                         test_secrets!();
1831
1832                         secrets.push([0; 32]);
1833                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1834                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1835                         test_secrets!();
1836
1837                         secrets.push([0; 32]);
1838                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
1839                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1840                         test_secrets!();
1841
1842                         secrets.push([0; 32]);
1843                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1844                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1845                         test_secrets!();
1846
1847                         secrets.push([0; 32]);
1848                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1849                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1850                 }
1851
1852                 {
1853                         // insert_secret #7 incorrect
1854                         monitor = CounterpartyCommitmentSecrets::new();
1855                         secrets.clear();
1856
1857                         secrets.push([0; 32]);
1858                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1859                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1860                         test_secrets!();
1861
1862                         secrets.push([0; 32]);
1863                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1864                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1865                         test_secrets!();
1866
1867                         secrets.push([0; 32]);
1868                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1869                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1870                         test_secrets!();
1871
1872                         secrets.push([0; 32]);
1873                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1874                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1875                         test_secrets!();
1876
1877                         secrets.push([0; 32]);
1878                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1879                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1880                         test_secrets!();
1881
1882                         secrets.push([0; 32]);
1883                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1884                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1885                         test_secrets!();
1886
1887                         secrets.push([0; 32]);
1888                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
1889                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1890                         test_secrets!();
1891
1892                         secrets.push([0; 32]);
1893                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1894                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1895                 }
1896
1897                 {
1898                         // insert_secret #8 incorrect
1899                         monitor = CounterpartyCommitmentSecrets::new();
1900                         secrets.clear();
1901
1902                         secrets.push([0; 32]);
1903                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1904                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1905                         test_secrets!();
1906
1907                         secrets.push([0; 32]);
1908                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1909                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1910                         test_secrets!();
1911
1912                         secrets.push([0; 32]);
1913                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1914                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1915                         test_secrets!();
1916
1917                         secrets.push([0; 32]);
1918                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1919                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1920                         test_secrets!();
1921
1922                         secrets.push([0; 32]);
1923                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1924                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1925                         test_secrets!();
1926
1927                         secrets.push([0; 32]);
1928                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1929                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1930                         test_secrets!();
1931
1932                         secrets.push([0; 32]);
1933                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1934                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1935                         test_secrets!();
1936
1937                         secrets.push([0; 32]);
1938                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
1939                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1940                 }
1941         }
1942 }