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