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