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