]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/chan_utils.rs
9ee564df59d99e7679b244101bab4c0c5742ff68
[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 /// Locates the output with an anchor script paying to `funding_pubkey` within `commitment_tx`.
833 pub(crate) fn get_anchor_output<'a>(commitment_tx: &'a Transaction, funding_pubkey: &PublicKey) -> Option<(u32, &'a TxOut)> {
834         let anchor_script = chan_utils::get_anchor_redeemscript(funding_pubkey).to_v0_p2wsh();
835         commitment_tx.output.iter().enumerate()
836                 .find(|(_, txout)| txout.script_pubkey == anchor_script)
837                 .map(|(idx, txout)| (idx as u32, txout))
838 }
839
840 /// Returns the witness required to satisfy and spend an anchor input.
841 pub fn build_anchor_input_witness(funding_key: &PublicKey, funding_sig: &Signature) -> Witness {
842         let anchor_redeem_script = chan_utils::get_anchor_redeemscript(funding_key);
843         let mut ret = Witness::new();
844         ret.push_bitcoin_signature(&funding_sig.serialize_der(), EcdsaSighashType::All);
845         ret.push(anchor_redeem_script.as_bytes());
846         ret
847 }
848
849 /// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
850 /// The fields are organized by holder/counterparty.
851 ///
852 /// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
853 /// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
854 #[derive(Clone, Debug, PartialEq, Eq)]
855 pub struct ChannelTransactionParameters {
856         /// Holder public keys
857         pub holder_pubkeys: ChannelPublicKeys,
858         /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
859         pub holder_selected_contest_delay: u16,
860         /// Whether the holder is the initiator of this channel.
861         /// This is an input to the commitment number obscure factor computation.
862         pub is_outbound_from_holder: bool,
863         /// The late-bound counterparty channel transaction parameters.
864         /// These parameters are populated at the point in the protocol where the counterparty provides them.
865         pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
866         /// The late-bound funding outpoint
867         pub funding_outpoint: Option<chain::transaction::OutPoint>,
868         /// This channel's type, as negotiated during channel open. For old objects where this field
869         /// wasn't serialized, it will default to static_remote_key at deserialization.
870         pub channel_type_features: ChannelTypeFeatures
871 }
872
873 /// Late-bound per-channel counterparty data used to build transactions.
874 #[derive(Clone, Debug, PartialEq, Eq)]
875 pub struct CounterpartyChannelTransactionParameters {
876         /// Counter-party public keys
877         pub pubkeys: ChannelPublicKeys,
878         /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
879         pub selected_contest_delay: u16,
880 }
881
882 impl ChannelTransactionParameters {
883         /// Whether the late bound parameters are populated.
884         pub fn is_populated(&self) -> bool {
885                 self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
886         }
887
888         /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
889         /// given that the holder is the broadcaster.
890         ///
891         /// self.is_populated() must be true before calling this function.
892         pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
893                 assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
894                 DirectedChannelTransactionParameters {
895                         inner: self,
896                         holder_is_broadcaster: true
897                 }
898         }
899
900         /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
901         /// given that the counterparty is the broadcaster.
902         ///
903         /// self.is_populated() must be true before calling this function.
904         pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
905                 assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
906                 DirectedChannelTransactionParameters {
907                         inner: self,
908                         holder_is_broadcaster: false
909                 }
910         }
911 }
912
913 impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, {
914         (0, pubkeys, required),
915         (2, selected_contest_delay, required),
916 });
917
918 impl Writeable for ChannelTransactionParameters {
919         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
920                 let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
921                 write_tlv_fields!(writer, {
922                         (0, self.holder_pubkeys, required),
923                         (2, self.holder_selected_contest_delay, required),
924                         (4, self.is_outbound_from_holder, required),
925                         (6, self.counterparty_parameters, option),
926                         (8, self.funding_outpoint, option),
927                         (10, legacy_deserialization_prevention_marker, option),
928                         (11, self.channel_type_features, required),
929                 });
930                 Ok(())
931         }
932 }
933
934 impl Readable for ChannelTransactionParameters {
935         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
936                 let mut holder_pubkeys = RequiredWrapper(None);
937                 let mut holder_selected_contest_delay = RequiredWrapper(None);
938                 let mut is_outbound_from_holder = RequiredWrapper(None);
939                 let mut counterparty_parameters = None;
940                 let mut funding_outpoint = None;
941                 let mut _legacy_deserialization_prevention_marker: Option<()> = None;
942                 let mut channel_type_features = None;
943
944                 read_tlv_fields!(reader, {
945                         (0, holder_pubkeys, required),
946                         (2, holder_selected_contest_delay, required),
947                         (4, is_outbound_from_holder, required),
948                         (6, counterparty_parameters, option),
949                         (8, funding_outpoint, option),
950                         (10, _legacy_deserialization_prevention_marker, option),
951                         (11, channel_type_features, option),
952                 });
953
954                 let mut additional_features = ChannelTypeFeatures::empty();
955                 additional_features.set_anchors_nonzero_fee_htlc_tx_required();
956                 chain::package::verify_channel_type_features(&channel_type_features, Some(&additional_features))?;
957
958                 Ok(Self {
959                         holder_pubkeys: holder_pubkeys.0.unwrap(),
960                         holder_selected_contest_delay: holder_selected_contest_delay.0.unwrap(),
961                         is_outbound_from_holder: is_outbound_from_holder.0.unwrap(),
962                         counterparty_parameters,
963                         funding_outpoint,
964                         channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
965                 })
966         }
967 }
968
969 /// Static channel fields used to build transactions given per-commitment fields, organized by
970 /// broadcaster/countersignatory.
971 ///
972 /// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
973 /// as_holder_broadcastable and as_counterparty_broadcastable functions.
974 pub struct DirectedChannelTransactionParameters<'a> {
975         /// The holder's channel static parameters
976         inner: &'a ChannelTransactionParameters,
977         /// Whether the holder is the broadcaster
978         holder_is_broadcaster: bool,
979 }
980
981 impl<'a> DirectedChannelTransactionParameters<'a> {
982         /// Get the channel pubkeys for the broadcaster
983         pub fn broadcaster_pubkeys(&self) -> &ChannelPublicKeys {
984                 if self.holder_is_broadcaster {
985                         &self.inner.holder_pubkeys
986                 } else {
987                         &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
988                 }
989         }
990
991         /// Get the channel pubkeys for the countersignatory
992         pub fn countersignatory_pubkeys(&self) -> &ChannelPublicKeys {
993                 if self.holder_is_broadcaster {
994                         &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
995                 } else {
996                         &self.inner.holder_pubkeys
997                 }
998         }
999
1000         /// Get the contest delay applicable to the transactions.
1001         /// Note that the contest delay was selected by the countersignatory.
1002         pub fn contest_delay(&self) -> u16 {
1003                 let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
1004                 if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
1005         }
1006
1007         /// Whether the channel is outbound from the broadcaster.
1008         ///
1009         /// The boolean representing the side that initiated the channel is
1010         /// an input to the commitment number obscure factor computation.
1011         pub fn is_outbound(&self) -> bool {
1012                 if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
1013         }
1014
1015         /// The funding outpoint
1016         pub fn funding_outpoint(&self) -> OutPoint {
1017                 self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
1018         }
1019
1020         /// Whether to use anchors for this channel
1021         pub fn channel_type_features(&self) -> &ChannelTypeFeatures {
1022                 &self.inner.channel_type_features
1023         }
1024 }
1025
1026 /// Information needed to build and sign a holder's commitment transaction.
1027 ///
1028 /// The transaction is only signed once we are ready to broadcast.
1029 #[derive(Clone)]
1030 pub struct HolderCommitmentTransaction {
1031         inner: CommitmentTransaction,
1032         /// Our counterparty's signature for the transaction
1033         pub counterparty_sig: Signature,
1034         /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
1035         pub counterparty_htlc_sigs: Vec<Signature>,
1036         // Which order the signatures should go in when constructing the final commitment tx witness.
1037         // The user should be able to reconstruct this themselves, so we don't bother to expose it.
1038         holder_sig_first: bool,
1039 }
1040
1041 impl Deref for HolderCommitmentTransaction {
1042         type Target = CommitmentTransaction;
1043
1044         fn deref(&self) -> &Self::Target { &self.inner }
1045 }
1046
1047 impl Eq for HolderCommitmentTransaction {}
1048 impl PartialEq for HolderCommitmentTransaction {
1049         // We dont care whether we are signed in equality comparison
1050         fn eq(&self, o: &Self) -> bool {
1051                 self.inner == o.inner
1052         }
1053 }
1054
1055 impl_writeable_tlv_based!(HolderCommitmentTransaction, {
1056         (0, inner, required),
1057         (2, counterparty_sig, required),
1058         (4, holder_sig_first, required),
1059         (6, counterparty_htlc_sigs, required_vec),
1060 });
1061
1062 impl HolderCommitmentTransaction {
1063         #[cfg(test)]
1064         pub fn dummy(htlcs: &mut Vec<(HTLCOutputInCommitment, ())>) -> Self {
1065                 let secp_ctx = Secp256k1::new();
1066                 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1067                 let dummy_sig = sign(&secp_ctx, &secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
1068
1069                 let keys = TxCreationKeys {
1070                         per_commitment_point: dummy_key.clone(),
1071                         revocation_key: dummy_key.clone(),
1072                         broadcaster_htlc_key: dummy_key.clone(),
1073                         countersignatory_htlc_key: dummy_key.clone(),
1074                         broadcaster_delayed_payment_key: dummy_key.clone(),
1075                 };
1076                 let channel_pubkeys = ChannelPublicKeys {
1077                         funding_pubkey: dummy_key.clone(),
1078                         revocation_basepoint: dummy_key.clone(),
1079                         payment_point: dummy_key.clone(),
1080                         delayed_payment_basepoint: dummy_key.clone(),
1081                         htlc_basepoint: dummy_key.clone()
1082                 };
1083                 let channel_parameters = ChannelTransactionParameters {
1084                         holder_pubkeys: channel_pubkeys.clone(),
1085                         holder_selected_contest_delay: 0,
1086                         is_outbound_from_holder: false,
1087                         counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
1088                         funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1089                         channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
1090                 };
1091                 let mut counterparty_htlc_sigs = Vec::new();
1092                 for _ in 0..htlcs.len() {
1093                         counterparty_htlc_sigs.push(dummy_sig);
1094                 }
1095                 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());
1096                 htlcs.sort_by_key(|htlc| htlc.0.transaction_output_index);
1097                 HolderCommitmentTransaction {
1098                         inner,
1099                         counterparty_sig: dummy_sig,
1100                         counterparty_htlc_sigs,
1101                         holder_sig_first: false
1102                 }
1103         }
1104
1105         /// Create a new holder transaction with the given counterparty signatures.
1106         /// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
1107         pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
1108                 Self {
1109                         inner: commitment_tx,
1110                         counterparty_sig,
1111                         counterparty_htlc_sigs,
1112                         holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
1113                 }
1114         }
1115
1116         pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
1117                 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
1118                 let mut tx = self.inner.built.transaction.clone();
1119                 tx.input[0].witness.push(Vec::new());
1120
1121                 if self.holder_sig_first {
1122                         tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1123                         tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1124                 } else {
1125                         tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1126                         tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1127                 }
1128
1129                 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
1130                 tx
1131         }
1132 }
1133
1134 /// A pre-built Bitcoin commitment transaction and its txid.
1135 #[derive(Clone)]
1136 pub struct BuiltCommitmentTransaction {
1137         /// The commitment transaction
1138         pub transaction: Transaction,
1139         /// The txid for the commitment transaction.
1140         ///
1141         /// This is provided as a performance optimization, instead of calling transaction.txid()
1142         /// multiple times.
1143         pub txid: Txid,
1144 }
1145
1146 impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
1147         (0, transaction, required),
1148         (2, txid, required),
1149 });
1150
1151 impl BuiltCommitmentTransaction {
1152         /// Get the SIGHASH_ALL sighash value of the transaction.
1153         ///
1154         /// This can be used to verify a signature.
1155         pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1156                 let sighash = &sighash::SighashCache::new(&self.transaction).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1157                 hash_to_message!(sighash)
1158         }
1159
1160         /// Signs the counterparty's commitment transaction.
1161         pub fn sign_counterparty_commitment<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1162                 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1163                 sign(secp_ctx, &sighash, funding_key)
1164         }
1165
1166         /// Signs the holder commitment transaction because we are about to broadcast it.
1167         pub fn sign_holder_commitment<T: secp256k1::Signing, ES: Deref>(
1168                 &self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64,
1169                 entropy_source: &ES, secp_ctx: &Secp256k1<T>
1170         ) -> Signature where ES::Target: EntropySource {
1171                 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1172                 sign_with_aux_rand(secp_ctx, &sighash, funding_key, entropy_source)
1173         }
1174 }
1175
1176 /// This class tracks the per-transaction information needed to build a closing transaction and will
1177 /// actually build it and sign.
1178 ///
1179 /// This class can be used inside a signer implementation to generate a signature given the relevant
1180 /// secret key.
1181 #[derive(Clone, Hash, PartialEq, Eq)]
1182 pub struct ClosingTransaction {
1183         to_holder_value_sat: u64,
1184         to_counterparty_value_sat: u64,
1185         to_holder_script: Script,
1186         to_counterparty_script: Script,
1187         built: Transaction,
1188 }
1189
1190 impl ClosingTransaction {
1191         /// Construct an object of the class
1192         pub fn new(
1193                 to_holder_value_sat: u64,
1194                 to_counterparty_value_sat: u64,
1195                 to_holder_script: Script,
1196                 to_counterparty_script: Script,
1197                 funding_outpoint: OutPoint,
1198         ) -> Self {
1199                 let built = build_closing_transaction(
1200                         to_holder_value_sat, to_counterparty_value_sat,
1201                         to_holder_script.clone(), to_counterparty_script.clone(),
1202                         funding_outpoint
1203                 );
1204                 ClosingTransaction {
1205                         to_holder_value_sat,
1206                         to_counterparty_value_sat,
1207                         to_holder_script,
1208                         to_counterparty_script,
1209                         built
1210                 }
1211         }
1212
1213         /// Trust our pre-built transaction.
1214         ///
1215         /// Applies a wrapper which allows access to the transaction.
1216         ///
1217         /// This should only be used if you fully trust the builder of this object. It should not
1218         /// be used by an external signer - instead use the verify function.
1219         pub fn trust(&self) -> TrustedClosingTransaction {
1220                 TrustedClosingTransaction { inner: self }
1221         }
1222
1223         /// Verify our pre-built transaction.
1224         ///
1225         /// Applies a wrapper which allows access to the transaction.
1226         ///
1227         /// An external validating signer must call this method before signing
1228         /// or using the built transaction.
1229         pub fn verify(&self, funding_outpoint: OutPoint) -> Result<TrustedClosingTransaction, ()> {
1230                 let built = build_closing_transaction(
1231                         self.to_holder_value_sat, self.to_counterparty_value_sat,
1232                         self.to_holder_script.clone(), self.to_counterparty_script.clone(),
1233                         funding_outpoint
1234                 );
1235                 if self.built != built {
1236                         return Err(())
1237                 }
1238                 Ok(TrustedClosingTransaction { inner: self })
1239         }
1240
1241         /// The value to be sent to the holder, or zero if the output will be omitted
1242         pub fn to_holder_value_sat(&self) -> u64 {
1243                 self.to_holder_value_sat
1244         }
1245
1246         /// The value to be sent to the counterparty, or zero if the output will be omitted
1247         pub fn to_counterparty_value_sat(&self) -> u64 {
1248                 self.to_counterparty_value_sat
1249         }
1250
1251         /// The destination of the holder's output
1252         pub fn to_holder_script(&self) -> &Script {
1253                 &self.to_holder_script
1254         }
1255
1256         /// The destination of the counterparty's output
1257         pub fn to_counterparty_script(&self) -> &Script {
1258                 &self.to_counterparty_script
1259         }
1260 }
1261
1262 /// A wrapper on ClosingTransaction indicating that the built bitcoin
1263 /// transaction is trusted.
1264 ///
1265 /// See trust() and verify() functions on CommitmentTransaction.
1266 ///
1267 /// This structure implements Deref.
1268 pub struct TrustedClosingTransaction<'a> {
1269         inner: &'a ClosingTransaction,
1270 }
1271
1272 impl<'a> Deref for TrustedClosingTransaction<'a> {
1273         type Target = ClosingTransaction;
1274
1275         fn deref(&self) -> &Self::Target { self.inner }
1276 }
1277
1278 impl<'a> TrustedClosingTransaction<'a> {
1279         /// The pre-built Bitcoin commitment transaction
1280         pub fn built_transaction(&self) -> &Transaction {
1281                 &self.inner.built
1282         }
1283
1284         /// Get the SIGHASH_ALL sighash value of the transaction.
1285         ///
1286         /// This can be used to verify a signature.
1287         pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1288                 let sighash = &sighash::SighashCache::new(&self.inner.built).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1289                 hash_to_message!(sighash)
1290         }
1291
1292         /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1293         /// because we are about to broadcast a holder transaction.
1294         pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1295                 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1296                 sign(secp_ctx, &sighash, funding_key)
1297         }
1298 }
1299
1300 /// This class tracks the per-transaction information needed to build a commitment transaction and will
1301 /// actually build it and sign.  It is used for holder transactions that we sign only when needed
1302 /// and for transactions we sign for the counterparty.
1303 ///
1304 /// This class can be used inside a signer implementation to generate a signature given the relevant
1305 /// secret key.
1306 #[derive(Clone)]
1307 pub struct CommitmentTransaction {
1308         commitment_number: u64,
1309         to_broadcaster_value_sat: u64,
1310         to_countersignatory_value_sat: u64,
1311         feerate_per_kw: u32,
1312         htlcs: Vec<HTLCOutputInCommitment>,
1313         // Note that on upgrades, some features of existing outputs may be missed.
1314         channel_type_features: ChannelTypeFeatures,
1315         // A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
1316         keys: TxCreationKeys,
1317         // For access to the pre-built transaction, see doc for trust()
1318         built: BuiltCommitmentTransaction,
1319 }
1320
1321 impl Eq for CommitmentTransaction {}
1322 impl PartialEq for CommitmentTransaction {
1323         fn eq(&self, o: &Self) -> bool {
1324                 let eq = self.commitment_number == o.commitment_number &&
1325                         self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
1326                         self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
1327                         self.feerate_per_kw == o.feerate_per_kw &&
1328                         self.htlcs == o.htlcs &&
1329                         self.channel_type_features == o.channel_type_features &&
1330                         self.keys == o.keys;
1331                 if eq {
1332                         debug_assert_eq!(self.built.transaction, o.built.transaction);
1333                         debug_assert_eq!(self.built.txid, o.built.txid);
1334                 }
1335                 eq
1336         }
1337 }
1338
1339 impl Writeable for CommitmentTransaction {
1340         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1341                 let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
1342                 write_tlv_fields!(writer, {
1343                         (0, self.commitment_number, required),
1344                         (2, self.to_broadcaster_value_sat, required),
1345                         (4, self.to_countersignatory_value_sat, required),
1346                         (6, self.feerate_per_kw, required),
1347                         (8, self.keys, required),
1348                         (10, self.built, required),
1349                         (12, self.htlcs, required_vec),
1350                         (14, legacy_deserialization_prevention_marker, option),
1351                         (15, self.channel_type_features, required),
1352                 });
1353                 Ok(())
1354         }
1355 }
1356
1357 impl Readable for CommitmentTransaction {
1358         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1359                 _init_and_read_len_prefixed_tlv_fields!(reader, {
1360                         (0, commitment_number, required),
1361                         (2, to_broadcaster_value_sat, required),
1362                         (4, to_countersignatory_value_sat, required),
1363                         (6, feerate_per_kw, required),
1364                         (8, keys, required),
1365                         (10, built, required),
1366                         (12, htlcs, required_vec),
1367                         (14, _legacy_deserialization_prevention_marker, option),
1368                         (15, channel_type_features, option),
1369                 });
1370
1371                 let mut additional_features = ChannelTypeFeatures::empty();
1372                 additional_features.set_anchors_nonzero_fee_htlc_tx_required();
1373                 chain::package::verify_channel_type_features(&channel_type_features, Some(&additional_features))?;
1374
1375                 Ok(Self {
1376                         commitment_number: commitment_number.0.unwrap(),
1377                         to_broadcaster_value_sat: to_broadcaster_value_sat.0.unwrap(),
1378                         to_countersignatory_value_sat: to_countersignatory_value_sat.0.unwrap(),
1379                         feerate_per_kw: feerate_per_kw.0.unwrap(),
1380                         keys: keys.0.unwrap(),
1381                         built: built.0.unwrap(),
1382                         htlcs,
1383                         channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
1384                 })
1385         }
1386 }
1387
1388 impl CommitmentTransaction {
1389         /// Construct an object of the class while assigning transaction output indices to HTLCs.
1390         ///
1391         /// Populates HTLCOutputInCommitment.transaction_output_index in htlcs_with_aux.
1392         ///
1393         /// The generic T allows the caller to match the HTLC output index with auxiliary data.
1394         /// This auxiliary data is not stored in this object.
1395         ///
1396         /// Only include HTLCs that are above the dust limit for the channel.
1397         ///
1398         /// This is not exported to bindings users due to the generic though we likely should expose a version without
1399         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 {
1400                 // Sort outputs and populate output indices while keeping track of the auxiliary data
1401                 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();
1402
1403                 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
1404                 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1405                 let txid = transaction.txid();
1406                 CommitmentTransaction {
1407                         commitment_number,
1408                         to_broadcaster_value_sat,
1409                         to_countersignatory_value_sat,
1410                         feerate_per_kw,
1411                         htlcs,
1412                         channel_type_features: channel_parameters.channel_type_features().clone(),
1413                         keys,
1414                         built: BuiltCommitmentTransaction {
1415                                 transaction,
1416                                 txid
1417                         },
1418                 }
1419         }
1420
1421         /// Use non-zero fee anchors
1422         ///
1423         /// This is not exported to bindings users due to move, and also not likely to be useful for binding users
1424         pub fn with_non_zero_fee_anchors(mut self) -> Self {
1425                 self.channel_type_features.set_anchors_nonzero_fee_htlc_tx_required();
1426                 self
1427         }
1428
1429         fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<BuiltCommitmentTransaction, ()> {
1430                 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
1431
1432                 let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
1433                 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)?;
1434
1435                 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1436                 let txid = transaction.txid();
1437                 let built_transaction = BuiltCommitmentTransaction {
1438                         transaction,
1439                         txid
1440                 };
1441                 Ok(built_transaction)
1442         }
1443
1444         fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
1445                 Transaction {
1446                         version: 2,
1447                         lock_time: PackedLockTime(((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32)),
1448                         input: txins,
1449                         output: outputs,
1450                 }
1451         }
1452
1453         // This is used in two cases:
1454         // - initial sorting of outputs / HTLCs in the constructor, in which case T is auxiliary data the
1455         //   caller needs to have sorted together with the HTLCs so it can keep track of the output index
1456         // - building of a bitcoin transaction during a verify() call, in which case T is just ()
1457         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>), ()> {
1458                 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1459                 let contest_delay = channel_parameters.contest_delay();
1460
1461                 let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
1462
1463                 if to_countersignatory_value_sat > 0 {
1464                         let script = if channel_parameters.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
1465                             get_to_countersignatory_with_anchors_redeemscript(&countersignatory_pubkeys.payment_point).to_v0_p2wsh()
1466                         } else {
1467                             Payload::p2wpkh(&BitcoinPublicKey::new(countersignatory_pubkeys.payment_point)).unwrap().script_pubkey()
1468                         };
1469                         txouts.push((
1470                                 TxOut {
1471                                         script_pubkey: script.clone(),
1472                                         value: to_countersignatory_value_sat,
1473                                 },
1474                                 None,
1475                         ))
1476                 }
1477
1478                 if to_broadcaster_value_sat > 0 {
1479                         let redeem_script = get_revokeable_redeemscript(
1480                                 &keys.revocation_key,
1481                                 contest_delay,
1482                                 &keys.broadcaster_delayed_payment_key,
1483                         );
1484                         txouts.push((
1485                                 TxOut {
1486                                         script_pubkey: redeem_script.to_v0_p2wsh(),
1487                                         value: to_broadcaster_value_sat,
1488                                 },
1489                                 None,
1490                         ));
1491                 }
1492
1493                 if channel_parameters.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
1494                         if to_broadcaster_value_sat > 0 || !htlcs_with_aux.is_empty() {
1495                                 let anchor_script = get_anchor_redeemscript(broadcaster_funding_key);
1496                                 txouts.push((
1497                                         TxOut {
1498                                                 script_pubkey: anchor_script.to_v0_p2wsh(),
1499                                                 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1500                                         },
1501                                         None,
1502                                 ));
1503                         }
1504
1505                         if to_countersignatory_value_sat > 0 || !htlcs_with_aux.is_empty() {
1506                                 let anchor_script = get_anchor_redeemscript(countersignatory_funding_key);
1507                                 txouts.push((
1508                                         TxOut {
1509                                                 script_pubkey: anchor_script.to_v0_p2wsh(),
1510                                                 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1511                                         },
1512                                         None,
1513                                 ));
1514                         }
1515                 }
1516
1517                 let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
1518                 for (htlc, _) in htlcs_with_aux {
1519                         let script = chan_utils::get_htlc_redeemscript(&htlc, &channel_parameters.channel_type_features(), &keys);
1520                         let txout = TxOut {
1521                                 script_pubkey: script.to_v0_p2wsh(),
1522                                 value: htlc.amount_msat / 1000,
1523                         };
1524                         txouts.push((txout, Some(htlc)));
1525                 }
1526
1527                 // Sort output in BIP-69 order (amount, scriptPubkey).  Tie-breaks based on HTLC
1528                 // CLTV expiration height.
1529                 sort_outputs(&mut txouts, |a, b| {
1530                         if let &Some(ref a_htlcout) = a {
1531                                 if let &Some(ref b_htlcout) = b {
1532                                         a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
1533                                                 // Note that due to hash collisions, we have to have a fallback comparison
1534                                                 // here for fuzzing mode (otherwise at least chanmon_fail_consistency
1535                                                 // may fail)!
1536                                                 .then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
1537                                 // For non-HTLC outputs, if they're copying our SPK we don't really care if we
1538                                 // close the channel due to mismatches - they're doing something dumb:
1539                                 } else { cmp::Ordering::Equal }
1540                         } else { cmp::Ordering::Equal }
1541                 });
1542
1543                 let mut outputs = Vec::with_capacity(txouts.len());
1544                 for (idx, out) in txouts.drain(..).enumerate() {
1545                         if let Some(htlc) = out.1 {
1546                                 htlc.transaction_output_index = Some(idx as u32);
1547                                 htlcs.push(htlc.clone());
1548                         }
1549                         outputs.push(out.0);
1550                 }
1551                 Ok((outputs, htlcs))
1552         }
1553
1554         fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
1555                 let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
1556                 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1557                 let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
1558                         &broadcaster_pubkeys.payment_point,
1559                         &countersignatory_pubkeys.payment_point,
1560                         channel_parameters.is_outbound(),
1561                 );
1562
1563                 let obscured_commitment_transaction_number =
1564                         commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
1565
1566                 let txins = {
1567                         let mut ins: Vec<TxIn> = Vec::new();
1568                         ins.push(TxIn {
1569                                 previous_output: channel_parameters.funding_outpoint(),
1570                                 script_sig: Script::new(),
1571                                 sequence: Sequence(((0x80 as u32) << 8 * 3)
1572                                         | ((obscured_commitment_transaction_number >> 3 * 8) as u32)),
1573                                 witness: Witness::new(),
1574                         });
1575                         ins
1576                 };
1577                 (obscured_commitment_transaction_number, txins)
1578         }
1579
1580         /// The backwards-counting commitment number
1581         pub fn commitment_number(&self) -> u64 {
1582                 self.commitment_number
1583         }
1584
1585         /// The value to be sent to the broadcaster
1586         pub fn to_broadcaster_value_sat(&self) -> u64 {
1587                 self.to_broadcaster_value_sat
1588         }
1589
1590         /// The value to be sent to the counterparty
1591         pub fn to_countersignatory_value_sat(&self) -> u64 {
1592                 self.to_countersignatory_value_sat
1593         }
1594
1595         /// The feerate paid per 1000-weight-unit in this commitment transaction.
1596         pub fn feerate_per_kw(&self) -> u32 {
1597                 self.feerate_per_kw
1598         }
1599
1600         /// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
1601         /// which were included in this commitment transaction in output order.
1602         /// The transaction index is always populated.
1603         ///
1604         /// This is not exported to bindings users as we cannot currently convert Vec references to/from C, though we should
1605         /// expose a less effecient version which creates a Vec of references in the future.
1606         pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
1607                 &self.htlcs
1608         }
1609
1610         /// Trust our pre-built transaction and derived transaction creation public keys.
1611         ///
1612         /// Applies a wrapper which allows access to these fields.
1613         ///
1614         /// This should only be used if you fully trust the builder of this object.  It should not
1615         /// be used by an external signer - instead use the verify function.
1616         pub fn trust(&self) -> TrustedCommitmentTransaction {
1617                 TrustedCommitmentTransaction { inner: self }
1618         }
1619
1620         /// Verify our pre-built transaction and derived transaction creation public keys.
1621         ///
1622         /// Applies a wrapper which allows access to these fields.
1623         ///
1624         /// An external validating signer must call this method before signing
1625         /// or using the built transaction.
1626         pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
1627                 // This is the only field of the key cache that we trust
1628                 let per_commitment_point = self.keys.per_commitment_point;
1629                 let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx);
1630                 if keys != self.keys {
1631                         return Err(());
1632                 }
1633                 let tx = self.internal_rebuild_transaction(&keys, channel_parameters, &broadcaster_keys.funding_pubkey, &countersignatory_keys.funding_pubkey)?;
1634                 if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
1635                         return Err(());
1636                 }
1637                 Ok(TrustedCommitmentTransaction { inner: self })
1638         }
1639 }
1640
1641 /// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
1642 /// transaction and the transaction creation keys) are trusted.
1643 ///
1644 /// See trust() and verify() functions on CommitmentTransaction.
1645 ///
1646 /// This structure implements Deref.
1647 pub struct TrustedCommitmentTransaction<'a> {
1648         inner: &'a CommitmentTransaction,
1649 }
1650
1651 impl<'a> Deref for TrustedCommitmentTransaction<'a> {
1652         type Target = CommitmentTransaction;
1653
1654         fn deref(&self) -> &Self::Target { self.inner }
1655 }
1656
1657 impl<'a> TrustedCommitmentTransaction<'a> {
1658         /// The transaction ID of the built Bitcoin transaction
1659         pub fn txid(&self) -> Txid {
1660                 self.inner.built.txid
1661         }
1662
1663         /// The pre-built Bitcoin commitment transaction
1664         pub fn built_transaction(&self) -> &BuiltCommitmentTransaction {
1665                 &self.inner.built
1666         }
1667
1668         /// The pre-calculated transaction creation public keys.
1669         pub fn keys(&self) -> &TxCreationKeys {
1670                 &self.inner.keys
1671         }
1672
1673         /// Should anchors be used.
1674         pub fn channel_type_features(&self) -> &ChannelTypeFeatures {
1675                 &self.inner.channel_type_features
1676         }
1677
1678         /// Get a signature for each HTLC which was included in the commitment transaction (ie for
1679         /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
1680         ///
1681         /// The returned Vec has one entry for each HTLC, and in the same order.
1682         ///
1683         /// This function is only valid in the holder commitment context, it always uses EcdsaSighashType::All.
1684         pub fn get_htlc_sigs<T: secp256k1::Signing, ES: Deref>(
1685                 &self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters,
1686                 entropy_source: &ES, secp_ctx: &Secp256k1<T>,
1687         ) -> Result<Vec<Signature>, ()> where ES::Target: EntropySource {
1688                 let inner = self.inner;
1689                 let keys = &inner.keys;
1690                 let txid = inner.built.txid;
1691                 let mut ret = Vec::with_capacity(inner.htlcs.len());
1692                 let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key);
1693
1694                 for this_htlc in inner.htlcs.iter() {
1695                         assert!(this_htlc.transaction_output_index.is_some());
1696                         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);
1697
1698                         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);
1699
1700                         let sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, EcdsaSighashType::All).unwrap()[..]);
1701                         ret.push(sign_with_aux_rand(secp_ctx, &sighash, &holder_htlc_key, entropy_source));
1702                 }
1703                 Ok(ret)
1704         }
1705
1706         /// Gets a signed HTLC transaction given a preimage (for !htlc.offered) and the holder HTLC transaction signature.
1707         pub(crate) fn get_signed_htlc_tx(&self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature, preimage: &Option<PaymentPreimage>) -> Transaction {
1708                 let inner = self.inner;
1709                 let keys = &inner.keys;
1710                 let txid = inner.built.txid;
1711                 let this_htlc = &inner.htlcs[htlc_index];
1712                 assert!(this_htlc.transaction_output_index.is_some());
1713                 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
1714                 if !this_htlc.offered && preimage.is_none() { unreachable!(); }
1715                 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
1716                 if  this_htlc.offered && preimage.is_some() { unreachable!(); }
1717
1718                 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);
1719
1720                 let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc, &self.channel_type_features, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key);
1721
1722                 htlc_tx.input[0].witness = chan_utils::build_htlc_input_witness(
1723                         signature, counterparty_signature, preimage, &htlc_redeemscript, &self.channel_type_features,
1724                 );
1725                 htlc_tx
1726         }
1727 }
1728
1729 /// Commitment transaction numbers which appear in the transactions themselves are XOR'd with a
1730 /// shared secret first. This prevents on-chain observers from discovering how many commitment
1731 /// transactions occurred in a channel before it was closed.
1732 ///
1733 /// This function gets the shared secret from relevant channel public keys and can be used to
1734 /// "decrypt" the commitment transaction number given a commitment transaction on-chain.
1735 pub fn get_commitment_transaction_number_obscure_factor(
1736         broadcaster_payment_basepoint: &PublicKey,
1737         countersignatory_payment_basepoint: &PublicKey,
1738         outbound_from_broadcaster: bool,
1739 ) -> u64 {
1740         let mut sha = Sha256::engine();
1741
1742         if outbound_from_broadcaster {
1743                 sha.input(&broadcaster_payment_basepoint.serialize());
1744                 sha.input(&countersignatory_payment_basepoint.serialize());
1745         } else {
1746                 sha.input(&countersignatory_payment_basepoint.serialize());
1747                 sha.input(&broadcaster_payment_basepoint.serialize());
1748         }
1749         let res = Sha256::from_engine(sha).into_inner();
1750
1751         ((res[26] as u64) << 5 * 8)
1752                 | ((res[27] as u64) << 4 * 8)
1753                 | ((res[28] as u64) << 3 * 8)
1754                 | ((res[29] as u64) << 2 * 8)
1755                 | ((res[30] as u64) << 1 * 8)
1756                 | ((res[31] as u64) << 0 * 8)
1757 }
1758
1759 #[cfg(test)]
1760 mod tests {
1761         use super::CounterpartyCommitmentSecrets;
1762         use crate::{hex, chain};
1763         use crate::prelude::*;
1764         use crate::ln::chan_utils::{get_htlc_redeemscript, get_to_countersignatory_with_anchors_redeemscript, CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
1765         use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
1766         use crate::util::test_utils;
1767         use crate::sign::{ChannelSigner, SignerProvider};
1768         use bitcoin::{Network, Txid};
1769         use bitcoin::hashes::Hash;
1770         use crate::ln::PaymentHash;
1771         use bitcoin::hashes::hex::ToHex;
1772         use bitcoin::util::address::Payload;
1773         use bitcoin::PublicKey as BitcoinPublicKey;
1774         use crate::ln::features::ChannelTypeFeatures;
1775
1776         #[test]
1777         fn test_anchors() {
1778                 let secp_ctx = Secp256k1::new();
1779
1780                 let seed = [42; 32];
1781                 let network = Network::Testnet;
1782                 let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
1783                 let signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(false, 1_000_000, 0));
1784                 let counterparty_signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(true, 1_000_000, 1));
1785                 let delayed_payment_base = &signer.pubkeys().delayed_payment_basepoint;
1786                 let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
1787                 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
1788                 let htlc_basepoint = &signer.pubkeys().htlc_basepoint;
1789                 let holder_pubkeys = signer.pubkeys();
1790                 let counterparty_pubkeys = counterparty_signer.pubkeys();
1791                 let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint);
1792                 let mut channel_parameters = ChannelTransactionParameters {
1793                         holder_pubkeys: holder_pubkeys.clone(),
1794                         holder_selected_contest_delay: 0,
1795                         is_outbound_from_holder: false,
1796                         counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: counterparty_pubkeys.clone(), selected_contest_delay: 0 }),
1797                         funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1798                         channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
1799                 };
1800
1801                 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
1802
1803                 // Generate broadcaster and counterparty outputs
1804                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1805                         0, 1000, 2000,
1806                         holder_pubkeys.funding_pubkey,
1807                         counterparty_pubkeys.funding_pubkey,
1808                         keys.clone(), 1,
1809                         &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1810                 );
1811                 assert_eq!(tx.built.transaction.output.len(), 2);
1812                 assert_eq!(tx.built.transaction.output[1].script_pubkey, Payload::p2wpkh(&BitcoinPublicKey::new(counterparty_pubkeys.payment_point)).unwrap().script_pubkey());
1813
1814                 // Generate broadcaster and counterparty outputs as well as two anchors
1815                 channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
1816                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1817                         0, 1000, 2000,
1818                         holder_pubkeys.funding_pubkey,
1819                         counterparty_pubkeys.funding_pubkey,
1820                         keys.clone(), 1,
1821                         &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1822                 );
1823                 assert_eq!(tx.built.transaction.output.len(), 4);
1824                 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_to_countersignatory_with_anchors_redeemscript(&counterparty_pubkeys.payment_point).to_v0_p2wsh());
1825
1826                 // Generate broadcaster output and anchor
1827                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1828                         0, 3000, 0,
1829                         holder_pubkeys.funding_pubkey,
1830                         counterparty_pubkeys.funding_pubkey,
1831                         keys.clone(), 1,
1832                         &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1833                 );
1834                 assert_eq!(tx.built.transaction.output.len(), 2);
1835
1836                 // Generate counterparty output and anchor
1837                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1838                         0, 0, 3000,
1839                         holder_pubkeys.funding_pubkey,
1840                         counterparty_pubkeys.funding_pubkey,
1841                         keys.clone(), 1,
1842                         &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1843                 );
1844                 assert_eq!(tx.built.transaction.output.len(), 2);
1845
1846                 let received_htlc = HTLCOutputInCommitment {
1847                         offered: false,
1848                         amount_msat: 400000,
1849                         cltv_expiry: 100,
1850                         payment_hash: PaymentHash([42; 32]),
1851                         transaction_output_index: None,
1852                 };
1853
1854                 let offered_htlc = HTLCOutputInCommitment {
1855                         offered: true,
1856                         amount_msat: 600000,
1857                         cltv_expiry: 100,
1858                         payment_hash: PaymentHash([43; 32]),
1859                         transaction_output_index: None,
1860                 };
1861
1862                 // Generate broadcaster output and received and offered HTLC outputs,  w/o anchors
1863                 channel_parameters.channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1864                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1865                         0, 3000, 0,
1866                         holder_pubkeys.funding_pubkey,
1867                         counterparty_pubkeys.funding_pubkey,
1868                         keys.clone(), 1,
1869                         &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1870                         &channel_parameters.as_holder_broadcastable()
1871                 );
1872                 assert_eq!(tx.built.transaction.output.len(), 3);
1873                 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh());
1874                 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh());
1875                 assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh().to_hex(),
1876                                    "0020e43a7c068553003fe68fcae424fb7b28ec5ce48cd8b6744b3945631389bad2fb");
1877                 assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh().to_hex(),
1878                                    "0020215d61bba56b19e9eadb6107f5a85d7f99c40f65992443f69229c290165bc00d");
1879
1880                 // Generate broadcaster output and received and offered HTLC outputs,  with anchors
1881                 channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
1882                 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1883                         0, 3000, 0,
1884                         holder_pubkeys.funding_pubkey,
1885                         counterparty_pubkeys.funding_pubkey,
1886                         keys.clone(), 1,
1887                         &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1888                         &channel_parameters.as_holder_broadcastable()
1889                 );
1890                 assert_eq!(tx.built.transaction.output.len(), 5);
1891                 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());
1892                 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());
1893                 assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_v0_p2wsh().to_hex(),
1894                                    "0020b70d0649c72b38756885c7a30908d912a7898dd5d79457a7280b8e9a20f3f2bc");
1895                 assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_v0_p2wsh().to_hex(),
1896                                    "002087a3faeb1950a469c0e2db4a79b093a41b9526e5a6fc6ef5cb949bde3be379c7");
1897         }
1898
1899         #[test]
1900         fn test_per_commitment_storage() {
1901                 // Test vectors from BOLT 3:
1902                 let mut secrets: Vec<[u8; 32]> = Vec::new();
1903                 let mut monitor;
1904
1905                 macro_rules! test_secrets {
1906                         () => {
1907                                 let mut idx = 281474976710655;
1908                                 for secret in secrets.iter() {
1909                                         assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1910                                         idx -= 1;
1911                                 }
1912                                 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1913                                 assert!(monitor.get_secret(idx).is_none());
1914                         };
1915                 }
1916
1917                 {
1918                         // insert_secret correct sequence
1919                         monitor = CounterpartyCommitmentSecrets::new();
1920                         secrets.clear();
1921
1922                         secrets.push([0; 32]);
1923                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1924                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1925                         test_secrets!();
1926
1927                         secrets.push([0; 32]);
1928                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1929                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1930                         test_secrets!();
1931
1932                         secrets.push([0; 32]);
1933                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1934                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1935                         test_secrets!();
1936
1937                         secrets.push([0; 32]);
1938                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1939                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1940                         test_secrets!();
1941
1942                         secrets.push([0; 32]);
1943                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1944                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1945                         test_secrets!();
1946
1947                         secrets.push([0; 32]);
1948                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1949                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1950                         test_secrets!();
1951
1952                         secrets.push([0; 32]);
1953                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1954                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1955                         test_secrets!();
1956
1957                         secrets.push([0; 32]);
1958                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1959                         monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
1960                         test_secrets!();
1961                 }
1962
1963                 {
1964                         // insert_secret #1 incorrect
1965                         monitor = CounterpartyCommitmentSecrets::new();
1966                         secrets.clear();
1967
1968                         secrets.push([0; 32]);
1969                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1970                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1971                         test_secrets!();
1972
1973                         secrets.push([0; 32]);
1974                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1975                         assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
1976                 }
1977
1978                 {
1979                         // insert_secret #2 incorrect (#1 derived from incorrect)
1980                         monitor = CounterpartyCommitmentSecrets::new();
1981                         secrets.clear();
1982
1983                         secrets.push([0; 32]);
1984                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1985                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1986                         test_secrets!();
1987
1988                         secrets.push([0; 32]);
1989                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1990                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1991                         test_secrets!();
1992
1993                         secrets.push([0; 32]);
1994                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1995                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1996                         test_secrets!();
1997
1998                         secrets.push([0; 32]);
1999                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2000                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
2001                 }
2002
2003                 {
2004                         // insert_secret #3 incorrect
2005                         monitor = CounterpartyCommitmentSecrets::new();
2006                         secrets.clear();
2007
2008                         secrets.push([0; 32]);
2009                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2010                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2011                         test_secrets!();
2012
2013                         secrets.push([0; 32]);
2014                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2015                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2016                         test_secrets!();
2017
2018                         secrets.push([0; 32]);
2019                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2020                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2021                         test_secrets!();
2022
2023                         secrets.push([0; 32]);
2024                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2025                         assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
2026                 }
2027
2028                 {
2029                         // insert_secret #4 incorrect (1,2,3 derived from incorrect)
2030                         monitor = CounterpartyCommitmentSecrets::new();
2031                         secrets.clear();
2032
2033                         secrets.push([0; 32]);
2034                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2035                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2036                         test_secrets!();
2037
2038                         secrets.push([0; 32]);
2039                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2040                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2041                         test_secrets!();
2042
2043                         secrets.push([0; 32]);
2044                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2045                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2046                         test_secrets!();
2047
2048                         secrets.push([0; 32]);
2049                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
2050                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2051                         test_secrets!();
2052
2053                         secrets.push([0; 32]);
2054                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2055                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2056                         test_secrets!();
2057
2058                         secrets.push([0; 32]);
2059                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2060                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2061                         test_secrets!();
2062
2063                         secrets.push([0; 32]);
2064                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2065                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2066                         test_secrets!();
2067
2068                         secrets.push([0; 32]);
2069                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2070                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2071                 }
2072
2073                 {
2074                         // insert_secret #5 incorrect
2075                         monitor = CounterpartyCommitmentSecrets::new();
2076                         secrets.clear();
2077
2078                         secrets.push([0; 32]);
2079                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2080                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2081                         test_secrets!();
2082
2083                         secrets.push([0; 32]);
2084                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2085                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2086                         test_secrets!();
2087
2088                         secrets.push([0; 32]);
2089                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2090                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2091                         test_secrets!();
2092
2093                         secrets.push([0; 32]);
2094                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2095                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2096                         test_secrets!();
2097
2098                         secrets.push([0; 32]);
2099                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2100                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2101                         test_secrets!();
2102
2103                         secrets.push([0; 32]);
2104                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2105                         assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
2106                 }
2107
2108                 {
2109                         // insert_secret #6 incorrect (5 derived from incorrect)
2110                         monitor = CounterpartyCommitmentSecrets::new();
2111                         secrets.clear();
2112
2113                         secrets.push([0; 32]);
2114                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2115                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2116                         test_secrets!();
2117
2118                         secrets.push([0; 32]);
2119                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2120                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2121                         test_secrets!();
2122
2123                         secrets.push([0; 32]);
2124                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2125                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2126                         test_secrets!();
2127
2128                         secrets.push([0; 32]);
2129                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2130                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2131                         test_secrets!();
2132
2133                         secrets.push([0; 32]);
2134                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2135                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2136                         test_secrets!();
2137
2138                         secrets.push([0; 32]);
2139                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
2140                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2141                         test_secrets!();
2142
2143                         secrets.push([0; 32]);
2144                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2145                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2146                         test_secrets!();
2147
2148                         secrets.push([0; 32]);
2149                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2150                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2151                 }
2152
2153                 {
2154                         // insert_secret #7 incorrect
2155                         monitor = CounterpartyCommitmentSecrets::new();
2156                         secrets.clear();
2157
2158                         secrets.push([0; 32]);
2159                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2160                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2161                         test_secrets!();
2162
2163                         secrets.push([0; 32]);
2164                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2165                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2166                         test_secrets!();
2167
2168                         secrets.push([0; 32]);
2169                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2170                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2171                         test_secrets!();
2172
2173                         secrets.push([0; 32]);
2174                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2175                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2176                         test_secrets!();
2177
2178                         secrets.push([0; 32]);
2179                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2180                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2181                         test_secrets!();
2182
2183                         secrets.push([0; 32]);
2184                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2185                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2186                         test_secrets!();
2187
2188                         secrets.push([0; 32]);
2189                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2190                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2191                         test_secrets!();
2192
2193                         secrets.push([0; 32]);
2194                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2195                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2196                 }
2197
2198                 {
2199                         // insert_secret #8 incorrect
2200                         monitor = CounterpartyCommitmentSecrets::new();
2201                         secrets.clear();
2202
2203                         secrets.push([0; 32]);
2204                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2205                         monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2206                         test_secrets!();
2207
2208                         secrets.push([0; 32]);
2209                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2210                         monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2211                         test_secrets!();
2212
2213                         secrets.push([0; 32]);
2214                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2215                         monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2216                         test_secrets!();
2217
2218                         secrets.push([0; 32]);
2219                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2220                         monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2221                         test_secrets!();
2222
2223                         secrets.push([0; 32]);
2224                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2225                         monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2226                         test_secrets!();
2227
2228                         secrets.push([0; 32]);
2229                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2230                         monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2231                         test_secrets!();
2232
2233                         secrets.push([0; 32]);
2234                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2235                         monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2236                         test_secrets!();
2237
2238                         secrets.push([0; 32]);
2239                         secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2240                         assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2241                 }
2242         }
2243 }