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