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