1 // This file is Copyright its original authors, visible in version control
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
10 //! Various utilities for building scripts and deriving keys related to channels. These are
11 //! largely of interest for those implementing chain::keysinterface::Sign message signing by hand.
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;
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};
24 use crate::ln::{PaymentHash, PaymentPreimage};
25 use crate::ln::msgs::DecodeError;
26 use crate::util::ser::{Readable, Writeable, Writer};
27 use crate::util::{byte_utils, transaction_utils};
29 use bitcoin::secp256k1::{SecretKey, PublicKey, Scalar};
30 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature, Message};
31 use bitcoin::secp256k1::Error as SecpError;
32 use bitcoin::{PackedLockTime, secp256k1, Sequence, Witness};
33 use bitcoin::PublicKey as BitcoinPublicKey;
36 use crate::prelude::*;
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};
43 use crate::util::crypto::sign;
45 /// Maximum number of one-way in-flight HTLC (protocol-level value).
46 pub const MAX_HTLCS: u16 = 483;
47 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, non-anchor variant.
48 pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
49 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, anchor variant.
50 pub const OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS: usize = 136;
52 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
53 /// We define a range that encompasses both its non-anchors and anchors variants.
54 pub(crate) const MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 136;
55 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
56 /// We define a range that encompasses both its non-anchors and anchors variants.
57 /// This is the maximum post-anchor value.
58 pub const MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 143;
60 /// Gets the weight for an HTLC-Success transaction.
62 pub fn htlc_success_tx_weight(opt_anchors: bool) -> u64 {
63 const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
64 const HTLC_SUCCESS_ANCHOR_TX_WEIGHT: u64 = 706;
65 if opt_anchors { HTLC_SUCCESS_ANCHOR_TX_WEIGHT } else { HTLC_SUCCESS_TX_WEIGHT }
68 /// Gets the weight for an HTLC-Timeout transaction.
70 pub fn htlc_timeout_tx_weight(opt_anchors: bool) -> u64 {
71 const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
72 const HTLC_TIMEOUT_ANCHOR_TX_WEIGHT: u64 = 666;
73 if opt_anchors { HTLC_TIMEOUT_ANCHOR_TX_WEIGHT } else { HTLC_TIMEOUT_TX_WEIGHT }
76 /// Describes the type of HTLC claim as determined by analyzing the witness.
77 #[derive(PartialEq, Eq)]
79 /// Claims an offered output on a commitment transaction through the timeout path.
81 /// Claims an offered output on a commitment transaction through the success path.
83 /// Claims an accepted output on a commitment transaction through the timeout path.
85 /// Claims an accepted output on a commitment transaction through the success path.
87 /// Claims an offered/accepted output on a commitment transaction through the revocation path.
92 /// Check if a given input witness attempts to claim a HTLC.
93 pub fn from_witness(witness: &Witness) -> Option<Self> {
94 debug_assert_eq!(OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS, MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT);
95 if witness.len() < 2 {
98 let witness_script = witness.last().unwrap();
99 let second_to_last = witness.second_to_last().unwrap();
100 if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT {
101 if witness.len() == 3 && second_to_last.len() == 33 {
102 // <revocation sig> <revocationpubkey> <witness_script>
103 Some(Self::Revocation)
104 } else if witness.len() == 3 && second_to_last.len() == 32 {
105 // <remotehtlcsig> <payment_preimage> <witness_script>
106 Some(Self::OfferedPreimage)
107 } else if witness.len() == 5 && second_to_last.len() == 0 {
108 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
109 Some(Self::OfferedTimeout)
113 } else if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS {
114 // It's possible for the weight of `offered_htlc_script` and `accepted_htlc_script` to
115 // match so we check for both here.
116 if witness.len() == 3 && second_to_last.len() == 33 {
117 // <revocation sig> <revocationpubkey> <witness_script>
118 Some(Self::Revocation)
119 } else if witness.len() == 3 && second_to_last.len() == 32 {
120 // <remotehtlcsig> <payment_preimage> <witness_script>
121 Some(Self::OfferedPreimage)
122 } else if witness.len() == 5 && second_to_last.len() == 0 {
123 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
124 Some(Self::OfferedTimeout)
125 } else if witness.len() == 3 && second_to_last.len() == 0 {
126 // <remotehtlcsig> <> <witness_script>
127 Some(Self::AcceptedTimeout)
128 } else if witness.len() == 5 && second_to_last.len() == 32 {
129 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
130 Some(Self::AcceptedPreimage)
134 } else if witness_script.len() > MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT &&
135 witness_script.len() <= MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT {
136 // Handle remaining range of ACCEPTED_HTLC_SCRIPT_WEIGHT.
137 if witness.len() == 3 && second_to_last.len() == 33 {
138 // <revocation sig> <revocationpubkey> <witness_script>
139 Some(Self::Revocation)
140 } else if witness.len() == 3 && second_to_last.len() == 0 {
141 // <remotehtlcsig> <> <witness_script>
142 Some(Self::AcceptedTimeout)
143 } else if witness.len() == 5 && second_to_last.len() == 32 {
144 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
145 Some(Self::AcceptedPreimage)
155 // Various functions for key derivation and transaction creation for use within channels. Primarily
156 // used in Channel and ChannelMonitor.
158 /// Build the commitment secret from the seed and the commitment number
159 pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
160 let mut res: [u8; 32] = commitment_seed.clone();
163 if idx & (1 << bitpos) == (1 << bitpos) {
164 res[bitpos / 8] ^= 1 << (bitpos & 7);
165 res = Sha256::hash(&res).into_inner();
171 /// Build a closing transaction
172 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 {
174 let mut ins: Vec<TxIn> = Vec::new();
176 previous_output: funding_outpoint,
177 script_sig: Script::new(),
178 sequence: Sequence::MAX,
179 witness: Witness::new(),
184 let mut txouts: Vec<(TxOut, ())> = Vec::new();
186 if to_counterparty_value_sat > 0 {
188 script_pubkey: to_counterparty_script,
189 value: to_counterparty_value_sat
193 if to_holder_value_sat > 0 {
195 script_pubkey: to_holder_script,
196 value: to_holder_value_sat
200 transaction_utils::sort_outputs(&mut txouts, |_, _| { cmp::Ordering::Equal }); // Ordering doesnt matter if they used our pubkey...
202 let mut outputs: Vec<TxOut> = Vec::new();
203 for out in txouts.drain(..) {
209 lock_time: PackedLockTime::ZERO,
215 /// Implements the per-commitment secret storage scheme from
216 /// [BOLT 3](https://github.com/lightning/bolts/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
218 /// Allows us to keep track of all of the revocation secrets of our counterparty in just 50*32 bytes
221 pub struct CounterpartyCommitmentSecrets {
222 old_secrets: [([u8; 32], u64); 49],
225 impl Eq for CounterpartyCommitmentSecrets {}
226 impl PartialEq for CounterpartyCommitmentSecrets {
227 fn eq(&self, other: &Self) -> bool {
228 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
229 if secret != o_secret || idx != o_idx {
237 impl CounterpartyCommitmentSecrets {
238 /// Creates a new empty `CounterpartyCommitmentSecrets` structure.
239 pub fn new() -> Self {
240 Self { old_secrets: [([0; 32], 1 << 48); 49], }
244 fn place_secret(idx: u64) -> u8 {
246 if idx & (1 << i) == (1 << i) {
253 /// Returns the minimum index of all stored secrets. Note that indexes start
254 /// at 1 << 48 and get decremented by one for each new secret.
255 pub fn get_min_seen_secret(&self) -> u64 {
256 //TODO This can be optimized?
257 let mut min = 1 << 48;
258 for &(_, idx) in self.old_secrets.iter() {
267 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
268 let mut res: [u8; 32] = secret;
270 let bitpos = bits - 1 - i;
271 if idx & (1 << bitpos) == (1 << bitpos) {
272 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
273 res = Sha256::hash(&res).into_inner();
279 /// Inserts the `secret` at `idx`. Returns `Ok(())` if the secret
280 /// was generated in accordance with BOLT 3 and is consistent with previous secrets.
281 pub fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
282 let pos = Self::place_secret(idx);
284 let (old_secret, old_idx) = self.old_secrets[i as usize];
285 if Self::derive_secret(secret, pos, old_idx) != old_secret {
289 if self.get_min_seen_secret() <= idx {
292 self.old_secrets[pos as usize] = (secret, idx);
296 /// Returns the secret at `idx`.
297 /// Returns `None` if `idx` is < [`CounterpartyCommitmentSecrets::get_min_seen_secret`].
298 pub fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
299 for i in 0..self.old_secrets.len() {
300 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
301 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
304 assert!(idx < self.get_min_seen_secret());
309 impl Writeable for CounterpartyCommitmentSecrets {
310 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
311 for &(ref secret, ref idx) in self.old_secrets.iter() {
312 writer.write_all(secret)?;
313 writer.write_all(&byte_utils::be64_to_array(*idx))?;
315 write_tlv_fields!(writer, {});
319 impl Readable for CounterpartyCommitmentSecrets {
320 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
321 let mut old_secrets = [([0; 32], 1 << 48); 49];
322 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
323 *secret = Readable::read(reader)?;
324 *idx = Readable::read(reader)?;
326 read_tlv_fields!(reader, {});
327 Ok(Self { old_secrets })
331 /// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
332 /// from the base secret and the per_commitment_point.
334 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
335 /// generated (ie our own).
336 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> Result<SecretKey, SecpError> {
337 let mut sha = Sha256::engine();
338 sha.input(&per_commitment_point.serialize());
339 sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
340 let res = Sha256::from_engine(sha).into_inner();
342 base_secret.clone().add_tweak(&Scalar::from_be_bytes(res).unwrap())
345 /// Derives a per-commitment-transaction public key (eg an htlc key or a delayed_payment key)
346 /// from the base point and the per_commitment_key. This is the public equivalent of
347 /// derive_private_key - using only public keys to derive a public key instead of private keys.
349 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
350 /// generated (ie our own).
351 pub fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> Result<PublicKey, SecpError> {
352 let mut sha = Sha256::engine();
353 sha.input(&per_commitment_point.serialize());
354 sha.input(&base_point.serialize());
355 let res = Sha256::from_engine(sha).into_inner();
357 let hashkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&res)?);
358 base_point.combine(&hashkey)
361 /// Derives a per-commitment-transaction revocation key from its constituent parts.
363 /// Only the cheating participant owns a valid witness to propagate a revoked
364 /// commitment transaction, thus per_commitment_secret always come from cheater
365 /// and revocation_base_secret always come from punisher, which is the broadcaster
366 /// of the transaction spending with this key knowledge.
368 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
369 /// generated (ie our own).
370 pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_secret: &SecretKey, countersignatory_revocation_base_secret: &SecretKey) -> Result<SecretKey, SecpError> {
371 let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
372 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
374 let rev_append_commit_hash_key = {
375 let mut sha = Sha256::engine();
376 sha.input(&countersignatory_revocation_base_point.serialize());
377 sha.input(&per_commitment_point.serialize());
379 Sha256::from_engine(sha).into_inner()
381 let commit_append_rev_hash_key = {
382 let mut sha = Sha256::engine();
383 sha.input(&per_commitment_point.serialize());
384 sha.input(&countersignatory_revocation_base_point.serialize());
386 Sha256::from_engine(sha).into_inner()
389 let countersignatory_contrib = countersignatory_revocation_base_secret.clone().mul_tweak(&Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())?;
390 let broadcaster_contrib = per_commitment_secret.clone().mul_tweak(&Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())?;
391 countersignatory_contrib.add_tweak(&Scalar::from_be_bytes(broadcaster_contrib.secret_bytes()).unwrap())
394 /// Derives a per-commitment-transaction revocation public key from its constituent parts. This is
395 /// the public equivalend of derive_private_revocation_key - using only public keys to derive a
396 /// public key instead of private keys.
398 /// Only the cheating participant owns a valid witness to propagate a revoked
399 /// commitment transaction, thus per_commitment_point always come from cheater
400 /// and revocation_base_point always come from punisher, which is the broadcaster
401 /// of the transaction spending with this key knowledge.
403 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
404 /// generated (ie our own).
405 pub fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, countersignatory_revocation_base_point: &PublicKey) -> Result<PublicKey, SecpError> {
406 let rev_append_commit_hash_key = {
407 let mut sha = Sha256::engine();
408 sha.input(&countersignatory_revocation_base_point.serialize());
409 sha.input(&per_commitment_point.serialize());
411 Sha256::from_engine(sha).into_inner()
413 let commit_append_rev_hash_key = {
414 let mut sha = Sha256::engine();
415 sha.input(&per_commitment_point.serialize());
416 sha.input(&countersignatory_revocation_base_point.serialize());
418 Sha256::from_engine(sha).into_inner()
421 let countersignatory_contrib = countersignatory_revocation_base_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())?;
422 let broadcaster_contrib = per_commitment_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())?;
423 countersignatory_contrib.combine(&broadcaster_contrib)
426 /// The set of public keys which are used in the creation of one commitment transaction.
427 /// These are derived from the channel base keys and per-commitment data.
429 /// A broadcaster key is provided from potential broadcaster of the computed transaction.
430 /// A countersignatory key is coming from a protocol participant unable to broadcast the
433 /// These keys are assumed to be good, either because the code derived them from
434 /// channel basepoints via the new function, or they were obtained via
435 /// CommitmentTransaction.trust().keys() because we trusted the source of the
436 /// pre-calculated keys.
437 #[derive(PartialEq, Eq, Clone)]
438 pub struct TxCreationKeys {
439 /// The broadcaster's per-commitment public key which was used to derive the other keys.
440 pub per_commitment_point: PublicKey,
441 /// The revocation key which is used to allow the broadcaster of the commitment
442 /// transaction to provide their counterparty the ability to punish them if they broadcast
444 pub revocation_key: PublicKey,
445 /// Broadcaster's HTLC Key
446 pub broadcaster_htlc_key: PublicKey,
447 /// Countersignatory's HTLC Key
448 pub countersignatory_htlc_key: PublicKey,
449 /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
450 pub broadcaster_delayed_payment_key: PublicKey,
453 impl_writeable_tlv_based!(TxCreationKeys, {
454 (0, per_commitment_point, required),
455 (2, revocation_key, required),
456 (4, broadcaster_htlc_key, required),
457 (6, countersignatory_htlc_key, required),
458 (8, broadcaster_delayed_payment_key, required),
461 /// One counterparty's public keys which do not change over the life of a channel.
462 #[derive(Clone, PartialEq, Eq)]
463 pub struct ChannelPublicKeys {
464 /// The public key which is used to sign all commitment transactions, as it appears in the
465 /// on-chain channel lock-in 2-of-2 multisig output.
466 pub funding_pubkey: PublicKey,
467 /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
468 /// revocation keys. This is combined with the per-commitment-secret generated by the
469 /// counterparty to create a secret which the counterparty can reveal to revoke previous
471 pub revocation_basepoint: PublicKey,
472 /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
473 /// spendable primary channel balance on the broadcaster's commitment transaction. This key is
474 /// static across every commitment transaction.
475 pub payment_point: PublicKey,
476 /// The base point which is used (with derive_public_key) to derive a per-commitment payment
477 /// public key which receives non-HTLC-encumbered funds which are only available for spending
478 /// after some delay (or can be claimed via the revocation path).
479 pub delayed_payment_basepoint: PublicKey,
480 /// The base point which is used (with derive_public_key) to derive a per-commitment public key
481 /// which is used to encumber HTLC-in-flight outputs.
482 pub htlc_basepoint: PublicKey,
485 impl_writeable_tlv_based!(ChannelPublicKeys, {
486 (0, funding_pubkey, required),
487 (2, revocation_basepoint, required),
488 (4, payment_point, required),
489 (6, delayed_payment_basepoint, required),
490 (8, htlc_basepoint, required),
493 impl TxCreationKeys {
494 /// Create per-state keys from channel base points and the per-commitment point.
495 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
496 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) -> Result<TxCreationKeys, SecpError> {
498 per_commitment_point: per_commitment_point.clone(),
499 revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &countersignatory_revocation_base)?,
500 broadcaster_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_htlc_base)?,
501 countersignatory_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &countersignatory_htlc_base)?,
502 broadcaster_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_delayed_payment_base)?,
506 /// Generate per-state keys from channel static keys.
507 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
508 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>) -> Result<TxCreationKeys, SecpError> {
509 TxCreationKeys::derive_new(
511 &per_commitment_point,
512 &broadcaster_keys.delayed_payment_basepoint,
513 &broadcaster_keys.htlc_basepoint,
514 &countersignatory_keys.revocation_basepoint,
515 &countersignatory_keys.htlc_basepoint,
520 /// The maximum length of a script returned by get_revokeable_redeemscript.
521 // Calculated as 6 bytes of opcodes, 1 byte push plus 2 bytes for contest_delay, and two public
522 // keys of 33 bytes (+ 1 push).
523 pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 3 + 34*2;
525 /// A script either spendable by the revocation
526 /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
527 /// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
528 pub fn get_revokeable_redeemscript(revocation_key: &PublicKey, contest_delay: u16, broadcaster_delayed_payment_key: &PublicKey) -> Script {
529 let res = Builder::new().push_opcode(opcodes::all::OP_IF)
530 .push_slice(&revocation_key.serialize())
531 .push_opcode(opcodes::all::OP_ELSE)
532 .push_int(contest_delay as i64)
533 .push_opcode(opcodes::all::OP_CSV)
534 .push_opcode(opcodes::all::OP_DROP)
535 .push_slice(&broadcaster_delayed_payment_key.serialize())
536 .push_opcode(opcodes::all::OP_ENDIF)
537 .push_opcode(opcodes::all::OP_CHECKSIG)
539 debug_assert!(res.len() <= REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH);
543 /// Information about an HTLC as it appears in a commitment transaction
544 #[derive(Clone, Debug, PartialEq, Eq)]
545 pub struct HTLCOutputInCommitment {
546 /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
547 /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
548 /// need to compare this value to whether the commitment transaction in question is that of
549 /// the counterparty or our own.
551 /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
552 /// this divided by 1000.
553 pub amount_msat: u64,
554 /// The CLTV lock-time at which this HTLC expires.
555 pub cltv_expiry: u32,
556 /// The hash of the preimage which unlocks this HTLC.
557 pub payment_hash: PaymentHash,
558 /// The position within the commitment transactions' outputs. This may be None if the value is
559 /// below the dust limit (in which case no output appears in the commitment transaction and the
560 /// value is spent to additional transaction fees).
561 pub transaction_output_index: Option<u32>,
564 impl_writeable_tlv_based!(HTLCOutputInCommitment, {
565 (0, offered, required),
566 (2, amount_msat, required),
567 (4, cltv_expiry, required),
568 (6, payment_hash, required),
569 (8, transaction_output_index, option),
573 pub(crate) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, opt_anchors: bool, broadcaster_htlc_key: &PublicKey, countersignatory_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
574 let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
576 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
577 .push_opcode(opcodes::all::OP_HASH160)
578 .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
579 .push_opcode(opcodes::all::OP_EQUAL)
580 .push_opcode(opcodes::all::OP_IF)
581 .push_opcode(opcodes::all::OP_CHECKSIG)
582 .push_opcode(opcodes::all::OP_ELSE)
583 .push_slice(&countersignatory_htlc_key.serialize()[..])
584 .push_opcode(opcodes::all::OP_SWAP)
585 .push_opcode(opcodes::all::OP_SIZE)
587 .push_opcode(opcodes::all::OP_EQUAL)
588 .push_opcode(opcodes::all::OP_NOTIF)
589 .push_opcode(opcodes::all::OP_DROP)
591 .push_opcode(opcodes::all::OP_SWAP)
592 .push_slice(&broadcaster_htlc_key.serialize()[..])
594 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
595 .push_opcode(opcodes::all::OP_ELSE)
596 .push_opcode(opcodes::all::OP_HASH160)
597 .push_slice(&payment_hash160)
598 .push_opcode(opcodes::all::OP_EQUALVERIFY)
599 .push_opcode(opcodes::all::OP_CHECKSIG)
600 .push_opcode(opcodes::all::OP_ENDIF);
602 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
603 .push_opcode(opcodes::all::OP_CSV)
604 .push_opcode(opcodes::all::OP_DROP);
606 bldr.push_opcode(opcodes::all::OP_ENDIF)
609 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
610 .push_opcode(opcodes::all::OP_HASH160)
611 .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
612 .push_opcode(opcodes::all::OP_EQUAL)
613 .push_opcode(opcodes::all::OP_IF)
614 .push_opcode(opcodes::all::OP_CHECKSIG)
615 .push_opcode(opcodes::all::OP_ELSE)
616 .push_slice(&countersignatory_htlc_key.serialize()[..])
617 .push_opcode(opcodes::all::OP_SWAP)
618 .push_opcode(opcodes::all::OP_SIZE)
620 .push_opcode(opcodes::all::OP_EQUAL)
621 .push_opcode(opcodes::all::OP_IF)
622 .push_opcode(opcodes::all::OP_HASH160)
623 .push_slice(&payment_hash160)
624 .push_opcode(opcodes::all::OP_EQUALVERIFY)
626 .push_opcode(opcodes::all::OP_SWAP)
627 .push_slice(&broadcaster_htlc_key.serialize()[..])
629 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
630 .push_opcode(opcodes::all::OP_ELSE)
631 .push_opcode(opcodes::all::OP_DROP)
632 .push_int(htlc.cltv_expiry as i64)
633 .push_opcode(opcodes::all::OP_CLTV)
634 .push_opcode(opcodes::all::OP_DROP)
635 .push_opcode(opcodes::all::OP_CHECKSIG)
636 .push_opcode(opcodes::all::OP_ENDIF);
638 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
639 .push_opcode(opcodes::all::OP_CSV)
640 .push_opcode(opcodes::all::OP_DROP);
642 bldr.push_opcode(opcodes::all::OP_ENDIF)
647 /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
648 /// does not need to have its previous_output_index filled.
650 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, opt_anchors: bool, keys: &TxCreationKeys) -> Script {
651 get_htlc_redeemscript_with_explicit_keys(htlc, opt_anchors, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
654 /// Gets the redeemscript for a funding output from the two funding public keys.
655 /// Note that the order of funding public keys does not matter.
656 pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> Script {
657 let broadcaster_funding_key = broadcaster.serialize();
658 let countersignatory_funding_key = countersignatory.serialize();
660 let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
661 if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
662 builder.push_slice(&broadcaster_funding_key)
663 .push_slice(&countersignatory_funding_key)
665 builder.push_slice(&countersignatory_funding_key)
666 .push_slice(&broadcaster_funding_key)
667 }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
670 /// Builds an unsigned HTLC-Success or HTLC-Timeout transaction from the given channel and HTLC
671 /// parameters. This is used by [`TrustedCommitmentTransaction::get_htlc_sigs`] to fetch the
672 /// transaction which needs signing, and can be used to construct an HTLC transaction which is
673 /// broadcastable given a counterparty HTLC signature.
675 /// Panics if htlc.transaction_output_index.is_none() (as such HTLCs do not appear in the
676 /// commitment transaction).
677 pub fn build_htlc_transaction(commitment_txid: &Txid, feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, opt_anchors: bool, broadcaster_delayed_payment_key: &PublicKey, revocation_key: &PublicKey) -> Transaction {
678 let mut txins: Vec<TxIn> = Vec::new();
680 previous_output: OutPoint {
681 txid: commitment_txid.clone(),
682 vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
684 script_sig: Script::new(),
685 sequence: Sequence(if opt_anchors { 1 } else { 0 }),
686 witness: Witness::new(),
689 let weight = if htlc.offered {
690 htlc_timeout_tx_weight(opt_anchors)
692 htlc_success_tx_weight(opt_anchors)
694 let output_value = if opt_anchors {
695 htlc.amount_msat / 1000
697 let total_fee = feerate_per_kw as u64 * weight / 1000;
698 htlc.amount_msat / 1000 - total_fee
701 let mut txouts: Vec<TxOut> = Vec::new();
703 script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_v0_p2wsh(),
709 lock_time: PackedLockTime(if htlc.offered { htlc.cltv_expiry } else { 0 }),
715 /// Gets the witnessScript for the to_remote output when anchors are enabled.
717 pub fn get_to_countersignatory_with_anchors_redeemscript(payment_point: &PublicKey) -> Script {
719 .push_slice(&payment_point.serialize()[..])
720 .push_opcode(opcodes::all::OP_CHECKSIGVERIFY)
722 .push_opcode(opcodes::all::OP_CSV)
726 /// Gets the witnessScript for an anchor output from the funding public key.
727 /// The witness in the spending input must be:
728 /// <BIP 143 funding_signature>
729 /// After 16 blocks of confirmation, an alternative satisfying witness could be:
731 /// (empty vector required to satisfy compliance with MINIMALIF-standard rule)
733 pub fn get_anchor_redeemscript(funding_pubkey: &PublicKey) -> Script {
734 Builder::new().push_slice(&funding_pubkey.serialize()[..])
735 .push_opcode(opcodes::all::OP_CHECKSIG)
736 .push_opcode(opcodes::all::OP_IFDUP)
737 .push_opcode(opcodes::all::OP_NOTIF)
739 .push_opcode(opcodes::all::OP_CSV)
740 .push_opcode(opcodes::all::OP_ENDIF)
745 /// Locates the output with an anchor script paying to `funding_pubkey` within `commitment_tx`.
746 pub(crate) fn get_anchor_output<'a>(commitment_tx: &'a Transaction, funding_pubkey: &PublicKey) -> Option<(u32, &'a TxOut)> {
747 let anchor_script = chan_utils::get_anchor_redeemscript(funding_pubkey).to_v0_p2wsh();
748 commitment_tx.output.iter().enumerate()
749 .find(|(_, txout)| txout.script_pubkey == anchor_script)
750 .map(|(idx, txout)| (idx as u32, txout))
753 /// Returns the witness required to satisfy and spend an anchor input.
754 pub fn build_anchor_input_witness(funding_key: &PublicKey, funding_sig: &Signature) -> Witness {
755 let anchor_redeem_script = chan_utils::get_anchor_redeemscript(funding_key);
756 let mut funding_sig = funding_sig.serialize_der().to_vec();
757 funding_sig.push(EcdsaSighashType::All as u8);
758 Witness::from_vec(vec![funding_sig, anchor_redeem_script.to_bytes()])
761 /// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
762 /// The fields are organized by holder/counterparty.
764 /// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
765 /// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
767 pub struct ChannelTransactionParameters {
768 /// Holder public keys
769 pub holder_pubkeys: ChannelPublicKeys,
770 /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
771 pub holder_selected_contest_delay: u16,
772 /// Whether the holder is the initiator of this channel.
773 /// This is an input to the commitment number obscure factor computation.
774 pub is_outbound_from_holder: bool,
775 /// The late-bound counterparty channel transaction parameters.
776 /// These parameters are populated at the point in the protocol where the counterparty provides them.
777 pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
778 /// The late-bound funding outpoint
779 pub funding_outpoint: Option<chain::transaction::OutPoint>,
780 /// Are anchors (zero fee HTLC transaction variant) used for this channel. Boolean is
781 /// serialization backwards-compatible.
782 pub opt_anchors: Option<()>
785 /// Late-bound per-channel counterparty data used to build transactions.
787 pub struct CounterpartyChannelTransactionParameters {
788 /// Counter-party public keys
789 pub pubkeys: ChannelPublicKeys,
790 /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
791 pub selected_contest_delay: u16,
794 impl ChannelTransactionParameters {
795 /// Whether the late bound parameters are populated.
796 pub fn is_populated(&self) -> bool {
797 self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
800 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
801 /// given that the holder is the broadcaster.
803 /// self.is_populated() must be true before calling this function.
804 pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
805 assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
806 DirectedChannelTransactionParameters {
808 holder_is_broadcaster: true
812 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
813 /// given that the counterparty is the broadcaster.
815 /// self.is_populated() must be true before calling this function.
816 pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
817 assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
818 DirectedChannelTransactionParameters {
820 holder_is_broadcaster: false
825 impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, {
826 (0, pubkeys, required),
827 (2, selected_contest_delay, required),
830 impl_writeable_tlv_based!(ChannelTransactionParameters, {
831 (0, holder_pubkeys, required),
832 (2, holder_selected_contest_delay, required),
833 (4, is_outbound_from_holder, required),
834 (6, counterparty_parameters, option),
835 (8, funding_outpoint, option),
836 (10, opt_anchors, option),
839 /// Static channel fields used to build transactions given per-commitment fields, organized by
840 /// broadcaster/countersignatory.
842 /// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
843 /// as_holder_broadcastable and as_counterparty_broadcastable functions.
844 pub struct DirectedChannelTransactionParameters<'a> {
845 /// The holder's channel static parameters
846 inner: &'a ChannelTransactionParameters,
847 /// Whether the holder is the broadcaster
848 holder_is_broadcaster: bool,
851 impl<'a> DirectedChannelTransactionParameters<'a> {
852 /// Get the channel pubkeys for the broadcaster
853 pub fn broadcaster_pubkeys(&self) -> &ChannelPublicKeys {
854 if self.holder_is_broadcaster {
855 &self.inner.holder_pubkeys
857 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
861 /// Get the channel pubkeys for the countersignatory
862 pub fn countersignatory_pubkeys(&self) -> &ChannelPublicKeys {
863 if self.holder_is_broadcaster {
864 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
866 &self.inner.holder_pubkeys
870 /// Get the contest delay applicable to the transactions.
871 /// Note that the contest delay was selected by the countersignatory.
872 pub fn contest_delay(&self) -> u16 {
873 let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
874 if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
877 /// Whether the channel is outbound from the broadcaster.
879 /// The boolean representing the side that initiated the channel is
880 /// an input to the commitment number obscure factor computation.
881 pub fn is_outbound(&self) -> bool {
882 if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
885 /// The funding outpoint
886 pub fn funding_outpoint(&self) -> OutPoint {
887 self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
890 /// Whether to use anchors for this channel
891 pub fn opt_anchors(&self) -> bool {
892 self.inner.opt_anchors.is_some()
896 /// Information needed to build and sign a holder's commitment transaction.
898 /// The transaction is only signed once we are ready to broadcast.
900 pub struct HolderCommitmentTransaction {
901 inner: CommitmentTransaction,
902 /// Our counterparty's signature for the transaction
903 pub counterparty_sig: Signature,
904 /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
905 pub counterparty_htlc_sigs: Vec<Signature>,
906 // Which order the signatures should go in when constructing the final commitment tx witness.
907 // The user should be able to reconstruct this themselves, so we don't bother to expose it.
908 holder_sig_first: bool,
911 impl Deref for HolderCommitmentTransaction {
912 type Target = CommitmentTransaction;
914 fn deref(&self) -> &Self::Target { &self.inner }
917 impl Eq for HolderCommitmentTransaction {}
918 impl PartialEq for HolderCommitmentTransaction {
919 // We dont care whether we are signed in equality comparison
920 fn eq(&self, o: &Self) -> bool {
921 self.inner == o.inner
925 impl_writeable_tlv_based!(HolderCommitmentTransaction, {
926 (0, inner, required),
927 (2, counterparty_sig, required),
928 (4, holder_sig_first, required),
929 (6, counterparty_htlc_sigs, vec_type),
932 impl HolderCommitmentTransaction {
934 pub fn dummy() -> Self {
935 let secp_ctx = Secp256k1::new();
936 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
937 let dummy_sig = sign(&secp_ctx, &secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
939 let keys = TxCreationKeys {
940 per_commitment_point: dummy_key.clone(),
941 revocation_key: dummy_key.clone(),
942 broadcaster_htlc_key: dummy_key.clone(),
943 countersignatory_htlc_key: dummy_key.clone(),
944 broadcaster_delayed_payment_key: dummy_key.clone(),
946 let channel_pubkeys = ChannelPublicKeys {
947 funding_pubkey: dummy_key.clone(),
948 revocation_basepoint: dummy_key.clone(),
949 payment_point: dummy_key.clone(),
950 delayed_payment_basepoint: dummy_key.clone(),
951 htlc_basepoint: dummy_key.clone()
953 let channel_parameters = ChannelTransactionParameters {
954 holder_pubkeys: channel_pubkeys.clone(),
955 holder_selected_contest_delay: 0,
956 is_outbound_from_holder: false,
957 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
958 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
961 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
962 let inner = CommitmentTransaction::new_with_auxiliary_htlc_data(0, 0, 0, false, dummy_key.clone(), dummy_key.clone(), keys, 0, &mut htlcs_with_aux, &channel_parameters.as_counterparty_broadcastable());
963 HolderCommitmentTransaction {
965 counterparty_sig: dummy_sig,
966 counterparty_htlc_sigs: Vec::new(),
967 holder_sig_first: false
971 /// Create a new holder transaction with the given counterparty signatures.
972 /// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
973 pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
975 inner: commitment_tx,
977 counterparty_htlc_sigs,
978 holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
982 pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
983 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
984 let mut tx = self.inner.built.transaction.clone();
985 tx.input[0].witness.push(Vec::new());
986 let mut ser_holder_sig = holder_sig.serialize_der().to_vec();
987 ser_holder_sig.push(EcdsaSighashType::All as u8);
988 let mut ser_cp_sig = self.counterparty_sig.serialize_der().to_vec();
989 ser_cp_sig.push(EcdsaSighashType::All as u8);
991 if self.holder_sig_first {
992 tx.input[0].witness.push(ser_holder_sig);
993 tx.input[0].witness.push(ser_cp_sig);
995 tx.input[0].witness.push(ser_cp_sig);
996 tx.input[0].witness.push(ser_holder_sig);
999 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
1004 /// A pre-built Bitcoin commitment transaction and its txid.
1006 pub struct BuiltCommitmentTransaction {
1007 /// The commitment transaction
1008 pub transaction: Transaction,
1009 /// The txid for the commitment transaction.
1011 /// This is provided as a performance optimization, instead of calling transaction.txid()
1016 impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
1017 (0, transaction, required),
1018 (2, txid, required),
1021 impl BuiltCommitmentTransaction {
1022 /// Get the SIGHASH_ALL sighash value of the transaction.
1024 /// This can be used to verify a signature.
1025 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1026 let sighash = &sighash::SighashCache::new(&self.transaction).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1027 hash_to_message!(sighash)
1030 /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1031 /// because we are about to broadcast a holder transaction.
1032 pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1033 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1034 sign(secp_ctx, &sighash, funding_key)
1038 /// This class tracks the per-transaction information needed to build a closing transaction and will
1039 /// actually build it and sign.
1041 /// This class can be used inside a signer implementation to generate a signature given the relevant
1043 #[derive(Clone, Hash, PartialEq, Eq)]
1044 pub struct ClosingTransaction {
1045 to_holder_value_sat: u64,
1046 to_counterparty_value_sat: u64,
1047 to_holder_script: Script,
1048 to_counterparty_script: Script,
1052 impl ClosingTransaction {
1053 /// Construct an object of the class
1055 to_holder_value_sat: u64,
1056 to_counterparty_value_sat: u64,
1057 to_holder_script: Script,
1058 to_counterparty_script: Script,
1059 funding_outpoint: OutPoint,
1061 let built = build_closing_transaction(
1062 to_holder_value_sat, to_counterparty_value_sat,
1063 to_holder_script.clone(), to_counterparty_script.clone(),
1066 ClosingTransaction {
1067 to_holder_value_sat,
1068 to_counterparty_value_sat,
1070 to_counterparty_script,
1075 /// Trust our pre-built transaction.
1077 /// Applies a wrapper which allows access to the transaction.
1079 /// This should only be used if you fully trust the builder of this object. It should not
1080 /// be used by an external signer - instead use the verify function.
1081 pub fn trust(&self) -> TrustedClosingTransaction {
1082 TrustedClosingTransaction { inner: self }
1085 /// Verify our pre-built transaction.
1087 /// Applies a wrapper which allows access to the transaction.
1089 /// An external validating signer must call this method before signing
1090 /// or using the built transaction.
1091 pub fn verify(&self, funding_outpoint: OutPoint) -> Result<TrustedClosingTransaction, ()> {
1092 let built = build_closing_transaction(
1093 self.to_holder_value_sat, self.to_counterparty_value_sat,
1094 self.to_holder_script.clone(), self.to_counterparty_script.clone(),
1097 if self.built != built {
1100 Ok(TrustedClosingTransaction { inner: self })
1103 /// The value to be sent to the holder, or zero if the output will be omitted
1104 pub fn to_holder_value_sat(&self) -> u64 {
1105 self.to_holder_value_sat
1108 /// The value to be sent to the counterparty, or zero if the output will be omitted
1109 pub fn to_counterparty_value_sat(&self) -> u64 {
1110 self.to_counterparty_value_sat
1113 /// The destination of the holder's output
1114 pub fn to_holder_script(&self) -> &Script {
1115 &self.to_holder_script
1118 /// The destination of the counterparty's output
1119 pub fn to_counterparty_script(&self) -> &Script {
1120 &self.to_counterparty_script
1124 /// A wrapper on ClosingTransaction indicating that the built bitcoin
1125 /// transaction is trusted.
1127 /// See trust() and verify() functions on CommitmentTransaction.
1129 /// This structure implements Deref.
1130 pub struct TrustedClosingTransaction<'a> {
1131 inner: &'a ClosingTransaction,
1134 impl<'a> Deref for TrustedClosingTransaction<'a> {
1135 type Target = ClosingTransaction;
1137 fn deref(&self) -> &Self::Target { self.inner }
1140 impl<'a> TrustedClosingTransaction<'a> {
1141 /// The pre-built Bitcoin commitment transaction
1142 pub fn built_transaction(&self) -> &Transaction {
1146 /// Get the SIGHASH_ALL sighash value of the transaction.
1148 /// This can be used to verify a signature.
1149 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1150 let sighash = &sighash::SighashCache::new(&self.inner.built).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1151 hash_to_message!(sighash)
1154 /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1155 /// because we are about to broadcast a holder transaction.
1156 pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1157 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1158 sign(secp_ctx, &sighash, funding_key)
1162 /// This class tracks the per-transaction information needed to build a commitment transaction and will
1163 /// actually build it and sign. It is used for holder transactions that we sign only when needed
1164 /// and for transactions we sign for the counterparty.
1166 /// This class can be used inside a signer implementation to generate a signature given the relevant
1169 pub struct CommitmentTransaction {
1170 commitment_number: u64,
1171 to_broadcaster_value_sat: u64,
1172 to_countersignatory_value_sat: u64,
1173 feerate_per_kw: u32,
1174 htlcs: Vec<HTLCOutputInCommitment>,
1175 // A boolean that is serialization backwards-compatible
1176 opt_anchors: Option<()>,
1177 // A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
1178 keys: TxCreationKeys,
1179 // For access to the pre-built transaction, see doc for trust()
1180 built: BuiltCommitmentTransaction,
1183 impl Eq for CommitmentTransaction {}
1184 impl PartialEq for CommitmentTransaction {
1185 fn eq(&self, o: &Self) -> bool {
1186 let eq = self.commitment_number == o.commitment_number &&
1187 self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
1188 self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
1189 self.feerate_per_kw == o.feerate_per_kw &&
1190 self.htlcs == o.htlcs &&
1191 self.opt_anchors == o.opt_anchors &&
1192 self.keys == o.keys;
1194 debug_assert_eq!(self.built.transaction, o.built.transaction);
1195 debug_assert_eq!(self.built.txid, o.built.txid);
1201 impl_writeable_tlv_based!(CommitmentTransaction, {
1202 (0, commitment_number, required),
1203 (2, to_broadcaster_value_sat, required),
1204 (4, to_countersignatory_value_sat, required),
1205 (6, feerate_per_kw, required),
1206 (8, keys, required),
1207 (10, built, required),
1208 (12, htlcs, vec_type),
1209 (14, opt_anchors, option),
1212 impl CommitmentTransaction {
1213 /// Construct an object of the class while assigning transaction output indices to HTLCs.
1215 /// Populates HTLCOutputInCommitment.transaction_output_index in htlcs_with_aux.
1217 /// The generic T allows the caller to match the HTLC output index with auxiliary data.
1218 /// This auxiliary data is not stored in this object.
1220 /// Only include HTLCs that are above the dust limit for the channel.
1222 /// (C-not exported) due to the generic though we likely should expose a version without
1223 pub fn new_with_auxiliary_htlc_data<T>(commitment_number: u64, to_broadcaster_value_sat: u64, to_countersignatory_value_sat: u64, opt_anchors: bool, 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 {
1224 // Sort outputs and populate output indices while keeping track of the auxiliary data
1225 let (outputs, htlcs) = Self::internal_build_outputs(&keys, to_broadcaster_value_sat, to_countersignatory_value_sat, htlcs_with_aux, channel_parameters, opt_anchors, &broadcaster_funding_key, &countersignatory_funding_key).unwrap();
1227 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
1228 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1229 let txid = transaction.txid();
1230 CommitmentTransaction {
1232 to_broadcaster_value_sat,
1233 to_countersignatory_value_sat,
1236 opt_anchors: if opt_anchors { Some(()) } else { None },
1238 built: BuiltCommitmentTransaction {
1245 fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<BuiltCommitmentTransaction, ()> {
1246 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
1248 let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
1249 let (outputs, _) = Self::internal_build_outputs(keys, self.to_broadcaster_value_sat, self.to_countersignatory_value_sat, &mut htlcs_with_aux, channel_parameters, self.opt_anchors.is_some(), broadcaster_funding_key, countersignatory_funding_key)?;
1251 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1252 let txid = transaction.txid();
1253 let built_transaction = BuiltCommitmentTransaction {
1257 Ok(built_transaction)
1260 fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
1263 lock_time: PackedLockTime(((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32)),
1269 // This is used in two cases:
1270 // - initial sorting of outputs / HTLCs in the constructor, in which case T is auxiliary data the
1271 // caller needs to have sorted together with the HTLCs so it can keep track of the output index
1272 // - building of a bitcoin transaction during a verify() call, in which case T is just ()
1273 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, opt_anchors: bool, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<(Vec<TxOut>, Vec<HTLCOutputInCommitment>), ()> {
1274 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1275 let contest_delay = channel_parameters.contest_delay();
1277 let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
1279 if to_countersignatory_value_sat > 0 {
1280 let script = if opt_anchors {
1281 get_to_countersignatory_with_anchors_redeemscript(&countersignatory_pubkeys.payment_point).to_v0_p2wsh()
1283 Payload::p2wpkh(&BitcoinPublicKey::new(countersignatory_pubkeys.payment_point)).unwrap().script_pubkey()
1287 script_pubkey: script.clone(),
1288 value: to_countersignatory_value_sat,
1294 if to_broadcaster_value_sat > 0 {
1295 let redeem_script = get_revokeable_redeemscript(
1296 &keys.revocation_key,
1298 &keys.broadcaster_delayed_payment_key,
1302 script_pubkey: redeem_script.to_v0_p2wsh(),
1303 value: to_broadcaster_value_sat,
1310 if to_broadcaster_value_sat > 0 || !htlcs_with_aux.is_empty() {
1311 let anchor_script = get_anchor_redeemscript(broadcaster_funding_key);
1314 script_pubkey: anchor_script.to_v0_p2wsh(),
1315 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1321 if to_countersignatory_value_sat > 0 || !htlcs_with_aux.is_empty() {
1322 let anchor_script = get_anchor_redeemscript(countersignatory_funding_key);
1325 script_pubkey: anchor_script.to_v0_p2wsh(),
1326 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1333 let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
1334 for (htlc, _) in htlcs_with_aux {
1335 let script = chan_utils::get_htlc_redeemscript(&htlc, opt_anchors, &keys);
1337 script_pubkey: script.to_v0_p2wsh(),
1338 value: htlc.amount_msat / 1000,
1340 txouts.push((txout, Some(htlc)));
1343 // Sort output in BIP-69 order (amount, scriptPubkey). Tie-breaks based on HTLC
1344 // CLTV expiration height.
1345 sort_outputs(&mut txouts, |a, b| {
1346 if let &Some(ref a_htlcout) = a {
1347 if let &Some(ref b_htlcout) = b {
1348 a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
1349 // Note that due to hash collisions, we have to have a fallback comparison
1350 // here for fuzzing mode (otherwise at least chanmon_fail_consistency
1352 .then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
1353 // For non-HTLC outputs, if they're copying our SPK we don't really care if we
1354 // close the channel due to mismatches - they're doing something dumb:
1355 } else { cmp::Ordering::Equal }
1356 } else { cmp::Ordering::Equal }
1359 let mut outputs = Vec::with_capacity(txouts.len());
1360 for (idx, out) in txouts.drain(..).enumerate() {
1361 if let Some(htlc) = out.1 {
1362 htlc.transaction_output_index = Some(idx as u32);
1363 htlcs.push(htlc.clone());
1365 outputs.push(out.0);
1367 Ok((outputs, htlcs))
1370 fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
1371 let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
1372 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1373 let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
1374 &broadcaster_pubkeys.payment_point,
1375 &countersignatory_pubkeys.payment_point,
1376 channel_parameters.is_outbound(),
1379 let obscured_commitment_transaction_number =
1380 commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
1383 let mut ins: Vec<TxIn> = Vec::new();
1385 previous_output: channel_parameters.funding_outpoint(),
1386 script_sig: Script::new(),
1387 sequence: Sequence(((0x80 as u32) << 8 * 3)
1388 | ((obscured_commitment_transaction_number >> 3 * 8) as u32)),
1389 witness: Witness::new(),
1393 (obscured_commitment_transaction_number, txins)
1396 /// The backwards-counting commitment number
1397 pub fn commitment_number(&self) -> u64 {
1398 self.commitment_number
1401 /// The value to be sent to the broadcaster
1402 pub fn to_broadcaster_value_sat(&self) -> u64 {
1403 self.to_broadcaster_value_sat
1406 /// The value to be sent to the counterparty
1407 pub fn to_countersignatory_value_sat(&self) -> u64 {
1408 self.to_countersignatory_value_sat
1411 /// The feerate paid per 1000-weight-unit in this commitment transaction.
1412 pub fn feerate_per_kw(&self) -> u32 {
1416 /// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
1417 /// which were included in this commitment transaction in output order.
1418 /// The transaction index is always populated.
1420 /// (C-not exported) as we cannot currently convert Vec references to/from C, though we should
1421 /// expose a less effecient version which creates a Vec of references in the future.
1422 pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
1426 /// Trust our pre-built transaction and derived transaction creation public keys.
1428 /// Applies a wrapper which allows access to these fields.
1430 /// This should only be used if you fully trust the builder of this object. It should not
1431 /// be used by an external signer - instead use the verify function.
1432 pub fn trust(&self) -> TrustedCommitmentTransaction {
1433 TrustedCommitmentTransaction { inner: self }
1436 /// Verify our pre-built transaction and derived transaction creation public keys.
1438 /// Applies a wrapper which allows access to these fields.
1440 /// An external validating signer must call this method before signing
1441 /// or using the built transaction.
1442 pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
1443 // This is the only field of the key cache that we trust
1444 let per_commitment_point = self.keys.per_commitment_point;
1445 let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx).unwrap();
1446 if keys != self.keys {
1449 let tx = self.internal_rebuild_transaction(&keys, channel_parameters, &broadcaster_keys.funding_pubkey, &countersignatory_keys.funding_pubkey)?;
1450 if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
1453 Ok(TrustedCommitmentTransaction { inner: self })
1457 /// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
1458 /// transaction and the transaction creation keys) are trusted.
1460 /// See trust() and verify() functions on CommitmentTransaction.
1462 /// This structure implements Deref.
1463 pub struct TrustedCommitmentTransaction<'a> {
1464 inner: &'a CommitmentTransaction,
1467 impl<'a> Deref for TrustedCommitmentTransaction<'a> {
1468 type Target = CommitmentTransaction;
1470 fn deref(&self) -> &Self::Target { self.inner }
1473 impl<'a> TrustedCommitmentTransaction<'a> {
1474 /// The transaction ID of the built Bitcoin transaction
1475 pub fn txid(&self) -> Txid {
1476 self.inner.built.txid
1479 /// The pre-built Bitcoin commitment transaction
1480 pub fn built_transaction(&self) -> &BuiltCommitmentTransaction {
1484 /// The pre-calculated transaction creation public keys.
1485 pub fn keys(&self) -> &TxCreationKeys {
1489 /// Should anchors be used.
1490 pub fn opt_anchors(&self) -> bool {
1491 self.opt_anchors.is_some()
1494 /// Get a signature for each HTLC which was included in the commitment transaction (ie for
1495 /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
1497 /// The returned Vec has one entry for each HTLC, and in the same order.
1499 /// This function is only valid in the holder commitment context, it always uses EcdsaSighashType::All.
1500 pub fn get_htlc_sigs<T: secp256k1::Signing>(&self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters, secp_ctx: &Secp256k1<T>) -> Result<Vec<Signature>, ()> {
1501 let inner = self.inner;
1502 let keys = &inner.keys;
1503 let txid = inner.built.txid;
1504 let mut ret = Vec::with_capacity(inner.htlcs.len());
1505 let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key).map_err(|_| ())?;
1507 for this_htlc in inner.htlcs.iter() {
1508 assert!(this_htlc.transaction_output_index.is_some());
1509 let htlc_tx = build_htlc_transaction(&txid, inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc, self.opt_anchors(), &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
1511 let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc, self.opt_anchors(), &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key);
1513 let sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, EcdsaSighashType::All).unwrap()[..]);
1514 ret.push(sign(secp_ctx, &sighash, &holder_htlc_key));
1519 /// Gets a signed HTLC transaction given a preimage (for !htlc.offered) and the holder HTLC transaction signature.
1520 pub(crate) fn get_signed_htlc_tx(&self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature, preimage: &Option<PaymentPreimage>) -> Transaction {
1521 let inner = self.inner;
1522 let keys = &inner.keys;
1523 let txid = inner.built.txid;
1524 let this_htlc = &inner.htlcs[htlc_index];
1525 assert!(this_htlc.transaction_output_index.is_some());
1526 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
1527 if !this_htlc.offered && preimage.is_none() { unreachable!(); }
1528 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
1529 if this_htlc.offered && preimage.is_some() { unreachable!(); }
1531 let mut htlc_tx = build_htlc_transaction(&txid, inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc, self.opt_anchors(), &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
1533 let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc, self.opt_anchors(), &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key);
1535 let sighashtype = if self.opt_anchors() { EcdsaSighashType::SinglePlusAnyoneCanPay } else { EcdsaSighashType::All };
1537 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
1538 htlc_tx.input[0].witness.push(Vec::new());
1540 let mut cp_sig_ser = counterparty_signature.serialize_der().to_vec();
1541 cp_sig_ser.push(sighashtype as u8);
1542 htlc_tx.input[0].witness.push(cp_sig_ser);
1543 let mut holder_sig_ser = signature.serialize_der().to_vec();
1544 holder_sig_ser.push(EcdsaSighashType::All as u8);
1545 htlc_tx.input[0].witness.push(holder_sig_ser);
1547 if this_htlc.offered {
1548 // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
1549 htlc_tx.input[0].witness.push(Vec::new());
1551 htlc_tx.input[0].witness.push(preimage.unwrap().0.to_vec());
1554 htlc_tx.input[0].witness.push(htlc_redeemscript.as_bytes().to_vec());
1559 /// Commitment transaction numbers which appear in the transactions themselves are XOR'd with a
1560 /// shared secret first. This prevents on-chain observers from discovering how many commitment
1561 /// transactions occurred in a channel before it was closed.
1563 /// This function gets the shared secret from relevant channel public keys and can be used to
1564 /// "decrypt" the commitment transaction number given a commitment transaction on-chain.
1565 pub fn get_commitment_transaction_number_obscure_factor(
1566 broadcaster_payment_basepoint: &PublicKey,
1567 countersignatory_payment_basepoint: &PublicKey,
1568 outbound_from_broadcaster: bool,
1570 let mut sha = Sha256::engine();
1572 if outbound_from_broadcaster {
1573 sha.input(&broadcaster_payment_basepoint.serialize());
1574 sha.input(&countersignatory_payment_basepoint.serialize());
1576 sha.input(&countersignatory_payment_basepoint.serialize());
1577 sha.input(&broadcaster_payment_basepoint.serialize());
1579 let res = Sha256::from_engine(sha).into_inner();
1581 ((res[26] as u64) << 5 * 8)
1582 | ((res[27] as u64) << 4 * 8)
1583 | ((res[28] as u64) << 3 * 8)
1584 | ((res[29] as u64) << 2 * 8)
1585 | ((res[30] as u64) << 1 * 8)
1586 | ((res[31] as u64) << 0 * 8)
1591 use super::CounterpartyCommitmentSecrets;
1592 use crate::{hex, chain};
1593 use crate::prelude::*;
1594 use crate::ln::chan_utils::{get_htlc_redeemscript, get_to_countersignatory_with_anchors_redeemscript, CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
1595 use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
1596 use crate::util::test_utils;
1597 use crate::chain::keysinterface::{KeysInterface, BaseSign};
1598 use bitcoin::{Network, Txid};
1599 use bitcoin::hashes::Hash;
1600 use crate::ln::PaymentHash;
1601 use bitcoin::hashes::hex::ToHex;
1602 use bitcoin::util::address::Payload;
1603 use bitcoin::PublicKey as BitcoinPublicKey;
1607 let secp_ctx = Secp256k1::new();
1609 let seed = [42; 32];
1610 let network = Network::Testnet;
1611 let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
1612 let signer = keys_provider.get_channel_signer(false, 3000);
1613 let counterparty_signer = keys_provider.get_channel_signer(false, 3000);
1614 let delayed_payment_base = &signer.pubkeys().delayed_payment_basepoint;
1615 let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
1616 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
1617 let htlc_basepoint = &signer.pubkeys().htlc_basepoint;
1618 let holder_pubkeys = signer.pubkeys();
1619 let counterparty_pubkeys = counterparty_signer.pubkeys();
1620 let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint).unwrap();
1621 let mut channel_parameters = ChannelTransactionParameters {
1622 holder_pubkeys: holder_pubkeys.clone(),
1623 holder_selected_contest_delay: 0,
1624 is_outbound_from_holder: false,
1625 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: counterparty_pubkeys.clone(), selected_contest_delay: 0 }),
1626 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1630 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
1632 // Generate broadcaster and counterparty outputs
1633 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1636 holder_pubkeys.funding_pubkey,
1637 counterparty_pubkeys.funding_pubkey,
1639 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1641 assert_eq!(tx.built.transaction.output.len(), 2);
1642 assert_eq!(tx.built.transaction.output[1].script_pubkey, Payload::p2wpkh(&BitcoinPublicKey::new(counterparty_pubkeys.payment_point)).unwrap().script_pubkey());
1644 // Generate broadcaster and counterparty outputs as well as two anchors
1645 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1648 holder_pubkeys.funding_pubkey,
1649 counterparty_pubkeys.funding_pubkey,
1651 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1653 assert_eq!(tx.built.transaction.output.len(), 4);
1654 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_to_countersignatory_with_anchors_redeemscript(&counterparty_pubkeys.payment_point).to_v0_p2wsh());
1656 // Generate broadcaster output and anchor
1657 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1660 holder_pubkeys.funding_pubkey,
1661 counterparty_pubkeys.funding_pubkey,
1663 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1665 assert_eq!(tx.built.transaction.output.len(), 2);
1667 // Generate counterparty output and anchor
1668 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1671 holder_pubkeys.funding_pubkey,
1672 counterparty_pubkeys.funding_pubkey,
1674 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1676 assert_eq!(tx.built.transaction.output.len(), 2);
1678 let received_htlc = HTLCOutputInCommitment {
1680 amount_msat: 400000,
1682 payment_hash: PaymentHash([42; 32]),
1683 transaction_output_index: None,
1686 let offered_htlc = HTLCOutputInCommitment {
1688 amount_msat: 600000,
1690 payment_hash: PaymentHash([43; 32]),
1691 transaction_output_index: None,
1694 // Generate broadcaster output and received and offered HTLC outputs, w/o anchors
1695 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1698 holder_pubkeys.funding_pubkey,
1699 counterparty_pubkeys.funding_pubkey,
1701 &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1702 &channel_parameters.as_holder_broadcastable()
1704 assert_eq!(tx.built.transaction.output.len(), 3);
1705 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_htlc_redeemscript(&received_htlc, false, &keys).to_v0_p2wsh());
1706 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&offered_htlc, false, &keys).to_v0_p2wsh());
1707 assert_eq!(get_htlc_redeemscript(&received_htlc, false, &keys).to_v0_p2wsh().to_hex(),
1708 "002085cf52e41ba7c099a39df504e7b61f6de122971ceb53b06731876eaeb85e8dc5");
1709 assert_eq!(get_htlc_redeemscript(&offered_htlc, false, &keys).to_v0_p2wsh().to_hex(),
1710 "002049f0736bb335c61a04d2623a24df878a7592a3c51fa7258d41b2c85318265e73");
1712 // Generate broadcaster output and received and offered HTLC outputs, with anchors
1713 channel_parameters.opt_anchors = Some(());
1714 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1717 holder_pubkeys.funding_pubkey,
1718 counterparty_pubkeys.funding_pubkey,
1720 &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1721 &channel_parameters.as_holder_broadcastable()
1723 assert_eq!(tx.built.transaction.output.len(), 5);
1724 assert_eq!(tx.built.transaction.output[2].script_pubkey, get_htlc_redeemscript(&received_htlc, true, &keys).to_v0_p2wsh());
1725 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_htlc_redeemscript(&offered_htlc, true, &keys).to_v0_p2wsh());
1726 assert_eq!(get_htlc_redeemscript(&received_htlc, true, &keys).to_v0_p2wsh().to_hex(),
1727 "002067114123af3f95405bae4fd930fc95de03e3c86baaee8b2dd29b43dd26cf613c");
1728 assert_eq!(get_htlc_redeemscript(&offered_htlc, true, &keys).to_v0_p2wsh().to_hex(),
1729 "0020a06e3b0d4fcf704f2b9c41e16a70099e39989466c3142b8573a1154542f28f57");
1733 fn test_per_commitment_storage() {
1734 // Test vectors from BOLT 3:
1735 let mut secrets: Vec<[u8; 32]> = Vec::new();
1738 macro_rules! test_secrets {
1740 let mut idx = 281474976710655;
1741 for secret in secrets.iter() {
1742 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1745 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1746 assert!(monitor.get_secret(idx).is_none());
1751 // insert_secret correct sequence
1752 monitor = CounterpartyCommitmentSecrets::new();
1755 secrets.push([0; 32]);
1756 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1757 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1760 secrets.push([0; 32]);
1761 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1762 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1765 secrets.push([0; 32]);
1766 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1767 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1770 secrets.push([0; 32]);
1771 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1772 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1775 secrets.push([0; 32]);
1776 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1777 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1780 secrets.push([0; 32]);
1781 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1782 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1785 secrets.push([0; 32]);
1786 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1787 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1790 secrets.push([0; 32]);
1791 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1792 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
1797 // insert_secret #1 incorrect
1798 monitor = CounterpartyCommitmentSecrets::new();
1801 secrets.push([0; 32]);
1802 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1803 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1806 secrets.push([0; 32]);
1807 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1808 assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
1812 // insert_secret #2 incorrect (#1 derived from incorrect)
1813 monitor = CounterpartyCommitmentSecrets::new();
1816 secrets.push([0; 32]);
1817 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1818 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1821 secrets.push([0; 32]);
1822 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1823 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1826 secrets.push([0; 32]);
1827 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1828 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1831 secrets.push([0; 32]);
1832 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1833 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1837 // insert_secret #3 incorrect
1838 monitor = CounterpartyCommitmentSecrets::new();
1841 secrets.push([0; 32]);
1842 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1843 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1846 secrets.push([0; 32]);
1847 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1848 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1851 secrets.push([0; 32]);
1852 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1853 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1856 secrets.push([0; 32]);
1857 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1858 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1862 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
1863 monitor = CounterpartyCommitmentSecrets::new();
1866 secrets.push([0; 32]);
1867 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1868 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1871 secrets.push([0; 32]);
1872 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1873 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1876 secrets.push([0; 32]);
1877 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1878 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1881 secrets.push([0; 32]);
1882 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
1883 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1886 secrets.push([0; 32]);
1887 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1888 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1891 secrets.push([0; 32]);
1892 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1893 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1896 secrets.push([0; 32]);
1897 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1898 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1901 secrets.push([0; 32]);
1902 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1903 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1907 // insert_secret #5 incorrect
1908 monitor = CounterpartyCommitmentSecrets::new();
1911 secrets.push([0; 32]);
1912 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1913 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1916 secrets.push([0; 32]);
1917 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1918 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1921 secrets.push([0; 32]);
1922 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1923 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1926 secrets.push([0; 32]);
1927 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1928 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1931 secrets.push([0; 32]);
1932 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1933 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1936 secrets.push([0; 32]);
1937 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1938 assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
1942 // insert_secret #6 incorrect (5 derived from incorrect)
1943 monitor = CounterpartyCommitmentSecrets::new();
1946 secrets.push([0; 32]);
1947 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1948 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1951 secrets.push([0; 32]);
1952 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1953 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1956 secrets.push([0; 32]);
1957 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1958 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1961 secrets.push([0; 32]);
1962 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1963 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1966 secrets.push([0; 32]);
1967 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1968 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1971 secrets.push([0; 32]);
1972 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
1973 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1976 secrets.push([0; 32]);
1977 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1978 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1981 secrets.push([0; 32]);
1982 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1983 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1987 // insert_secret #7 incorrect
1988 monitor = CounterpartyCommitmentSecrets::new();
1991 secrets.push([0; 32]);
1992 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1993 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1996 secrets.push([0; 32]);
1997 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1998 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2001 secrets.push([0; 32]);
2002 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2003 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2006 secrets.push([0; 32]);
2007 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2008 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2011 secrets.push([0; 32]);
2012 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2013 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2016 secrets.push([0; 32]);
2017 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2018 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2021 secrets.push([0; 32]);
2022 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2023 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2026 secrets.push([0; 32]);
2027 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2028 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2032 // insert_secret #8 incorrect
2033 monitor = CounterpartyCommitmentSecrets::new();
2036 secrets.push([0; 32]);
2037 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2038 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2041 secrets.push([0; 32]);
2042 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2043 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2046 secrets.push([0; 32]);
2047 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2048 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2051 secrets.push([0; 32]);
2052 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2053 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2056 secrets.push([0; 32]);
2057 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2058 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2061 secrets.push([0; 32]);
2062 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2063 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2066 secrets.push([0; 32]);
2067 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2068 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2071 secrets.push([0; 32]);
2072 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2073 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());