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