Pull anchor check into helper function
[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 related to channels. These are
11 //! largely of interest for those implementing the traits on [`crate::sign`] by hand.
12
13 use bitcoin::blockdata::script::{Script, ScriptBuf, Builder};
14 use bitcoin::blockdata::opcodes;
15 use bitcoin::blockdata::transaction::{TxIn,TxOut,OutPoint,Transaction};
16 use bitcoin::sighash;
17 use bitcoin::sighash::EcdsaSighashType;
18 use bitcoin::address::Payload;
19
20 use bitcoin::hashes::{Hash, HashEngine};
21 use bitcoin::hashes::sha256::Hash as Sha256;
22 use bitcoin::hashes::ripemd160::Hash as Ripemd160;
23 use bitcoin::hash_types::{Txid, PubkeyHash, WPubkeyHash};
24
25 use crate::chain::chaininterface::fee_for_weight;
26 use crate::chain::package::WEIGHT_REVOKED_OUTPUT;
27 use crate::sign::EntropySource;
28 use crate::ln::{PaymentHash, PaymentPreimage};
29 use crate::ln::msgs::DecodeError;
30 use crate::util::ser::{Readable, RequiredWrapper, Writeable, Writer};
31 use crate::util::transaction_utils;
32
33 use bitcoin::blockdata::locktime::absolute::LockTime;
34 use bitcoin::secp256k1::{SecretKey, PublicKey, Scalar};
35 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature, Message};
36 use bitcoin::{secp256k1, Sequence, Witness};
37 use bitcoin::PublicKey as BitcoinPublicKey;
38
39 use crate::io;
40 use core::cmp;
41 use crate::ln::chan_utils;
42 use crate::util::transaction_utils::sort_outputs;
43 use crate::ln::channel::{INITIAL_COMMITMENT_NUMBER, ANCHOR_OUTPUT_VALUE_SATOSHI};
44 use core::ops::Deref;
45 use crate::chain;
46 use crate::ln::features::ChannelTypeFeatures;
47 use crate::crypto::utils::{sign, sign_with_aux_rand};
48 use super::channel_keys::{DelayedPaymentBasepoint, DelayedPaymentKey, HtlcKey, HtlcBasepoint, RevocationKey, RevocationBasepoint};
49
50 #[allow(unused_imports)]
51 use crate::prelude::*;
52
53 /// Maximum number of one-way in-flight HTLC (protocol-level value).
54 pub const MAX_HTLCS: u16 = 483;
55 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, non-anchor variant.
56 pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
57 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, anchor variant.
58 pub const OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS: usize = 136;
59
60 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
61 /// We define a range that encompasses both its non-anchors and anchors variants.
62 pub(crate) const MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 136;
63 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
64 /// We define a range that encompasses both its non-anchors and anchors variants.
65 /// This is the maximum post-anchor value.
66 pub const MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 143;
67
68 /// The upper bound weight of an anchor input.
69 pub const ANCHOR_INPUT_WITNESS_WEIGHT: u64 = 116;
70 /// The upper bound weight of an HTLC timeout input from a commitment transaction with anchor
71 /// outputs.
72 pub const HTLC_TIMEOUT_INPUT_ANCHOR_WITNESS_WEIGHT: u64 = 288;
73 /// The upper bound weight of an HTLC success input from a commitment transaction with anchor
74 /// outputs.
75 pub const HTLC_SUCCESS_INPUT_ANCHOR_WITNESS_WEIGHT: u64 = 327;
76
77 /// Gets the weight for an HTLC-Success transaction.
78 #[inline]
79 pub fn htlc_success_tx_weight(channel_type_features: &ChannelTypeFeatures) -> u64 {
80         const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
81         const HTLC_SUCCESS_ANCHOR_TX_WEIGHT: u64 = 706;
82         if channel_type_features.supports_anchors_zero_fee_htlc_tx() { HTLC_SUCCESS_ANCHOR_TX_WEIGHT } else { HTLC_SUCCESS_TX_WEIGHT }
83 }
84
85 /// Gets the weight for an HTLC-Timeout transaction.
86 #[inline]
87 pub fn htlc_timeout_tx_weight(channel_type_features: &ChannelTypeFeatures) -> u64 {
88         const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
89         const HTLC_TIMEOUT_ANCHOR_TX_WEIGHT: u64 = 666;
90         if channel_type_features.supports_anchors_zero_fee_htlc_tx() { HTLC_TIMEOUT_ANCHOR_TX_WEIGHT } else { HTLC_TIMEOUT_TX_WEIGHT }
91 }
92
93 /// Describes the type of HTLC claim as determined by analyzing the witness.
94 #[derive(PartialEq, Eq)]
95 pub enum HTLCClaim {
96         /// Claims an offered output on a commitment transaction through the timeout path.
97         OfferedTimeout,
98         /// Claims an offered output on a commitment transaction through the success path.
99         OfferedPreimage,
100         /// Claims an accepted output on a commitment transaction through the timeout path.
101         AcceptedTimeout,
102         /// Claims an accepted output on a commitment transaction through the success path.
103         AcceptedPreimage,
104         /// Claims an offered/accepted output on a commitment transaction through the revocation path.
105         Revocation,
106 }
107
108 impl HTLCClaim {
109         /// Check if a given input witness attempts to claim a HTLC.
110         pub fn from_witness(witness: &Witness) -> Option<Self> {
111                 debug_assert_eq!(OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS, MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT);
112                 if witness.len() < 2 {
113                         return None;
114                 }
115                 let witness_script = witness.last().unwrap();
116                 let second_to_last = witness.second_to_last().unwrap();
117                 if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT {
118                         if witness.len() == 3 && second_to_last.len() == 33 {
119                                 // <revocation sig> <revocationpubkey> <witness_script>
120                                 Some(Self::Revocation)
121                         } else if witness.len() == 3 && second_to_last.len() == 32 {
122                                 // <remotehtlcsig> <payment_preimage> <witness_script>
123                                 Some(Self::OfferedPreimage)
124                         } else if witness.len() == 5 && second_to_last.len() == 0 {
125                                 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
126                                 Some(Self::OfferedTimeout)
127                         } else {
128                                 None
129                         }
130                 } else if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS {
131                         // It's possible for the weight of `offered_htlc_script` and `accepted_htlc_script` to
132                         // match so we check for both here.
133                         if witness.len() == 3 && second_to_last.len() == 33 {
134                                 // <revocation sig> <revocationpubkey> <witness_script>
135                                 Some(Self::Revocation)
136                         } else if witness.len() == 3 && second_to_last.len() == 32 {
137                                 // <remotehtlcsig> <payment_preimage> <witness_script>
138                                 Some(Self::OfferedPreimage)
139                         } else if witness.len() == 5 && second_to_last.len() == 0 {
140                                 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
141                                 Some(Self::OfferedTimeout)
142                         } else if witness.len() == 3 && second_to_last.len() == 0 {
143                                 // <remotehtlcsig> <> <witness_script>
144                                 Some(Self::AcceptedTimeout)
145                         } else if witness.len() == 5 && second_to_last.len() == 32 {
146                                 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
147                                 Some(Self::AcceptedPreimage)
148                         } else {
149                                 None
150                         }
151                 } else if witness_script.len() > MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT &&
152                         witness_script.len() <= MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT {
153                         // Handle remaining range of ACCEPTED_HTLC_SCRIPT_WEIGHT.
154                         if witness.len() == 3 && second_to_last.len() == 33 {
155                                 // <revocation sig> <revocationpubkey> <witness_script>
156                                 Some(Self::Revocation)
157                         } else if witness.len() == 3 && second_to_last.len() == 0 {
158                                 // <remotehtlcsig> <> <witness_script>
159                                 Some(Self::AcceptedTimeout)
160                         } else if witness.len() == 5 && second_to_last.len() == 32 {
161                                 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
162                                 Some(Self::AcceptedPreimage)
163                         } else {
164                                 None
165                         }
166                 } else {
167                         None
168                 }
169         }
170 }
171
172 // Various functions for key derivation and transaction creation for use within channels. Primarily
173 // used in Channel and ChannelMonitor.
174
175 /// Build the commitment secret from the seed and the commitment number
176 pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
177         let mut res: [u8; 32] = commitment_seed.clone();
178         for i in 0..48 {
179                 let bitpos = 47 - i;
180                 if idx & (1 << bitpos) == (1 << bitpos) {
181                         res[bitpos / 8] ^= 1 << (bitpos & 7);
182                         res = Sha256::hash(&res).to_byte_array();
183                 }
184         }
185         res
186 }
187
188 /// Build a closing transaction
189 pub fn build_closing_transaction(to_holder_value_sat: u64, to_counterparty_value_sat: u64, to_holder_script: ScriptBuf, to_counterparty_script: ScriptBuf, funding_outpoint: OutPoint) -> Transaction {
190         let txins = {
191                 let mut ins: Vec<TxIn> = Vec::new();
192                 ins.push(TxIn {
193                         previous_output: funding_outpoint,
194                         script_sig: ScriptBuf::new(),
195                         sequence: Sequence::MAX,
196                         witness: Witness::new(),
197                 });
198                 ins
199         };
200
201         let mut txouts: Vec<(TxOut, ())> = Vec::new();
202
203         if to_counterparty_value_sat > 0 {
204                 txouts.push((TxOut {
205                         script_pubkey: to_counterparty_script,
206                         value: to_counterparty_value_sat
207                 }, ()));
208         }
209
210         if to_holder_value_sat > 0 {
211                 txouts.push((TxOut {
212                         script_pubkey: to_holder_script,
213                         value: to_holder_value_sat
214                 }, ()));
215         }
216
217         transaction_utils::sort_outputs(&mut txouts, |_, _| { cmp::Ordering::Equal }); // Ordering doesnt matter if they used our pubkey...
218
219         let mut outputs: Vec<TxOut> = Vec::new();
220         for out in txouts.drain(..) {
221                 outputs.push(out.0);
222         }
223
224         Transaction {
225                 version: 2,
226                 lock_time: LockTime::ZERO,
227                 input: txins,
228                 output: outputs,
229         }
230 }
231
232 /// Implements the per-commitment secret storage scheme from
233 /// [BOLT 3](https://github.com/lightning/bolts/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
234 ///
235 /// Allows us to keep track of all of the revocation secrets of our counterparty in just 50*32 bytes
236 /// or so.
237 #[derive(Clone)]
238 pub struct CounterpartyCommitmentSecrets {
239         old_secrets: [([u8; 32], u64); 49],
240 }
241
242 impl Eq for CounterpartyCommitmentSecrets {}
243 impl PartialEq for CounterpartyCommitmentSecrets {
244         fn eq(&self, other: &Self) -> bool {
245                 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
246                         if secret != o_secret || idx != o_idx {
247                                 return false
248                         }
249                 }
250                 true
251         }
252 }
253
254 impl CounterpartyCommitmentSecrets {
255         /// Creates a new empty `CounterpartyCommitmentSecrets` structure.
256         pub fn new() -> Self {
257                 Self { old_secrets: [([0; 32], 1 << 48); 49], }
258         }
259
260         #[inline]
261         fn place_secret(idx: u64) -> u8 {
262                 for i in 0..48 {
263                         if idx & (1 << i) == (1 << i) {
264                                 return i
265                         }
266                 }
267                 48
268         }
269
270         /// Returns the minimum index of all stored secrets. Note that indexes start
271         /// at 1 << 48 and get decremented by one for each new secret.
272         pub fn get_min_seen_secret(&self) -> u64 {
273                 //TODO This can be optimized?
274                 let mut min = 1 << 48;
275                 for &(_, idx) in self.old_secrets.iter() {
276                         if idx < min {
277                                 min = idx;
278                         }
279                 }
280                 min
281         }
282
283         #[inline]
284         fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
285                 let mut res: [u8; 32] = secret;
286                 for i in 0..bits {
287                         let bitpos = bits - 1 - i;
288                         if idx & (1 << bitpos) == (1 << bitpos) {
289                                 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
290                                 res = Sha256::hash(&res).to_byte_array();
291                         }
292                 }
293                 res
294         }
295
296         /// Inserts the `secret` at `idx`. Returns `Ok(())` if the secret
297         /// was generated in accordance with BOLT 3 and is consistent with previous secrets.
298         pub fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
299                 let pos = Self::place_secret(idx);
300                 for i in 0..pos {
301                         let (old_secret, old_idx) = self.old_secrets[i as usize];
302                         if Self::derive_secret(secret, pos, old_idx) != old_secret {
303                                 return Err(());
304                         }
305                 }
306                 if self.get_min_seen_secret() <= idx {
307                         return Ok(());
308                 }
309                 self.old_secrets[pos as usize] = (secret, idx);
310                 Ok(())
311         }
312
313         /// Returns the secret at `idx`.
314         /// Returns `None` if `idx` is < [`CounterpartyCommitmentSecrets::get_min_seen_secret`].
315         pub fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
316                 for i in 0..self.old_secrets.len() {
317                         if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
318                                 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
319                         }
320                 }
321                 assert!(idx < self.get_min_seen_secret());
322                 None
323         }
324 }
325
326 impl Writeable for CounterpartyCommitmentSecrets {
327         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
328                 for &(ref secret, ref idx) in self.old_secrets.iter() {
329                         writer.write_all(secret)?;
330                         writer.write_all(&idx.to_be_bytes())?;
331                 }
332                 write_tlv_fields!(writer, {});
333                 Ok(())
334         }
335 }
336 impl Readable for CounterpartyCommitmentSecrets {
337         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
338                 let mut old_secrets = [([0; 32], 1 << 48); 49];
339                 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
340                         *secret = Readable::read(reader)?;
341                         *idx = Readable::read(reader)?;
342                 }
343                 read_tlv_fields!(reader, {});
344                 Ok(Self { old_secrets })
345         }
346 }
347
348 /// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
349 /// from the base secret and the per_commitment_point.
350 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> SecretKey {
351         let mut sha = Sha256::engine();
352         sha.input(&per_commitment_point.serialize());
353         sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
354         let res = Sha256::from_engine(sha).to_byte_array();
355
356         base_secret.clone().add_tweak(&Scalar::from_be_bytes(res).unwrap())
357                 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak contains the hash of the key.")
358 }
359
360 /// Derives a per-commitment-transaction revocation key from its constituent parts.
361 ///
362 /// Only the cheating participant owns a valid witness to propagate a revoked
363 /// commitment transaction, thus per_commitment_secret always come from cheater
364 /// and revocation_base_secret always come from punisher, which is the broadcaster
365 /// of the transaction spending with this key knowledge.
366 pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>,
367         per_commitment_secret: &SecretKey, countersignatory_revocation_base_secret: &SecretKey)
368 -> SecretKey {
369         let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
370         let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
371
372         let rev_append_commit_hash_key = {
373                 let mut sha = Sha256::engine();
374                 sha.input(&countersignatory_revocation_base_point.serialize());
375                 sha.input(&per_commitment_point.serialize());
376
377                 Sha256::from_engine(sha).to_byte_array()
378         };
379         let commit_append_rev_hash_key = {
380                 let mut sha = Sha256::engine();
381                 sha.input(&per_commitment_point.serialize());
382                 sha.input(&countersignatory_revocation_base_point.serialize());
383
384                 Sha256::from_engine(sha).to_byte_array()
385         };
386
387         let countersignatory_contrib = countersignatory_revocation_base_secret.clone().mul_tweak(&Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
388                 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
389         let broadcaster_contrib = per_commitment_secret.clone().mul_tweak(&Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
390                 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
391         countersignatory_contrib.add_tweak(&Scalar::from_be_bytes(broadcaster_contrib.secret_bytes()).unwrap())
392                 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
393 }
394
395 /// The set of public keys which are used in the creation of one commitment transaction.
396 /// These are derived from the channel base keys and per-commitment data.
397 ///
398 /// A broadcaster key is provided from potential broadcaster of the computed transaction.
399 /// A countersignatory key is coming from a protocol participant unable to broadcast the
400 /// transaction.
401 ///
402 /// These keys are assumed to be good, either because the code derived them from
403 /// channel basepoints via the new function, or they were obtained via
404 /// CommitmentTransaction.trust().keys() because we trusted the source of the
405 /// pre-calculated keys.
406 #[derive(PartialEq, Eq, Clone, Debug)]
407 pub struct TxCreationKeys {
408         /// The broadcaster's per-commitment public key which was used to derive the other keys.
409         pub per_commitment_point: PublicKey,
410         /// The revocation key which is used to allow the broadcaster of the commitment
411         /// transaction to provide their counterparty the ability to punish them if they broadcast
412         /// an old state.
413         pub revocation_key: RevocationKey,
414         /// Broadcaster's HTLC Key
415         pub broadcaster_htlc_key: HtlcKey,
416         /// Countersignatory's HTLC Key
417         pub countersignatory_htlc_key: HtlcKey,
418         /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
419         pub broadcaster_delayed_payment_key: DelayedPaymentKey,
420 }
421
422 impl_writeable_tlv_based!(TxCreationKeys, {
423         (0, per_commitment_point, required),
424         (2, revocation_key, required),
425         (4, broadcaster_htlc_key, required),
426         (6, countersignatory_htlc_key, required),
427         (8, broadcaster_delayed_payment_key, required),
428 });
429
430 /// One counterparty's public keys which do not change over the life of a channel.
431 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
432 pub struct ChannelPublicKeys {
433         /// The public key which is used to sign all commitment transactions, as it appears in the
434         /// on-chain channel lock-in 2-of-2 multisig output.
435         pub funding_pubkey: PublicKey,
436         /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
437         /// revocation keys. This is combined with the per-commitment-secret generated by the
438         /// counterparty to create a secret which the counterparty can reveal to revoke previous
439         /// states.
440         pub revocation_basepoint: RevocationBasepoint,
441         /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
442         /// spendable primary channel balance on the broadcaster's commitment transaction. This key is
443         /// static across every commitment transaction.
444         pub payment_point: PublicKey,
445         /// The base point which is used (with derive_public_key) to derive a per-commitment payment
446         /// public key which receives non-HTLC-encumbered funds which are only available for spending
447         /// after some delay (or can be claimed via the revocation path).
448         pub delayed_payment_basepoint: DelayedPaymentBasepoint,
449         /// The base point which is used (with derive_public_key) to derive a per-commitment public key
450         /// which is used to encumber HTLC-in-flight outputs.
451         pub htlc_basepoint: HtlcBasepoint,
452 }
453
454 impl_writeable_tlv_based!(ChannelPublicKeys, {
455         (0, funding_pubkey, required),
456         (2, revocation_basepoint, required),
457         (4, payment_point, required),
458         (6, delayed_payment_basepoint, required),
459         (8, htlc_basepoint, required),
460 });
461
462 impl TxCreationKeys {
463         /// Create per-state keys from channel base points and the per-commitment point.
464         /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
465         pub fn derive_new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, broadcaster_delayed_payment_base: &DelayedPaymentBasepoint, broadcaster_htlc_base: &HtlcBasepoint, countersignatory_revocation_base: &RevocationBasepoint, countersignatory_htlc_base: &HtlcBasepoint) -> TxCreationKeys {
466                 TxCreationKeys {
467                         per_commitment_point: per_commitment_point.clone(),
468                         revocation_key: RevocationKey::from_basepoint(&secp_ctx, &countersignatory_revocation_base, &per_commitment_point),
469                         broadcaster_htlc_key: HtlcKey::from_basepoint(&secp_ctx, &broadcaster_htlc_base, &per_commitment_point),
470                         countersignatory_htlc_key: HtlcKey::from_basepoint(&secp_ctx, &countersignatory_htlc_base, &per_commitment_point),
471                         broadcaster_delayed_payment_key: DelayedPaymentKey::from_basepoint(&secp_ctx, &broadcaster_delayed_payment_base, &per_commitment_point),
472                 }
473         }
474
475         /// Generate per-state keys from channel static keys.
476         /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
477         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>) -> TxCreationKeys {
478                 TxCreationKeys::derive_new(
479                         &secp_ctx,
480                         &per_commitment_point,
481                         &broadcaster_keys.delayed_payment_basepoint,
482                         &broadcaster_keys.htlc_basepoint,
483                         &countersignatory_keys.revocation_basepoint,
484                         &countersignatory_keys.htlc_basepoint,
485                 )
486         }
487 }
488
489 /// The maximum length of a script returned by get_revokeable_redeemscript.
490 // Calculated as 6 bytes of opcodes, 1 byte push plus 3 bytes for contest_delay, and two public
491 // keys of 33 bytes (+ 1 push). Generally, pushes are only 2 bytes (for values below 0x7fff, i.e.
492 // around 7 months), however, a 7 month contest delay shouldn't result in being unable to reclaim
493 // on-chain funds.
494 pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 4 + 34*2;
495
496 /// A script either spendable by the revocation
497 /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
498 /// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
499 pub fn get_revokeable_redeemscript(revocation_key: &RevocationKey, contest_delay: u16, broadcaster_delayed_payment_key: &DelayedPaymentKey) -> ScriptBuf {
500         let res = Builder::new().push_opcode(opcodes::all::OP_IF)
501                       .push_slice(&revocation_key.to_public_key().serialize())
502                       .push_opcode(opcodes::all::OP_ELSE)
503                       .push_int(contest_delay as i64)
504                       .push_opcode(opcodes::all::OP_CSV)
505                       .push_opcode(opcodes::all::OP_DROP)
506                       .push_slice(&broadcaster_delayed_payment_key.to_public_key().serialize())
507                       .push_opcode(opcodes::all::OP_ENDIF)
508                       .push_opcode(opcodes::all::OP_CHECKSIG)
509                       .into_script();
510         debug_assert!(res.len() <= REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH);
511         res
512 }
513
514 /// Returns the script for the counterparty's output on a holder's commitment transaction based on
515 /// the channel type.
516 pub fn get_counterparty_payment_script(channel_type_features: &ChannelTypeFeatures, payment_key: &PublicKey) -> ScriptBuf {
517         if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
518                 get_to_countersignatory_with_anchors_redeemscript(payment_key).to_v0_p2wsh()
519         } else {
520                 ScriptBuf::new_v0_p2wpkh(&WPubkeyHash::hash(&payment_key.serialize()))
521         }
522 }
523
524 /// Information about an HTLC as it appears in a commitment transaction
525 #[derive(Clone, Debug, PartialEq, Eq)]
526 pub struct HTLCOutputInCommitment {
527         /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
528         /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
529         /// need to compare this value to whether the commitment transaction in question is that of
530         /// the counterparty or our own.
531         pub offered: bool,
532         /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
533         /// this divided by 1000.
534         pub amount_msat: u64,
535         /// The CLTV lock-time at which this HTLC expires.
536         pub cltv_expiry: u32,
537         /// The hash of the preimage which unlocks this HTLC.
538         pub payment_hash: PaymentHash,
539         /// The position within the commitment transactions' outputs. This may be None if the value is
540         /// below the dust limit (in which case no output appears in the commitment transaction and the
541         /// value is spent to additional transaction fees).
542         pub transaction_output_index: Option<u32>,
543 }
544
545 impl_writeable_tlv_based!(HTLCOutputInCommitment, {
546         (0, offered, required),
547         (2, amount_msat, required),
548         (4, cltv_expiry, required),
549         (6, payment_hash, required),
550         (8, transaction_output_index, option),
551 });
552
553 #[inline]
554 pub(crate) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, broadcaster_htlc_key: &HtlcKey, countersignatory_htlc_key: &HtlcKey, revocation_key: &RevocationKey) -> ScriptBuf {
555         let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).to_byte_array();
556         if htlc.offered {
557                 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
558                               .push_opcode(opcodes::all::OP_HASH160)
559                               .push_slice(PubkeyHash::hash(&revocation_key.to_public_key().serialize()))
560                               .push_opcode(opcodes::all::OP_EQUAL)
561                               .push_opcode(opcodes::all::OP_IF)
562                               .push_opcode(opcodes::all::OP_CHECKSIG)
563                               .push_opcode(opcodes::all::OP_ELSE)
564                               .push_slice(&countersignatory_htlc_key.to_public_key().serialize())
565                               .push_opcode(opcodes::all::OP_SWAP)
566                               .push_opcode(opcodes::all::OP_SIZE)
567                               .push_int(32)
568                               .push_opcode(opcodes::all::OP_EQUAL)
569                               .push_opcode(opcodes::all::OP_NOTIF)
570                               .push_opcode(opcodes::all::OP_DROP)
571                               .push_int(2)
572                               .push_opcode(opcodes::all::OP_SWAP)
573                               .push_slice(&broadcaster_htlc_key.to_public_key().serialize())
574                               .push_int(2)
575                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
576                               .push_opcode(opcodes::all::OP_ELSE)
577                               .push_opcode(opcodes::all::OP_HASH160)
578                               .push_slice(&payment_hash160)
579                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
580                               .push_opcode(opcodes::all::OP_CHECKSIG)
581                               .push_opcode(opcodes::all::OP_ENDIF);
582                 if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
583                         bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
584                                 .push_opcode(opcodes::all::OP_CSV)
585                                 .push_opcode(opcodes::all::OP_DROP);
586                 }
587                 bldr.push_opcode(opcodes::all::OP_ENDIF)
588                         .into_script()
589         } else {
590                         let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
591                               .push_opcode(opcodes::all::OP_HASH160)
592                               .push_slice(&PubkeyHash::hash(&revocation_key.to_public_key().serialize()))
593                               .push_opcode(opcodes::all::OP_EQUAL)
594                               .push_opcode(opcodes::all::OP_IF)
595                               .push_opcode(opcodes::all::OP_CHECKSIG)
596                               .push_opcode(opcodes::all::OP_ELSE)
597                               .push_slice(&countersignatory_htlc_key.to_public_key().serialize())
598                               .push_opcode(opcodes::all::OP_SWAP)
599                               .push_opcode(opcodes::all::OP_SIZE)
600                               .push_int(32)
601                               .push_opcode(opcodes::all::OP_EQUAL)
602                               .push_opcode(opcodes::all::OP_IF)
603                               .push_opcode(opcodes::all::OP_HASH160)
604                               .push_slice(&payment_hash160)
605                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
606                               .push_int(2)
607                               .push_opcode(opcodes::all::OP_SWAP)
608                               .push_slice(&broadcaster_htlc_key.to_public_key().serialize())
609                               .push_int(2)
610                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
611                               .push_opcode(opcodes::all::OP_ELSE)
612                               .push_opcode(opcodes::all::OP_DROP)
613                               .push_int(htlc.cltv_expiry as i64)
614                               .push_opcode(opcodes::all::OP_CLTV)
615                               .push_opcode(opcodes::all::OP_DROP)
616                               .push_opcode(opcodes::all::OP_CHECKSIG)
617                               .push_opcode(opcodes::all::OP_ENDIF);
618                 if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
619                         bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
620                                 .push_opcode(opcodes::all::OP_CSV)
621                                 .push_opcode(opcodes::all::OP_DROP);
622                 }
623                 bldr.push_opcode(opcodes::all::OP_ENDIF)
624                         .into_script()
625         }
626 }
627
628 /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
629 /// does not need to have its previous_output_index filled.
630 #[inline]
631 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, keys: &TxCreationKeys) -> ScriptBuf {
632         get_htlc_redeemscript_with_explicit_keys(htlc, channel_type_features, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
633 }
634
635 /// Gets the redeemscript for a funding output from the two funding public keys.
636 /// Note that the order of funding public keys does not matter.
637 pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> ScriptBuf {
638         let broadcaster_funding_key = broadcaster.serialize();
639         let countersignatory_funding_key = countersignatory.serialize();
640
641         make_funding_redeemscript_from_slices(&broadcaster_funding_key, &countersignatory_funding_key)
642 }
643
644 pub(crate) fn make_funding_redeemscript_from_slices(broadcaster_funding_key: &[u8; 33], countersignatory_funding_key: &[u8; 33]) -> ScriptBuf {
645         let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
646         if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
647                 builder.push_slice(broadcaster_funding_key)
648                         .push_slice(countersignatory_funding_key)
649         } else {
650                 builder.push_slice(countersignatory_funding_key)
651                         .push_slice(broadcaster_funding_key)
652         }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
653 }
654
655 /// Builds an unsigned HTLC-Success or HTLC-Timeout transaction from the given channel and HTLC
656 /// parameters. This is used by [`TrustedCommitmentTransaction::get_htlc_sigs`] to fetch the
657 /// transaction which needs signing, and can be used to construct an HTLC transaction which is
658 /// broadcastable given a counterparty HTLC signature.
659 ///
660 /// Panics if htlc.transaction_output_index.is_none() (as such HTLCs do not appear in the
661 /// commitment transaction).
662 pub fn build_htlc_transaction(commitment_txid: &Txid, feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, broadcaster_delayed_payment_key: &DelayedPaymentKey, revocation_key: &RevocationKey) -> Transaction {
663         let mut txins: Vec<TxIn> = Vec::new();
664         txins.push(build_htlc_input(commitment_txid, htlc, channel_type_features));
665
666         let mut txouts: Vec<TxOut> = Vec::new();
667         txouts.push(build_htlc_output(
668                 feerate_per_kw, contest_delay, htlc, channel_type_features,
669                 broadcaster_delayed_payment_key, revocation_key
670         ));
671
672         Transaction {
673                 version: 2,
674                 lock_time: LockTime::from_consensus(if htlc.offered { htlc.cltv_expiry } else { 0 }),
675                 input: txins,
676                 output: txouts,
677         }
678 }
679
680 pub(crate) fn build_htlc_input(commitment_txid: &Txid, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures) -> TxIn {
681         TxIn {
682                 previous_output: OutPoint {
683                         txid: commitment_txid.clone(),
684                         vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
685                 },
686                 script_sig: ScriptBuf::new(),
687                 sequence: Sequence(if channel_type_features.supports_anchors_zero_fee_htlc_tx() { 1 } else { 0 }),
688                 witness: Witness::new(),
689         }
690 }
691
692 pub(crate) fn build_htlc_output(
693         feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, broadcaster_delayed_payment_key: &DelayedPaymentKey, revocation_key: &RevocationKey
694 ) -> TxOut {
695         let weight = if htlc.offered {
696                 htlc_timeout_tx_weight(channel_type_features)
697         } else {
698                 htlc_success_tx_weight(channel_type_features)
699         };
700         let output_value = if channel_type_features.supports_anchors_zero_fee_htlc_tx() && !channel_type_features.supports_anchors_nonzero_fee_htlc_tx() {
701                 htlc.amount_msat / 1000
702         } else {
703                 let total_fee = feerate_per_kw as u64 * weight / 1000;
704                 htlc.amount_msat / 1000 - total_fee
705         };
706
707         TxOut {
708                 script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_v0_p2wsh(),
709                 value: output_value,
710         }
711 }
712
713 /// Returns the witness required to satisfy and spend a HTLC input.
714 pub fn build_htlc_input_witness(
715         local_sig: &Signature, remote_sig: &Signature, preimage: &Option<PaymentPreimage>,
716         redeem_script: &Script, channel_type_features: &ChannelTypeFeatures,
717 ) -> Witness {
718         let remote_sighash_type = if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
719                 EcdsaSighashType::SinglePlusAnyoneCanPay
720         } else {
721                 EcdsaSighashType::All
722         };
723
724         let mut witness = Witness::new();
725         // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
726         witness.push(vec![]);
727         witness.push_bitcoin_signature(&remote_sig.serialize_der(), remote_sighash_type);
728         witness.push_bitcoin_signature(&local_sig.serialize_der(), EcdsaSighashType::All);
729         if let Some(preimage) = preimage {
730                 witness.push(preimage.0.to_vec());
731         } else {
732                 // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
733                 witness.push(vec![]);
734         }
735         witness.push(redeem_script.to_bytes());
736         witness
737 }
738
739 /// Pre-anchors channel type features did not use to get serialized in the following six structs:
740 /// â€” [`ChannelTransactionParameters`]
741 /// â€” [`CommitmentTransaction`]
742 /// â€” [`CounterpartyOfferedHTLCOutput`]
743 /// â€” [`CounterpartyReceivedHTLCOutput`]
744 /// â€” [`HolderHTLCOutput`]
745 /// â€” [`HolderFundingOutput`]
746 ///
747 /// To ensure a forwards-compatible serialization, we use odd TLV fields. However, if new features
748 /// are used that could break security, where old signers should be prevented from handling the
749 /// serialized data, an optional even-field TLV will be used as a stand-in to break compatibility.
750 ///
751 /// This method determines whether or not that option needs to be set based on the chanenl type
752 /// features, and returns it.
753 ///
754 /// [`CounterpartyOfferedHTLCOutput`]: crate::chain::package::CounterpartyOfferedHTLCOutput
755 /// [`CounterpartyReceivedHTLCOutput`]: crate::chain::package::CounterpartyReceivedHTLCOutput
756 /// [`HolderHTLCOutput`]: crate::chain::package::HolderHTLCOutput
757 /// [`HolderFundingOutput`]: crate::chain::package::HolderFundingOutput
758 pub(crate) fn legacy_deserialization_prevention_marker_for_channel_type_features(features: &ChannelTypeFeatures) -> Option<()> {
759         let mut legacy_version_bit_set = ChannelTypeFeatures::only_static_remote_key();
760         legacy_version_bit_set.set_scid_privacy_required();
761         legacy_version_bit_set.set_zero_conf_required();
762
763         if features.is_subset(&legacy_version_bit_set) {
764                 None
765         } else {
766                 Some(())
767         }
768 }
769
770 /// Gets the witnessScript for the to_remote output when anchors are enabled.
771 #[inline]
772 pub fn get_to_countersignatory_with_anchors_redeemscript(payment_point: &PublicKey) -> ScriptBuf {
773         Builder::new()
774                 .push_slice(payment_point.serialize())
775                 .push_opcode(opcodes::all::OP_CHECKSIGVERIFY)
776                 .push_int(1)
777                 .push_opcode(opcodes::all::OP_CSV)
778                 .into_script()
779 }
780
781 /// Gets the witnessScript for an anchor output from the funding public key.
782 /// The witness in the spending input must be:
783 /// <BIP 143 funding_signature>
784 /// After 16 blocks of confirmation, an alternative satisfying witness could be:
785 /// <>
786 /// (empty vector required to satisfy compliance with MINIMALIF-standard rule)
787 #[inline]
788 pub fn get_anchor_redeemscript(funding_pubkey: &PublicKey) -> ScriptBuf {
789         Builder::new().push_slice(funding_pubkey.serialize())
790                 .push_opcode(opcodes::all::OP_CHECKSIG)
791                 .push_opcode(opcodes::all::OP_IFDUP)
792                 .push_opcode(opcodes::all::OP_NOTIF)
793                 .push_int(16)
794                 .push_opcode(opcodes::all::OP_CSV)
795                 .push_opcode(opcodes::all::OP_ENDIF)
796                 .into_script()
797 }
798
799 /// Locates the output with an anchor script paying to `funding_pubkey` within `commitment_tx`.
800 pub(crate) fn get_anchor_output<'a>(commitment_tx: &'a Transaction, funding_pubkey: &PublicKey) -> Option<(u32, &'a TxOut)> {
801         let anchor_script = chan_utils::get_anchor_redeemscript(funding_pubkey).to_v0_p2wsh();
802         commitment_tx.output.iter().enumerate()
803                 .find(|(_, txout)| txout.script_pubkey == anchor_script)
804                 .map(|(idx, txout)| (idx as u32, txout))
805 }
806
807 /// Returns the witness required to satisfy and spend an anchor input.
808 pub fn build_anchor_input_witness(funding_key: &PublicKey, funding_sig: &Signature) -> Witness {
809         let anchor_redeem_script = chan_utils::get_anchor_redeemscript(funding_key);
810         let mut ret = Witness::new();
811         ret.push_bitcoin_signature(&funding_sig.serialize_der(), EcdsaSighashType::All);
812         ret.push(anchor_redeem_script.as_bytes());
813         ret
814 }
815
816 /// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
817 /// The fields are organized by holder/counterparty.
818 ///
819 /// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
820 /// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
821 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
822 pub struct ChannelTransactionParameters {
823         /// Holder public keys
824         pub holder_pubkeys: ChannelPublicKeys,
825         /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
826         pub holder_selected_contest_delay: u16,
827         /// Whether the holder is the initiator of this channel.
828         /// This is an input to the commitment number obscure factor computation.
829         pub is_outbound_from_holder: bool,
830         /// The late-bound counterparty channel transaction parameters.
831         /// These parameters are populated at the point in the protocol where the counterparty provides them.
832         pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
833         /// The late-bound funding outpoint
834         pub funding_outpoint: Option<chain::transaction::OutPoint>,
835         /// This channel's type, as negotiated during channel open. For old objects where this field
836         /// wasn't serialized, it will default to static_remote_key at deserialization.
837         pub channel_type_features: ChannelTypeFeatures
838 }
839
840 /// Late-bound per-channel counterparty data used to build transactions.
841 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
842 pub struct CounterpartyChannelTransactionParameters {
843         /// Counter-party public keys
844         pub pubkeys: ChannelPublicKeys,
845         /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
846         pub selected_contest_delay: u16,
847 }
848
849 impl ChannelTransactionParameters {
850         /// Whether the late bound parameters are populated.
851         pub fn is_populated(&self) -> bool {
852                 self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
853         }
854
855         /// Whether the channel supports zero-fee HTLC transaction anchors.
856         pub(crate) fn supports_anchors(&self) -> bool {
857                 self.channel_type_features.supports_anchors_zero_fee_htlc_tx()
858         }
859
860         /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
861         /// given that the holder is the broadcaster.
862         ///
863         /// self.is_populated() must be true before calling this function.
864         pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
865                 assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
866                 DirectedChannelTransactionParameters {
867                         inner: self,
868                         holder_is_broadcaster: true
869                 }
870         }
871
872         /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
873         /// given that the counterparty is the broadcaster.
874         ///
875         /// self.is_populated() must be true before calling this function.
876         pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
877                 assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
878                 DirectedChannelTransactionParameters {
879                         inner: self,
880                         holder_is_broadcaster: false
881                 }
882         }
883 }
884
885 impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, {
886         (0, pubkeys, required),
887         (2, selected_contest_delay, required),
888 });
889
890 impl Writeable for ChannelTransactionParameters {
891         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
892                 let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
893                 write_tlv_fields!(writer, {
894                         (0, self.holder_pubkeys, required),
895                         (2, self.holder_selected_contest_delay, required),
896                         (4, self.is_outbound_from_holder, required),
897                         (6, self.counterparty_parameters, option),
898                         (8, self.funding_outpoint, option),
899                         (10, legacy_deserialization_prevention_marker, option),
900                         (11, self.channel_type_features, required),
901                 });
902                 Ok(())
903         }
904 }
905
906 impl Readable for ChannelTransactionParameters {
907         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
908                 let mut holder_pubkeys = RequiredWrapper(None);
909                 let mut holder_selected_contest_delay = RequiredWrapper(None);
910                 let mut is_outbound_from_holder = RequiredWrapper(None);
911                 let mut counterparty_parameters = None;
912                 let mut funding_outpoint = None;
913                 let mut _legacy_deserialization_prevention_marker: Option<()> = None;
914                 let mut channel_type_features = None;
915
916                 read_tlv_fields!(reader, {
917                         (0, holder_pubkeys, required),
918                         (2, holder_selected_contest_delay, required),
919                         (4, is_outbound_from_holder, required),
920                         (6, counterparty_parameters, option),
921                         (8, funding_outpoint, option),
922                         (10, _legacy_deserialization_prevention_marker, option),
923                         (11, channel_type_features, option),
924                 });
925
926                 let mut additional_features = ChannelTypeFeatures::empty();
927                 additional_features.set_anchors_nonzero_fee_htlc_tx_required();
928                 chain::package::verify_channel_type_features(&channel_type_features, Some(&additional_features))?;
929
930                 Ok(Self {
931                         holder_pubkeys: holder_pubkeys.0.unwrap(),
932                         holder_selected_contest_delay: holder_selected_contest_delay.0.unwrap(),
933                         is_outbound_from_holder: is_outbound_from_holder.0.unwrap(),
934                         counterparty_parameters,
935                         funding_outpoint,
936                         channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
937                 })
938         }
939 }
940
941 /// Static channel fields used to build transactions given per-commitment fields, organized by
942 /// broadcaster/countersignatory.
943 ///
944 /// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
945 /// as_holder_broadcastable and as_counterparty_broadcastable functions.
946 pub struct DirectedChannelTransactionParameters<'a> {
947         /// The holder's channel static parameters
948         inner: &'a ChannelTransactionParameters,
949         /// Whether the holder is the broadcaster
950         holder_is_broadcaster: bool,
951 }
952
953 impl<'a> DirectedChannelTransactionParameters<'a> {
954         /// Get the channel pubkeys for the broadcaster
955         pub fn broadcaster_pubkeys(&self) -> &'a ChannelPublicKeys {
956                 if self.holder_is_broadcaster {
957                         &self.inner.holder_pubkeys
958                 } else {
959                         &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
960                 }
961         }
962
963         /// Get the channel pubkeys for the countersignatory
964         pub fn countersignatory_pubkeys(&self) -> &'a ChannelPublicKeys {
965                 if self.holder_is_broadcaster {
966                         &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
967                 } else {
968                         &self.inner.holder_pubkeys
969                 }
970         }
971
972         /// Get the contest delay applicable to the transactions.
973         /// Note that the contest delay was selected by the countersignatory.
974         pub fn contest_delay(&self) -> u16 {
975                 let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
976                 if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
977         }
978
979         /// Whether the channel is outbound from the broadcaster.
980         ///
981         /// The boolean representing the side that initiated the channel is
982         /// an input to the commitment number obscure factor computation.
983         pub fn is_outbound(&self) -> bool {
984                 if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
985         }
986
987         /// The funding outpoint
988         pub fn funding_outpoint(&self) -> OutPoint {
989                 self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
990         }
991
992         /// Whether to use anchors for this channel
993         pub fn channel_type_features(&self) -> &'a ChannelTypeFeatures {
994                 &self.inner.channel_type_features
995         }
996 }
997
998 /// Information needed to build and sign a holder's commitment transaction.
999 ///
1000 /// The transaction is only signed once we are ready to broadcast.
1001 #[derive(Clone, Debug)]
1002 pub struct HolderCommitmentTransaction {
1003         inner: CommitmentTransaction,
1004         /// Our counterparty's signature for the transaction
1005         pub counterparty_sig: Signature,
1006         /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
1007         pub counterparty_htlc_sigs: Vec<Signature>,
1008         // Which order the signatures should go in when constructing the final commitment tx witness.
1009         // The user should be able to reconstruct this themselves, so we don't bother to expose it.
1010         holder_sig_first: bool,
1011 }
1012
1013 impl Deref for HolderCommitmentTransaction {
1014         type Target = CommitmentTransaction;
1015
1016         fn deref(&self) -> &Self::Target { &self.inner }
1017 }
1018
1019 impl Eq for HolderCommitmentTransaction {}
1020 impl PartialEq for HolderCommitmentTransaction {
1021         // We dont care whether we are signed in equality comparison
1022         fn eq(&self, o: &Self) -> bool {
1023                 self.inner == o.inner
1024         }
1025 }
1026
1027 impl_writeable_tlv_based!(HolderCommitmentTransaction, {
1028         (0, inner, required),
1029         (2, counterparty_sig, required),
1030         (4, holder_sig_first, required),
1031         (6, counterparty_htlc_sigs, required_vec),
1032 });
1033
1034 impl HolderCommitmentTransaction {
1035         #[cfg(test)]
1036         pub fn dummy(htlcs: &mut Vec<(HTLCOutputInCommitment, ())>) -> Self {
1037                 let secp_ctx = Secp256k1::new();
1038                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1039                 let dummy_sig = sign(&secp_ctx, &secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
1040
1041                 let keys = TxCreationKeys {
1042                         per_commitment_point: dummy_key.clone(),
1043                         revocation_key: RevocationKey::from_basepoint(&secp_ctx, &RevocationBasepoint::from(dummy_key), &dummy_key),
1044                         broadcaster_htlc_key: HtlcKey::from_basepoint(&secp_ctx, &HtlcBasepoint::from(dummy_key), &dummy_key),
1045                         countersignatory_htlc_key: HtlcKey::from_basepoint(&secp_ctx, &HtlcBasepoint::from(dummy_key), &dummy_key),
1046                         broadcaster_delayed_payment_key: DelayedPaymentKey::from_basepoint(&secp_ctx, &DelayedPaymentBasepoint::from(dummy_key), &dummy_key),
1047                 };
1048                 let channel_pubkeys = ChannelPublicKeys {
1049                         funding_pubkey: dummy_key.clone(),
1050                         revocation_basepoint: RevocationBasepoint::from(dummy_key),
1051                         payment_point: dummy_key.clone(),
1052                         delayed_payment_basepoint: DelayedPaymentBasepoint::from(dummy_key.clone()),
1053                         htlc_basepoint: HtlcBasepoint::from(dummy_key.clone())
1054                 };
1055                 let channel_parameters = ChannelTransactionParameters {
1056                         holder_pubkeys: channel_pubkeys.clone(),
1057                         holder_selected_contest_delay: 0,
1058                         is_outbound_from_holder: false,
1059                         counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
1060                         funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1061                         channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
1062                 };
1063                 let mut counterparty_htlc_sigs = Vec::new();
1064                 for _ in 0..htlcs.len() {
1065                         counterparty_htlc_sigs.push(dummy_sig);
1066                 }
1067                 let inner = CommitmentTransaction::new_with_auxiliary_htlc_data(0, 0, 0, dummy_key.clone(), dummy_key.clone(), keys, 0, htlcs, &channel_parameters.as_counterparty_broadcastable());
1068                 htlcs.sort_by_key(|htlc| htlc.0.transaction_output_index);
1069                 HolderCommitmentTransaction {
1070                         inner,
1071                         counterparty_sig: dummy_sig,
1072                         counterparty_htlc_sigs,
1073                         holder_sig_first: false
1074                 }
1075         }
1076
1077         /// Create a new holder transaction with the given counterparty signatures.
1078         /// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
1079         pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
1080                 Self {
1081                         inner: commitment_tx,
1082                         counterparty_sig,
1083                         counterparty_htlc_sigs,
1084                         holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
1085                 }
1086         }
1087
1088         pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
1089                 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
1090                 let mut tx = self.inner.built.transaction.clone();
1091                 tx.input[0].witness.push(Vec::new());
1092
1093                 if self.holder_sig_first {
1094                         tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1095                         tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1096                 } else {
1097                         tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1098                         tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1099                 }
1100
1101                 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
1102                 tx
1103         }
1104 }
1105
1106 /// A pre-built Bitcoin commitment transaction and its txid.
1107 #[derive(Clone, Debug)]
1108 pub struct BuiltCommitmentTransaction {
1109         /// The commitment transaction
1110         pub transaction: Transaction,
1111         /// The txid for the commitment transaction.
1112         ///
1113         /// This is provided as a performance optimization, instead of calling transaction.txid()
1114         /// multiple times.
1115         pub txid: Txid,
1116 }
1117
1118 impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
1119         (0, transaction, required),
1120         (2, txid, required),
1121 });
1122
1123 impl BuiltCommitmentTransaction {
1124         /// Get the SIGHASH_ALL sighash value of the transaction.
1125         ///
1126         /// This can be used to verify a signature.
1127         pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1128                 let sighash = &sighash::SighashCache::new(&self.transaction).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1129                 hash_to_message!(sighash)
1130         }
1131
1132         /// Signs the counterparty's commitment transaction.
1133         pub fn sign_counterparty_commitment<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1134                 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1135                 sign(secp_ctx, &sighash, funding_key)
1136         }
1137
1138         /// Signs the holder commitment transaction because we are about to broadcast it.
1139         pub fn sign_holder_commitment<T: secp256k1::Signing, ES: Deref>(
1140                 &self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64,
1141                 entropy_source: &ES, secp_ctx: &Secp256k1<T>
1142         ) -> Signature where ES::Target: EntropySource {
1143                 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1144                 sign_with_aux_rand(secp_ctx, &sighash, funding_key, entropy_source)
1145         }
1146 }
1147
1148 /// This class tracks the per-transaction information needed to build a closing transaction and will
1149 /// actually build it and sign.
1150 ///
1151 /// This class can be used inside a signer implementation to generate a signature given the relevant
1152 /// secret key.
1153 #[derive(Clone, Hash, PartialEq, Eq)]
1154 pub struct ClosingTransaction {
1155         to_holder_value_sat: u64,
1156         to_counterparty_value_sat: u64,
1157         to_holder_script: ScriptBuf,
1158         to_counterparty_script: ScriptBuf,
1159         built: Transaction,
1160 }
1161
1162 impl ClosingTransaction {
1163         /// Construct an object of the class
1164         pub fn new(
1165                 to_holder_value_sat: u64,
1166                 to_counterparty_value_sat: u64,
1167                 to_holder_script: ScriptBuf,
1168                 to_counterparty_script: ScriptBuf,
1169                 funding_outpoint: OutPoint,
1170         ) -> Self {
1171                 let built = build_closing_transaction(
1172                         to_holder_value_sat, to_counterparty_value_sat,
1173                         to_holder_script.clone(), to_counterparty_script.clone(),
1174                         funding_outpoint
1175                 );
1176                 ClosingTransaction {
1177                         to_holder_value_sat,
1178                         to_counterparty_value_sat,
1179                         to_holder_script,
1180                         to_counterparty_script,
1181                         built
1182                 }
1183         }
1184
1185         /// Trust our pre-built transaction.
1186         ///
1187         /// Applies a wrapper which allows access to the transaction.
1188         ///
1189         /// This should only be used if you fully trust the builder of this object. It should not
1190         /// be used by an external signer - instead use the verify function.
1191         pub fn trust(&self) -> TrustedClosingTransaction {
1192                 TrustedClosingTransaction { inner: self }
1193         }
1194
1195         /// Verify our pre-built transaction.
1196         ///
1197         /// Applies a wrapper which allows access to the transaction.
1198         ///
1199         /// An external validating signer must call this method before signing
1200         /// or using the built transaction.
1201         pub fn verify(&self, funding_outpoint: OutPoint) -> Result<TrustedClosingTransaction, ()> {
1202                 let built = build_closing_transaction(
1203                         self.to_holder_value_sat, self.to_counterparty_value_sat,
1204                         self.to_holder_script.clone(), self.to_counterparty_script.clone(),
1205                         funding_outpoint
1206                 );
1207                 if self.built != built {
1208                         return Err(())
1209                 }
1210                 Ok(TrustedClosingTransaction { inner: self })
1211         }
1212
1213         /// The value to be sent to the holder, or zero if the output will be omitted
1214         pub fn to_holder_value_sat(&self) -> u64 {
1215                 self.to_holder_value_sat
1216         }
1217
1218         /// The value to be sent to the counterparty, or zero if the output will be omitted
1219         pub fn to_counterparty_value_sat(&self) -> u64 {
1220                 self.to_counterparty_value_sat
1221         }
1222
1223         /// The destination of the holder's output
1224         pub fn to_holder_script(&self) -> &Script {
1225                 &self.to_holder_script
1226         }
1227
1228         /// The destination of the counterparty's output
1229         pub fn to_counterparty_script(&self) -> &Script {
1230                 &self.to_counterparty_script
1231         }
1232 }
1233
1234 /// A wrapper on ClosingTransaction indicating that the built bitcoin
1235 /// transaction is trusted.
1236 ///
1237 /// See trust() and verify() functions on CommitmentTransaction.
1238 ///
1239 /// This structure implements Deref.
1240 pub struct TrustedClosingTransaction<'a> {
1241         inner: &'a ClosingTransaction,
1242 }
1243
1244 impl<'a> Deref for TrustedClosingTransaction<'a> {
1245         type Target = ClosingTransaction;
1246
1247         fn deref(&self) -> &Self::Target { self.inner }
1248 }
1249
1250 impl<'a> TrustedClosingTransaction<'a> {
1251         /// The pre-built Bitcoin commitment transaction
1252         pub fn built_transaction(&self) -> &'a Transaction {
1253                 &self.inner.built
1254         }
1255
1256         /// Get the SIGHASH_ALL sighash value of the transaction.
1257         ///
1258         /// This can be used to verify a signature.
1259         pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1260                 let sighash = &sighash::SighashCache::new(&self.inner.built).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1261                 hash_to_message!(sighash)
1262         }
1263
1264         /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1265         /// because we are about to broadcast a holder transaction.
1266         pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1267                 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1268                 sign(secp_ctx, &sighash, funding_key)
1269         }
1270 }
1271
1272 /// This class tracks the per-transaction information needed to build a commitment transaction and will
1273 /// actually build it and sign.  It is used for holder transactions that we sign only when needed
1274 /// and for transactions we sign for the counterparty.
1275 ///
1276 /// This class can be used inside a signer implementation to generate a signature given the relevant
1277 /// secret key.
1278 #[derive(Clone, Debug)]
1279 pub struct CommitmentTransaction {
1280         commitment_number: u64,
1281         to_broadcaster_value_sat: u64,
1282         to_countersignatory_value_sat: u64,
1283         to_broadcaster_delay: Option<u16>, // Added in 0.0.117
1284         feerate_per_kw: u32,
1285         htlcs: Vec<HTLCOutputInCommitment>,
1286         // Note that on upgrades, some features of existing outputs may be missed.
1287         channel_type_features: ChannelTypeFeatures,
1288         // A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
1289         keys: TxCreationKeys,
1290         // For access to the pre-built transaction, see doc for trust()
1291         built: BuiltCommitmentTransaction,
1292 }
1293
1294 impl Eq for CommitmentTransaction {}
1295 impl PartialEq for CommitmentTransaction {
1296         fn eq(&self, o: &Self) -> bool {
1297                 let eq = self.commitment_number == o.commitment_number &&
1298                         self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
1299                         self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
1300                         self.feerate_per_kw == o.feerate_per_kw &&
1301                         self.htlcs == o.htlcs &&
1302                         self.channel_type_features == o.channel_type_features &&
1303                         self.keys == o.keys;
1304                 if eq {
1305                         debug_assert_eq!(self.built.transaction, o.built.transaction);
1306                         debug_assert_eq!(self.built.txid, o.built.txid);
1307                 }
1308                 eq
1309         }
1310 }
1311
1312 impl Writeable for CommitmentTransaction {
1313         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1314                 let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
1315                 write_tlv_fields!(writer, {
1316                         (0, self.commitment_number, required),
1317                         (1, self.to_broadcaster_delay, option),
1318                         (2, self.to_broadcaster_value_sat, required),
1319                         (4, self.to_countersignatory_value_sat, required),
1320                         (6, self.feerate_per_kw, required),
1321                         (8, self.keys, required),
1322                         (10, self.built, required),
1323                         (12, self.htlcs, required_vec),
1324                         (14, legacy_deserialization_prevention_marker, option),
1325                         (15, self.channel_type_features, required),
1326                 });
1327                 Ok(())
1328         }
1329 }
1330
1331 impl Readable for CommitmentTransaction {
1332         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1333                 _init_and_read_len_prefixed_tlv_fields!(reader, {
1334                         (0, commitment_number, required),
1335                         (1, to_broadcaster_delay, option),
1336                         (2, to_broadcaster_value_sat, required),
1337                         (4, to_countersignatory_value_sat, required),
1338                         (6, feerate_per_kw, required),
1339                         (8, keys, required),
1340                         (10, built, required),
1341                         (12, htlcs, required_vec),
1342                         (14, _legacy_deserialization_prevention_marker, option),
1343                         (15, channel_type_features, option),
1344                 });
1345
1346                 let mut additional_features = ChannelTypeFeatures::empty();
1347                 additional_features.set_anchors_nonzero_fee_htlc_tx_required();
1348                 chain::package::verify_channel_type_features(&channel_type_features, Some(&additional_features))?;
1349
1350                 Ok(Self {
1351                         commitment_number: commitment_number.0.unwrap(),
1352                         to_broadcaster_value_sat: to_broadcaster_value_sat.0.unwrap(),
1353                         to_countersignatory_value_sat: to_countersignatory_value_sat.0.unwrap(),
1354                         to_broadcaster_delay,
1355                         feerate_per_kw: feerate_per_kw.0.unwrap(),
1356                         keys: keys.0.unwrap(),
1357                         built: built.0.unwrap(),
1358                         htlcs,
1359                         channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
1360                 })
1361         }
1362 }
1363
1364 impl CommitmentTransaction {
1365         /// Construct an object of the class while assigning transaction output indices to HTLCs.
1366         ///
1367         /// Populates HTLCOutputInCommitment.transaction_output_index in htlcs_with_aux.
1368         ///
1369         /// The generic T allows the caller to match the HTLC output index with auxiliary data.
1370         /// This auxiliary data is not stored in this object.
1371         ///
1372         /// Only include HTLCs that are above the dust limit for the channel.
1373         ///
1374         /// This is not exported to bindings users due to the generic though we likely should expose a version without
1375         pub fn new_with_auxiliary_htlc_data<T>(commitment_number: u64, to_broadcaster_value_sat: u64, to_countersignatory_value_sat: u64, 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 {
1376                 // Sort outputs and populate output indices while keeping track of the auxiliary data
1377                 let (outputs, htlcs) = Self::internal_build_outputs(&keys, to_broadcaster_value_sat, to_countersignatory_value_sat, htlcs_with_aux, channel_parameters, &broadcaster_funding_key, &countersignatory_funding_key).unwrap();
1378
1379                 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
1380                 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1381                 let txid = transaction.txid();
1382                 CommitmentTransaction {
1383                         commitment_number,
1384                         to_broadcaster_value_sat,
1385                         to_countersignatory_value_sat,
1386                         to_broadcaster_delay: Some(channel_parameters.contest_delay()),
1387                         feerate_per_kw,
1388                         htlcs,
1389                         channel_type_features: channel_parameters.channel_type_features().clone(),
1390                         keys,
1391                         built: BuiltCommitmentTransaction {
1392                                 transaction,
1393                                 txid
1394                         },
1395                 }
1396         }
1397
1398         /// Use non-zero fee anchors
1399         ///
1400         /// This is not exported to bindings users due to move, and also not likely to be useful for binding users
1401         pub fn with_non_zero_fee_anchors(mut self) -> Self {
1402                 self.channel_type_features.set_anchors_nonzero_fee_htlc_tx_required();
1403                 self
1404         }
1405
1406         fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<BuiltCommitmentTransaction, ()> {
1407                 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
1408
1409                 let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
1410                 let (outputs, _) = Self::internal_build_outputs(keys, self.to_broadcaster_value_sat, self.to_countersignatory_value_sat, &mut htlcs_with_aux, channel_parameters, broadcaster_funding_key, countersignatory_funding_key)?;
1411
1412                 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1413                 let txid = transaction.txid();
1414                 let built_transaction = BuiltCommitmentTransaction {
1415                         transaction,
1416                         txid
1417                 };
1418                 Ok(built_transaction)
1419         }
1420
1421         fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
1422                 Transaction {
1423                         version: 2,
1424                         lock_time: LockTime::from_consensus(((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32)),
1425                         input: txins,
1426                         output: outputs,
1427                 }
1428         }
1429
1430         // This is used in two cases:
1431         // - initial sorting of outputs / HTLCs in the constructor, in which case T is auxiliary data the
1432         //   caller needs to have sorted together with the HTLCs so it can keep track of the output index
1433         // - building of a bitcoin transaction during a verify() call, in which case T is just ()
1434         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, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<(Vec<TxOut>, Vec<HTLCOutputInCommitment>), ()> {
1435                 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1436                 let contest_delay = channel_parameters.contest_delay();
1437
1438                 let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
1439
1440                 if to_countersignatory_value_sat > 0 {
1441                         let script = if channel_parameters.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
1442                             get_to_countersignatory_with_anchors_redeemscript(&countersignatory_pubkeys.payment_point).to_v0_p2wsh()
1443                         } else {
1444                             Payload::p2wpkh(&BitcoinPublicKey::new(countersignatory_pubkeys.payment_point)).unwrap().script_pubkey()
1445                         };
1446                         txouts.push((
1447                                 TxOut {
1448                                         script_pubkey: script.clone(),
1449                                         value: to_countersignatory_value_sat,
1450                                 },
1451                                 None,
1452                         ))
1453                 }
1454
1455                 if to_broadcaster_value_sat > 0 {
1456                         let redeem_script = get_revokeable_redeemscript(
1457                                 &keys.revocation_key,
1458                                 contest_delay,
1459                                 &keys.broadcaster_delayed_payment_key,
1460                         );
1461                         txouts.push((
1462                                 TxOut {
1463                                         script_pubkey: redeem_script.to_v0_p2wsh(),
1464                                         value: to_broadcaster_value_sat,
1465                                 },
1466                                 None,
1467                         ));
1468                 }
1469
1470                 if channel_parameters.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
1471                         if to_broadcaster_value_sat > 0 || !htlcs_with_aux.is_empty() {
1472                                 let anchor_script = get_anchor_redeemscript(broadcaster_funding_key);
1473                                 txouts.push((
1474                                         TxOut {
1475                                                 script_pubkey: anchor_script.to_v0_p2wsh(),
1476                                                 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1477                                         },
1478                                         None,
1479                                 ));
1480                         }
1481
1482                         if to_countersignatory_value_sat > 0 || !htlcs_with_aux.is_empty() {
1483                                 let anchor_script = get_anchor_redeemscript(countersignatory_funding_key);
1484                                 txouts.push((
1485                                         TxOut {
1486                                                 script_pubkey: anchor_script.to_v0_p2wsh(),
1487                                                 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1488                                         },
1489                                         None,
1490                                 ));
1491                         }
1492                 }
1493
1494                 let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
1495                 for (htlc, _) in htlcs_with_aux {
1496                         let script = chan_utils::get_htlc_redeemscript(&htlc, &channel_parameters.channel_type_features(), &keys);
1497                         let txout = TxOut {
1498                                 script_pubkey: script.to_v0_p2wsh(),
1499                                 value: htlc.amount_msat / 1000,
1500                         };
1501                         txouts.push((txout, Some(htlc)));
1502                 }
1503
1504                 // Sort output in BIP-69 order (amount, scriptPubkey).  Tie-breaks based on HTLC
1505                 // CLTV expiration height.
1506                 sort_outputs(&mut txouts, |a, b| {
1507                         if let &Some(ref a_htlcout) = a {
1508                                 if let &Some(ref b_htlcout) = b {
1509                                         a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
1510                                                 // Note that due to hash collisions, we have to have a fallback comparison
1511                                                 // here for fuzzing mode (otherwise at least chanmon_fail_consistency
1512                                                 // may fail)!
1513                                                 .then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
1514                                 // For non-HTLC outputs, if they're copying our SPK we don't really care if we
1515                                 // close the channel due to mismatches - they're doing something dumb:
1516                                 } else { cmp::Ordering::Equal }
1517                         } else { cmp::Ordering::Equal }
1518                 });
1519
1520                 let mut outputs = Vec::with_capacity(txouts.len());
1521                 for (idx, out) in txouts.drain(..).enumerate() {
1522                         if let Some(htlc) = out.1 {
1523                                 htlc.transaction_output_index = Some(idx as u32);
1524                                 htlcs.push(htlc.clone());
1525                         }
1526                         outputs.push(out.0);
1527                 }
1528                 Ok((outputs, htlcs))
1529         }
1530
1531         fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
1532                 let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
1533                 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1534                 let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
1535                         &broadcaster_pubkeys.payment_point,
1536                         &countersignatory_pubkeys.payment_point,
1537                         channel_parameters.is_outbound(),
1538                 );
1539
1540                 let obscured_commitment_transaction_number =
1541                         commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
1542
1543                 let txins = {
1544                         let mut ins: Vec<TxIn> = Vec::new();
1545                         ins.push(TxIn {
1546                                 previous_output: channel_parameters.funding_outpoint(),
1547                                 script_sig: ScriptBuf::new(),
1548                                 sequence: Sequence(((0x80 as u32) << 8 * 3)
1549                                         | ((obscured_commitment_transaction_number >> 3 * 8) as u32)),
1550                                 witness: Witness::new(),
1551                         });
1552                         ins
1553                 };
1554                 (obscured_commitment_transaction_number, txins)
1555         }
1556
1557         /// The backwards-counting commitment number
1558         pub fn commitment_number(&self) -> u64 {
1559                 self.commitment_number
1560         }
1561
1562         /// The per commitment point used by the broadcaster.
1563         pub fn per_commitment_point(&self) -> PublicKey {
1564                 self.keys.per_commitment_point
1565         }
1566
1567         /// The value to be sent to the broadcaster
1568         pub fn to_broadcaster_value_sat(&self) -> u64 {
1569                 self.to_broadcaster_value_sat
1570         }
1571
1572         /// The value to be sent to the counterparty
1573         pub fn to_countersignatory_value_sat(&self) -> u64 {
1574                 self.to_countersignatory_value_sat
1575         }
1576
1577         /// The feerate paid per 1000-weight-unit in this commitment transaction.
1578         pub fn feerate_per_kw(&self) -> u32 {
1579                 self.feerate_per_kw
1580         }
1581
1582         /// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
1583         /// which were included in this commitment transaction in output order.
1584         /// The transaction index is always populated.
1585         ///
1586         /// This is not exported to bindings users as we cannot currently convert Vec references to/from C, though we should
1587         /// expose a less effecient version which creates a Vec of references in the future.
1588         pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
1589                 &self.htlcs
1590         }
1591
1592         /// Trust our pre-built transaction and derived transaction creation public keys.
1593         ///
1594         /// Applies a wrapper which allows access to these fields.
1595         ///
1596         /// This should only be used if you fully trust the builder of this object.  It should not
1597         /// be used by an external signer - instead use the verify function.
1598         pub fn trust(&self) -> TrustedCommitmentTransaction {
1599                 TrustedCommitmentTransaction { inner: self }
1600         }
1601
1602         /// Verify our pre-built transaction and derived transaction creation public keys.
1603         ///
1604         /// Applies a wrapper which allows access to these fields.
1605         ///
1606         /// An external validating signer must call this method before signing
1607         /// or using the built transaction.
1608         pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
1609                 // This is the only field of the key cache that we trust
1610                 let per_commitment_point = self.keys.per_commitment_point;
1611                 let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx);
1612                 if keys != self.keys {
1613                         return Err(());
1614                 }
1615                 let tx = self.internal_rebuild_transaction(&keys, channel_parameters, &broadcaster_keys.funding_pubkey, &countersignatory_keys.funding_pubkey)?;
1616                 if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
1617                         return Err(());
1618                 }
1619                 Ok(TrustedCommitmentTransaction { inner: self })
1620         }
1621 }
1622
1623 /// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
1624 /// transaction and the transaction creation keys) are trusted.
1625 ///
1626 /// See trust() and verify() functions on CommitmentTransaction.
1627 ///
1628 /// This structure implements Deref.
1629 pub struct TrustedCommitmentTransaction<'a> {
1630         inner: &'a CommitmentTransaction,
1631 }
1632
1633 impl<'a> Deref for TrustedCommitmentTransaction<'a> {
1634         type Target = CommitmentTransaction;
1635
1636         fn deref(&self) -> &Self::Target { self.inner }
1637 }
1638
1639 impl<'a> TrustedCommitmentTransaction<'a> {
1640         /// The transaction ID of the built Bitcoin transaction
1641         pub fn txid(&self) -> Txid {
1642                 self.inner.built.txid
1643         }
1644
1645         /// The pre-built Bitcoin commitment transaction
1646         pub fn built_transaction(&self) -> &'a BuiltCommitmentTransaction {
1647                 &self.inner.built
1648         }
1649
1650         /// The pre-calculated transaction creation public keys.
1651         pub fn keys(&self) -> &'a TxCreationKeys {
1652                 &self.inner.keys
1653         }
1654
1655         /// Should anchors be used.
1656         pub fn channel_type_features(&self) -> &'a ChannelTypeFeatures {
1657                 &self.inner.channel_type_features
1658         }
1659
1660         /// Get a signature for each HTLC which was included in the commitment transaction (ie for
1661         /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
1662         ///
1663         /// The returned Vec has one entry for each HTLC, and in the same order.
1664         ///
1665         /// This function is only valid in the holder commitment context, it always uses EcdsaSighashType::All.
1666         pub fn get_htlc_sigs<T: secp256k1::Signing, ES: Deref>(
1667                 &self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters,
1668                 entropy_source: &ES, secp_ctx: &Secp256k1<T>,
1669         ) -> Result<Vec<Signature>, ()> where ES::Target: EntropySource {
1670                 let inner = self.inner;
1671                 let keys = &inner.keys;
1672                 let txid = inner.built.txid;
1673                 let mut ret = Vec::with_capacity(inner.htlcs.len());
1674                 let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key);
1675
1676                 for this_htlc in inner.htlcs.iter() {
1677                         assert!(this_htlc.transaction_output_index.is_some());
1678                         let htlc_tx = build_htlc_transaction(&txid, inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc, &self.channel_type_features, &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
1679
1680                         let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc, &self.channel_type_features, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key);
1681
1682                         let sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, EcdsaSighashType::All).unwrap()[..]);
1683                         ret.push(sign_with_aux_rand(secp_ctx, &sighash, &holder_htlc_key, entropy_source));
1684                 }
1685                 Ok(ret)
1686         }
1687
1688         /// Builds the second-level holder HTLC transaction for the HTLC with index `htlc_index`.
1689         pub(crate) fn build_unsigned_htlc_tx(
1690                 &self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize,
1691                 preimage: &Option<PaymentPreimage>,
1692         ) -> Transaction {
1693                 let keys = &self.inner.keys;
1694                 let this_htlc = &self.inner.htlcs[htlc_index];
1695                 assert!(this_htlc.transaction_output_index.is_some());
1696                 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
1697                 if !this_htlc.offered && preimage.is_none() { unreachable!(); }
1698                 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
1699                 if  this_htlc.offered && preimage.is_some() { unreachable!(); }
1700
1701                 build_htlc_transaction(
1702                         &self.inner.built.txid, self.inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc,
1703                         &self.channel_type_features, &keys.broadcaster_delayed_payment_key, &keys.revocation_key
1704                 )
1705         }
1706
1707
1708         /// Builds the witness required to spend the input for the HTLC with index `htlc_index` in a
1709         /// second-level holder HTLC transaction.
1710         pub(crate) fn build_htlc_input_witness(
1711                 &self, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature,
1712                 preimage: &Option<PaymentPreimage>
1713         ) -> Witness {
1714                 let keys = &self.inner.keys;
1715                 let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(
1716                         &self.inner.htlcs[htlc_index], &self.channel_type_features, &keys.broadcaster_htlc_key,
1717                         &keys.countersignatory_htlc_key, &keys.revocation_key
1718                 );
1719                 chan_utils::build_htlc_input_witness(
1720                         signature, counterparty_signature, preimage, &htlc_redeemscript, &self.channel_type_features,
1721                 )
1722         }
1723
1724         /// Returns the index of the revokeable output, i.e. the `to_local` output sending funds to
1725         /// the broadcaster, in the built transaction, if any exists.
1726         ///
1727         /// There are two cases where this may return `None`:
1728         /// - The balance of the revokeable output is below the dust limit (only found on commitments
1729         /// early in the channel's lifetime, i.e. before the channel reserve is met).
1730         /// - This commitment was created before LDK 0.0.117. In this case, the
1731         /// commitment transaction previously didn't contain enough information to locate the
1732         /// revokeable output.
1733         pub fn revokeable_output_index(&self) -> Option<usize> {
1734                 let revokeable_redeemscript = get_revokeable_redeemscript(
1735                         &self.keys.revocation_key,
1736                         self.to_broadcaster_delay?,
1737                         &self.keys.broadcaster_delayed_payment_key,
1738                 );
1739                 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1740                 let outputs = &self.inner.built.transaction.output;
1741                 outputs.iter().enumerate()
1742                         .find(|(_, out)| out.script_pubkey == revokeable_p2wsh)
1743                         .map(|(idx, _)| idx)
1744         }
1745
1746         /// Helper method to build an unsigned justice transaction spending the revokeable
1747         /// `to_local` output to a destination script. Fee estimation accounts for the expected
1748         /// revocation witness data that will be added when signed.
1749         ///
1750         /// This method will error if the given fee rate results in a fee greater than the value
1751         /// of the output being spent, or if there exists no revokeable `to_local` output on this
1752         /// commitment transaction. See [`Self::revokeable_output_index`] for more details.
1753         ///
1754         /// The built transaction will allow fee bumping with RBF, and this method takes
1755         /// `feerate_per_kw` as an input such that multiple copies of a justice transaction at different
1756         /// fee rates may be built.
1757         pub fn build_to_local_justice_tx(&self, feerate_per_kw: u64, destination_script: ScriptBuf)
1758         -> Result<Transaction, ()> {
1759                 let output_idx = self.revokeable_output_index().ok_or(())?;
1760                 let input = vec![TxIn {
1761                         previous_output: OutPoint {
1762                                 txid: self.trust().txid(),
1763                                 vout: output_idx as u32,
1764                         },
1765                         script_sig: ScriptBuf::new(),
1766                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
1767                         witness: Witness::new(),
1768                 }];
1769                 let value = self.inner.built.transaction.output[output_idx].value;
1770                 let output = vec![TxOut {
1771                         script_pubkey: destination_script,
1772                         value,
1773                 }];
1774                 let mut justice_tx = Transaction {
1775                         version: 2,
1776                         lock_time: LockTime::ZERO,
1777                         input,
1778                         output,
1779                 };
1780                 let weight = justice_tx.weight().to_wu() + WEIGHT_REVOKED_OUTPUT;
1781                 let fee = fee_for_weight(feerate_per_kw as u32, weight);
1782                 justice_tx.output[0].value = value.checked_sub(fee).ok_or(())?;
1783                 Ok(justice_tx)
1784         }
1785
1786 }
1787
1788 /// Commitment transaction numbers which appear in the transactions themselves are XOR'd with a
1789 /// shared secret first. This prevents on-chain observers from discovering how many commitment
1790 /// transactions occurred in a channel before it was closed.
1791 ///
1792 /// This function gets the shared secret from relevant channel public keys and can be used to
1793 /// "decrypt" the commitment transaction number given a commitment transaction on-chain.
1794 pub fn get_commitment_transaction_number_obscure_factor(
1795         broadcaster_payment_basepoint: &PublicKey,
1796         countersignatory_payment_basepoint: &PublicKey,
1797         outbound_from_broadcaster: bool,
1798 ) -> u64 {
1799         let mut sha = Sha256::engine();
1800
1801         if outbound_from_broadcaster {
1802                 sha.input(&broadcaster_payment_basepoint.serialize());
1803                 sha.input(&countersignatory_payment_basepoint.serialize());
1804         } else {
1805                 sha.input(&countersignatory_payment_basepoint.serialize());
1806                 sha.input(&broadcaster_payment_basepoint.serialize());
1807         }
1808         let res = Sha256::from_engine(sha).to_byte_array();
1809
1810         ((res[26] as u64) << 5 * 8)
1811                 | ((res[27] as u64) << 4 * 8)
1812                 | ((res[28] as u64) << 3 * 8)
1813                 | ((res[29] as u64) << 2 * 8)
1814                 | ((res[30] as u64) << 1 * 8)
1815                 | ((res[31] as u64) << 0 * 8)
1816 }
1817
1818 #[cfg(test)]
1819 mod tests {
1820         use super::{CounterpartyCommitmentSecrets, ChannelPublicKeys};
1821         use crate::chain;
1822         use crate::ln::chan_utils::{get_htlc_redeemscript, get_to_countersignatory_with_anchors_redeemscript, CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
1823         use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
1824         use crate::util::test_utils;
1825         use crate::sign::{ChannelSigner, SignerProvider};
1826         use bitcoin::{Network, Txid, ScriptBuf};
1827         use bitcoin::hashes::Hash;
1828         use bitcoin::hashes::hex::FromHex;
1829         use crate::ln::PaymentHash;
1830         use bitcoin::address::Payload;
1831         use bitcoin::PublicKey as BitcoinPublicKey;
1832         use crate::ln::features::ChannelTypeFeatures;
1833
1834         #[allow(unused_imports)]
1835         use crate::prelude::*;
1836
1837         struct TestCommitmentTxBuilder {
1838                 commitment_number: u64,
1839                 holder_funding_pubkey: PublicKey,
1840                 counterparty_funding_pubkey: PublicKey,
1841                 keys: TxCreationKeys,
1842                 feerate_per_kw: u32,
1843                 htlcs_with_aux: Vec<(HTLCOutputInCommitment, ())>,
1844                 channel_parameters: ChannelTransactionParameters,
1845                 counterparty_pubkeys: ChannelPublicKeys,
1846         }
1847
1848         impl TestCommitmentTxBuilder {
1849                 fn new() -> Self {
1850                         let secp_ctx = Secp256k1::new();
1851                         let seed = [42; 32];
1852                         let network = Network::Testnet;
1853                         let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
1854                         let signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(false, 1_000_000, 0));
1855                         let counterparty_signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(true, 1_000_000, 1));
1856                         let delayed_payment_base = &signer.pubkeys().delayed_payment_basepoint;
1857                         let per_commitment_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
1858                         let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
1859                         let htlc_basepoint = &signer.pubkeys().htlc_basepoint;
1860                         let holder_pubkeys = signer.pubkeys();
1861                         let counterparty_pubkeys = counterparty_signer.pubkeys().clone();
1862                         let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint);
1863                         let channel_parameters = ChannelTransactionParameters {
1864                                 holder_pubkeys: holder_pubkeys.clone(),
1865                                 holder_selected_contest_delay: 0,
1866                                 is_outbound_from_holder: false,
1867                                 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: counterparty_pubkeys.clone(), selected_contest_delay: 0 }),
1868                                 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1869                                 channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
1870                         };
1871                         let htlcs_with_aux = Vec::new();
1872
1873                         Self {
1874                                 commitment_number: 0,
1875                                 holder_funding_pubkey: holder_pubkeys.funding_pubkey,
1876                                 counterparty_funding_pubkey: counterparty_pubkeys.funding_pubkey,
1877                                 keys,
1878                                 feerate_per_kw: 1,
1879                                 htlcs_with_aux,
1880                                 channel_parameters,
1881                                 counterparty_pubkeys,
1882                         }
1883                 }
1884
1885                 fn build(&mut self, to_broadcaster_sats: u64, to_countersignatory_sats: u64) -> CommitmentTransaction {
1886                         CommitmentTransaction::new_with_auxiliary_htlc_data(
1887                                 self.commitment_number, to_broadcaster_sats, to_countersignatory_sats,
1888                                 self.holder_funding_pubkey.clone(),
1889                                 self.counterparty_funding_pubkey.clone(),
1890                                 self.keys.clone(), self.feerate_per_kw,
1891                                 &mut self.htlcs_with_aux, &self.channel_parameters.as_holder_broadcastable()
1892                         )
1893                 }
1894         }
1895
1896         #[test]
1897         fn test_anchors() {
1898                 let mut builder = TestCommitmentTxBuilder::new();
1899
1900                 // Generate broadcaster and counterparty outputs
1901                 let tx = builder.build(1000, 2000);
1902                 assert_eq!(tx.built.transaction.output.len(), 2);
1903                 assert_eq!(tx.built.transaction.output[1].script_pubkey, Payload::p2wpkh(&BitcoinPublicKey::new(builder.counterparty_pubkeys.payment_point)).unwrap().script_pubkey());
1904
1905                 // Generate broadcaster and counterparty outputs as well as two anchors
1906                 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
1907                 let tx = builder.build(1000, 2000);
1908                 assert_eq!(tx.built.transaction.output.len(), 4);
1909                 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_to_countersignatory_with_anchors_redeemscript(&builder.counterparty_pubkeys.payment_point).to_v0_p2wsh());
1910
1911                 // Generate broadcaster output and anchor
1912                 let tx = builder.build(3000, 0);
1913                 assert_eq!(tx.built.transaction.output.len(), 2);
1914
1915                 // Generate counterparty output and anchor
1916                 let tx = builder.build(0, 3000);
1917                 assert_eq!(tx.built.transaction.output.len(), 2);
1918
1919                 let received_htlc = HTLCOutputInCommitment {
1920                         offered: false,
1921                         amount_msat: 400000,
1922                         cltv_expiry: 100,
1923                         payment_hash: PaymentHash([42; 32]),
1924                         transaction_output_index: None,
1925                 };
1926
1927                 let offered_htlc = HTLCOutputInCommitment {
1928                         offered: true,
1929                         amount_msat: 600000,
1930                         cltv_expiry: 100,
1931                         payment_hash: PaymentHash([43; 32]),
1932                         transaction_output_index: None,
1933                 };
1934
1935                 // Generate broadcaster output and received and offered HTLC outputs,  w/o anchors
1936                 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1937                 builder.htlcs_with_aux = vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())];
1938                 let tx = builder.build(3000, 0);
1939                 let keys = &builder.keys.clone();
1940                 assert_eq!(tx.built.transaction.output.len(), 3);
1941                 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh());
1942                 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh());
1943                 assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh().to_hex_string(),
1944                                    "0020e43a7c068553003fe68fcae424fb7b28ec5ce48cd8b6744b3945631389bad2fb");
1945                 assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh().to_hex_string(),
1946                                    "0020215d61bba56b19e9eadb6107f5a85d7f99c40f65992443f69229c290165bc00d");
1947
1948                 // Generate broadcaster output and received and offered HTLC outputs,  with anchors
1949                 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
1950                 builder.htlcs_with_aux = vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())];
1951                 let tx = builder.build(3000, 0);
1952                 assert_eq!(tx.built.transaction.output.len(), 5);
1953                 assert_eq!(tx.built.transaction.output[2].script_pubkey, get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_v0_p2wsh());
1954                 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_v0_p2wsh());
1955                 assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_v0_p2wsh().to_hex_string(),
1956                                    "0020b70d0649c72b38756885c7a30908d912a7898dd5d79457a7280b8e9a20f3f2bc");
1957                 assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_v0_p2wsh().to_hex_string(),
1958                                    "002087a3faeb1950a469c0e2db4a79b093a41b9526e5a6fc6ef5cb949bde3be379c7");
1959         }
1960
1961         #[test]
1962         fn test_finding_revokeable_output_index() {
1963                 let mut builder = TestCommitmentTxBuilder::new();
1964
1965                 // Revokeable output present
1966                 let tx = builder.build(1000, 2000);
1967                 assert_eq!(tx.built.transaction.output.len(), 2);
1968                 assert_eq!(tx.trust().revokeable_output_index(), Some(0));
1969
1970                 // Revokeable output present (but to_broadcaster_delay missing)
1971                 let tx = CommitmentTransaction { to_broadcaster_delay: None, ..tx };
1972                 assert_eq!(tx.built.transaction.output.len(), 2);
1973                 assert_eq!(tx.trust().revokeable_output_index(), None);
1974
1975                 // Revokeable output not present (our balance is dust)
1976                 let tx = builder.build(0, 2000);
1977                 assert_eq!(tx.built.transaction.output.len(), 1);
1978                 assert_eq!(tx.trust().revokeable_output_index(), None);
1979         }
1980
1981         #[test]
1982         fn test_building_to_local_justice_tx() {
1983                 let mut builder = TestCommitmentTxBuilder::new();
1984
1985                 // Revokeable output not present (our balance is dust)
1986                 let tx = builder.build(0, 2000);
1987                 assert_eq!(tx.built.transaction.output.len(), 1);
1988                 assert!(tx.trust().build_to_local_justice_tx(253, ScriptBuf::new()).is_err());
1989
1990                 // Revokeable output present
1991                 let tx = builder.build(1000, 2000);
1992                 assert_eq!(tx.built.transaction.output.len(), 2);
1993
1994                 // Too high feerate
1995                 assert!(tx.trust().build_to_local_justice_tx(100_000, ScriptBuf::new()).is_err());
1996
1997                 // Generate a random public key for destination script
1998                 let secret_key = SecretKey::from_slice(
1999                         &<Vec<u8>>::from_hex("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100")
2000                         .unwrap()[..]).unwrap();
2001                 let pubkey_hash = BitcoinPublicKey::new(
2002                         PublicKey::from_secret_key(&Secp256k1::new(), &secret_key)).wpubkey_hash().unwrap();
2003                 let destination_script = ScriptBuf::new_v0_p2wpkh(&pubkey_hash);
2004
2005                 let justice_tx = tx.trust().build_to_local_justice_tx(253, destination_script.clone()).unwrap();
2006                 assert_eq!(justice_tx.input.len(), 1);
2007                 assert_eq!(justice_tx.input[0].previous_output.txid, tx.built.transaction.txid());
2008                 assert_eq!(justice_tx.input[0].previous_output.vout, tx.trust().revokeable_output_index().unwrap() as u32);
2009                 assert!(justice_tx.input[0].sequence.is_rbf());
2010
2011                 assert_eq!(justice_tx.output.len(), 1);
2012                 assert!(justice_tx.output[0].value < 1000);
2013                 assert_eq!(justice_tx.output[0].script_pubkey, destination_script);
2014         }
2015
2016         #[test]
2017         fn test_per_commitment_storage() {
2018                 // Test vectors from BOLT 3:
2019                 let mut secrets: Vec<[u8; 32]> = Vec::new();
2020                 let mut monitor;
2021
2022                 macro_rules! test_secrets {
2023                         () => {
2024                                 let mut idx = 281474976710655;
2025                                 for secret in secrets.iter() {
2026                                         assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
2027                                         idx -= 1;
2028                                 }
2029                                 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
2030                                 assert!(monitor.get_secret(idx).is_none());
2031                         };
2032                 }
2033
2034                 {
2035                         // insert_secret correct sequence
2036                         monitor = CounterpartyCommitmentSecrets::new();
2037                         secrets.clear();
2038
2039                         secrets.push([0; 32]);
2040                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2041                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2042                         test_secrets!();
2043
2044                         secrets.push([0; 32]);
2045                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2046                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2047                         test_secrets!();
2048
2049                         secrets.push([0; 32]);
2050                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2051                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2052                         test_secrets!();
2053
2054                         secrets.push([0; 32]);
2055                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2056                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2057                         test_secrets!();
2058
2059                         secrets.push([0; 32]);
2060                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2061                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2062                         test_secrets!();
2063
2064                         secrets.push([0; 32]);
2065                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2066                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2067                         test_secrets!();
2068
2069                         secrets.push([0; 32]);
2070                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2071                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2072                         test_secrets!();
2073
2074                         secrets.push([0; 32]);
2075                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2076                         monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
2077                         test_secrets!();
2078                 }
2079
2080                 {
2081                         // insert_secret #1 incorrect
2082                         monitor = CounterpartyCommitmentSecrets::new();
2083                         secrets.clear();
2084
2085                         secrets.push([0; 32]);
2086                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2087                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2088                         test_secrets!();
2089
2090                         secrets.push([0; 32]);
2091                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2092                         assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
2093                 }
2094
2095                 {
2096                         // insert_secret #2 incorrect (#1 derived from incorrect)
2097                         monitor = CounterpartyCommitmentSecrets::new();
2098                         secrets.clear();
2099
2100                         secrets.push([0; 32]);
2101                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2102                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2103                         test_secrets!();
2104
2105                         secrets.push([0; 32]);
2106                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2107                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2108                         test_secrets!();
2109
2110                         secrets.push([0; 32]);
2111                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2112                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2113                         test_secrets!();
2114
2115                         secrets.push([0; 32]);
2116                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2117                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
2118                 }
2119
2120                 {
2121                         // insert_secret #3 incorrect
2122                         monitor = CounterpartyCommitmentSecrets::new();
2123                         secrets.clear();
2124
2125                         secrets.push([0; 32]);
2126                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2127                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2128                         test_secrets!();
2129
2130                         secrets.push([0; 32]);
2131                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2132                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2133                         test_secrets!();
2134
2135                         secrets.push([0; 32]);
2136                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2137                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2138                         test_secrets!();
2139
2140                         secrets.push([0; 32]);
2141                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2142                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
2143                 }
2144
2145                 {
2146                         // insert_secret #4 incorrect (1,2,3 derived from incorrect)
2147                         monitor = CounterpartyCommitmentSecrets::new();
2148                         secrets.clear();
2149
2150                         secrets.push([0; 32]);
2151                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2152                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2153                         test_secrets!();
2154
2155                         secrets.push([0; 32]);
2156                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2157                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2158                         test_secrets!();
2159
2160                         secrets.push([0; 32]);
2161                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2162                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2163                         test_secrets!();
2164
2165                         secrets.push([0; 32]);
2166                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
2167                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2168                         test_secrets!();
2169
2170                         secrets.push([0; 32]);
2171                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2172                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2173                         test_secrets!();
2174
2175                         secrets.push([0; 32]);
2176                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2177                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2178                         test_secrets!();
2179
2180                         secrets.push([0; 32]);
2181                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2182                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2183                         test_secrets!();
2184
2185                         secrets.push([0; 32]);
2186                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2187                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2188                 }
2189
2190                 {
2191                         // insert_secret #5 incorrect
2192                         monitor = CounterpartyCommitmentSecrets::new();
2193                         secrets.clear();
2194
2195                         secrets.push([0; 32]);
2196                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2197                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2198                         test_secrets!();
2199
2200                         secrets.push([0; 32]);
2201                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2202                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2203                         test_secrets!();
2204
2205                         secrets.push([0; 32]);
2206                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2207                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2208                         test_secrets!();
2209
2210                         secrets.push([0; 32]);
2211                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2212                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2213                         test_secrets!();
2214
2215                         secrets.push([0; 32]);
2216                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2217                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2218                         test_secrets!();
2219
2220                         secrets.push([0; 32]);
2221                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2222                         assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
2223                 }
2224
2225                 {
2226                         // insert_secret #6 incorrect (5 derived from incorrect)
2227                         monitor = CounterpartyCommitmentSecrets::new();
2228                         secrets.clear();
2229
2230                         secrets.push([0; 32]);
2231                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2232                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2233                         test_secrets!();
2234
2235                         secrets.push([0; 32]);
2236                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2237                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2238                         test_secrets!();
2239
2240                         secrets.push([0; 32]);
2241                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2242                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2243                         test_secrets!();
2244
2245                         secrets.push([0; 32]);
2246                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2247                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2248                         test_secrets!();
2249
2250                         secrets.push([0; 32]);
2251                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2252                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2253                         test_secrets!();
2254
2255                         secrets.push([0; 32]);
2256                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
2257                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2258                         test_secrets!();
2259
2260                         secrets.push([0; 32]);
2261                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2262                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2263                         test_secrets!();
2264
2265                         secrets.push([0; 32]);
2266                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2267                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2268                 }
2269
2270                 {
2271                         // insert_secret #7 incorrect
2272                         monitor = CounterpartyCommitmentSecrets::new();
2273                         secrets.clear();
2274
2275                         secrets.push([0; 32]);
2276                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2277                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2278                         test_secrets!();
2279
2280                         secrets.push([0; 32]);
2281                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2282                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2283                         test_secrets!();
2284
2285                         secrets.push([0; 32]);
2286                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2287                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2288                         test_secrets!();
2289
2290                         secrets.push([0; 32]);
2291                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2292                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2293                         test_secrets!();
2294
2295                         secrets.push([0; 32]);
2296                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2297                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2298                         test_secrets!();
2299
2300                         secrets.push([0; 32]);
2301                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2302                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2303                         test_secrets!();
2304
2305                         secrets.push([0; 32]);
2306                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2307                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2308                         test_secrets!();
2309
2310                         secrets.push([0; 32]);
2311                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2312                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2313                 }
2314
2315                 {
2316                         // insert_secret #8 incorrect
2317                         monitor = CounterpartyCommitmentSecrets::new();
2318                         secrets.clear();
2319
2320                         secrets.push([0; 32]);
2321                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2322                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2323                         test_secrets!();
2324
2325                         secrets.push([0; 32]);
2326                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2327                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2328                         test_secrets!();
2329
2330                         secrets.push([0; 32]);
2331                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2332                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2333                         test_secrets!();
2334
2335                         secrets.push([0; 32]);
2336                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2337                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2338                         test_secrets!();
2339
2340                         secrets.push([0; 32]);
2341                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2342                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2343                         test_secrets!();
2344
2345                         secrets.push([0; 32]);
2346                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2347                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2348                         test_secrets!();
2349
2350                         secrets.push([0; 32]);
2351                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2352                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2353                         test_secrets!();
2354
2355                         secrets.push([0; 32]);
2356                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2357                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2358                 }
2359         }
2360 }