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;
18 use bitcoin::hashes::{Hash, HashEngine};
19 use bitcoin::hashes::sha256::Hash as Sha256;
20 use bitcoin::hashes::ripemd160::Hash as Ripemd160;
21 use bitcoin::hash_types::{Txid, PubkeyHash};
23 use crate::ln::{PaymentHash, PaymentPreimage};
24 use crate::ln::msgs::DecodeError;
25 use crate::util::ser::{Readable, Writeable, Writer};
26 use crate::util::{byte_utils, transaction_utils};
28 use bitcoin::hash_types::WPubkeyHash;
29 use bitcoin::secp256k1::{SecretKey, PublicKey, Scalar};
30 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature, Message};
31 use bitcoin::{PackedLockTime, secp256k1, Sequence, Witness};
34 use crate::prelude::*;
36 use crate::ln::chan_utils;
37 use crate::util::transaction_utils::sort_outputs;
38 use crate::ln::channel::{INITIAL_COMMITMENT_NUMBER, ANCHOR_OUTPUT_VALUE_SATOSHI};
41 use crate::util::crypto::sign;
43 pub(crate) const MAX_HTLCS: u16 = 483;
44 pub(crate) const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
45 pub(crate) const OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS: usize = 136;
46 // The weight of `accepted_htlc_script` can vary in function of its CLTV argument value. We define a
47 // range that encompasses both its non-anchors and anchors variants.
48 pub(crate) const MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 136;
49 pub(crate) const MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 143;
51 /// Gets the weight for an HTLC-Success transaction.
53 pub fn htlc_success_tx_weight(opt_anchors: bool) -> u64 {
54 const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
55 const HTLC_SUCCESS_ANCHOR_TX_WEIGHT: u64 = 706;
56 if opt_anchors { HTLC_SUCCESS_ANCHOR_TX_WEIGHT } else { HTLC_SUCCESS_TX_WEIGHT }
59 /// Gets the weight for an HTLC-Timeout transaction.
61 pub fn htlc_timeout_tx_weight(opt_anchors: bool) -> u64 {
62 const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
63 const HTLC_TIMEOUT_ANCHOR_TX_WEIGHT: u64 = 666;
64 if opt_anchors { HTLC_TIMEOUT_ANCHOR_TX_WEIGHT } else { HTLC_TIMEOUT_TX_WEIGHT }
67 #[derive(PartialEq, Eq)]
68 pub(crate) enum HTLCClaim {
77 /// Check if a given input witness attempts to claim a HTLC.
78 pub(crate) fn from_witness(witness: &Witness) -> Option<Self> {
79 debug_assert_eq!(OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS, MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT);
80 if witness.len() < 2 {
83 let witness_script = witness.last().unwrap();
84 let second_to_last = witness.second_to_last().unwrap();
85 if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT {
86 if witness.len() == 3 && second_to_last.len() == 33 {
87 // <revocation sig> <revocationpubkey> <witness_script>
88 Some(Self::Revocation)
89 } else if witness.len() == 3 && second_to_last.len() == 32 {
90 // <remotehtlcsig> <payment_preimage> <witness_script>
91 Some(Self::OfferedPreimage)
92 } else if witness.len() == 5 && second_to_last.len() == 0 {
93 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
94 Some(Self::OfferedTimeout)
98 } else if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS {
99 // It's possible for the weight of `offered_htlc_script` and `accepted_htlc_script` to
100 // match so we check for both here.
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)
110 } else if witness.len() == 3 && second_to_last.len() == 0 {
111 // <remotehtlcsig> <> <witness_script>
112 Some(Self::AcceptedTimeout)
113 } else if witness.len() == 5 && second_to_last.len() == 32 {
114 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
115 Some(Self::AcceptedPreimage)
119 } else if witness_script.len() > MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT &&
120 witness_script.len() <= MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT {
121 // Handle remaining range of ACCEPTED_HTLC_SCRIPT_WEIGHT.
122 if witness.len() == 3 && second_to_last.len() == 33 {
123 // <revocation sig> <revocationpubkey> <witness_script>
124 Some(Self::Revocation)
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)
140 // Various functions for key derivation and transaction creation for use within channels. Primarily
141 // used in Channel and ChannelMonitor.
143 /// Build the commitment secret from the seed and the commitment number
144 pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
145 let mut res: [u8; 32] = commitment_seed.clone();
148 if idx & (1 << bitpos) == (1 << bitpos) {
149 res[bitpos / 8] ^= 1 << (bitpos & 7);
150 res = Sha256::hash(&res).into_inner();
156 /// Build a closing transaction
157 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 {
159 let mut ins: Vec<TxIn> = Vec::new();
161 previous_output: funding_outpoint,
162 script_sig: Script::new(),
163 sequence: Sequence::MAX,
164 witness: Witness::new(),
169 let mut txouts: Vec<(TxOut, ())> = Vec::new();
171 if to_counterparty_value_sat > 0 {
173 script_pubkey: to_counterparty_script,
174 value: to_counterparty_value_sat
178 if to_holder_value_sat > 0 {
180 script_pubkey: to_holder_script,
181 value: to_holder_value_sat
185 transaction_utils::sort_outputs(&mut txouts, |_, _| { cmp::Ordering::Equal }); // Ordering doesnt matter if they used our pubkey...
187 let mut outputs: Vec<TxOut> = Vec::new();
188 for out in txouts.drain(..) {
194 lock_time: PackedLockTime::ZERO,
200 /// Implements the per-commitment secret storage scheme from
201 /// [BOLT 3](https://github.com/lightning/bolts/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
203 /// Allows us to keep track of all of the revocation secrets of our counterparty in just 50*32 bytes
206 pub struct CounterpartyCommitmentSecrets {
207 old_secrets: [([u8; 32], u64); 49],
210 impl Eq for CounterpartyCommitmentSecrets {}
211 impl PartialEq for CounterpartyCommitmentSecrets {
212 fn eq(&self, other: &Self) -> bool {
213 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
214 if secret != o_secret || idx != o_idx {
222 impl CounterpartyCommitmentSecrets {
223 /// Creates a new empty `CounterpartyCommitmentSecrets` structure.
224 pub fn new() -> Self {
225 Self { old_secrets: [([0; 32], 1 << 48); 49], }
229 fn place_secret(idx: u64) -> u8 {
231 if idx & (1 << i) == (1 << i) {
238 /// Returns the minimum index of all stored secrets. Note that indexes start
239 /// at 1 << 48 and get decremented by one for each new secret.
240 pub fn get_min_seen_secret(&self) -> u64 {
241 //TODO This can be optimized?
242 let mut min = 1 << 48;
243 for &(_, idx) in self.old_secrets.iter() {
252 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
253 let mut res: [u8; 32] = secret;
255 let bitpos = bits - 1 - i;
256 if idx & (1 << bitpos) == (1 << bitpos) {
257 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
258 res = Sha256::hash(&res).into_inner();
264 /// Inserts the `secret` at `idx`. Returns `Ok(())` if the secret
265 /// was generated in accordance with BOLT 3 and is consistent with previous secrets.
266 pub fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
267 let pos = Self::place_secret(idx);
269 let (old_secret, old_idx) = self.old_secrets[i as usize];
270 if Self::derive_secret(secret, pos, old_idx) != old_secret {
274 if self.get_min_seen_secret() <= idx {
277 self.old_secrets[pos as usize] = (secret, idx);
281 /// Returns the secret at `idx`.
282 /// Returns `None` if `idx` is < [`CounterpartyCommitmentSecrets::get_min_seen_secret`].
283 pub fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
284 for i in 0..self.old_secrets.len() {
285 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
286 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
289 assert!(idx < self.get_min_seen_secret());
294 impl Writeable for CounterpartyCommitmentSecrets {
295 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
296 for &(ref secret, ref idx) in self.old_secrets.iter() {
297 writer.write_all(secret)?;
298 writer.write_all(&byte_utils::be64_to_array(*idx))?;
300 write_tlv_fields!(writer, {});
304 impl Readable for CounterpartyCommitmentSecrets {
305 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
306 let mut old_secrets = [([0; 32], 1 << 48); 49];
307 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
308 *secret = Readable::read(reader)?;
309 *idx = Readable::read(reader)?;
311 read_tlv_fields!(reader, {});
312 Ok(Self { old_secrets })
316 /// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
317 /// from the base secret and the per_commitment_point.
318 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> SecretKey {
319 let mut sha = Sha256::engine();
320 sha.input(&per_commitment_point.serialize());
321 sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
322 let res = Sha256::from_engine(sha).into_inner();
324 base_secret.clone().add_tweak(&Scalar::from_be_bytes(res).unwrap())
325 .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.")
328 /// Derives a per-commitment-transaction public key (eg an htlc key or a delayed_payment key)
329 /// from the base point and the per_commitment_key. This is the public equivalent of
330 /// derive_private_key - using only public keys to derive a public key instead of private keys.
331 pub fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> PublicKey {
332 let mut sha = Sha256::engine();
333 sha.input(&per_commitment_point.serialize());
334 sha.input(&base_point.serialize());
335 let res = Sha256::from_engine(sha).into_inner();
337 let hashkey = PublicKey::from_secret_key(&secp_ctx,
338 &SecretKey::from_slice(&res).expect("Hashes should always be valid keys unless SHA-256 is broken"));
339 base_point.combine(&hashkey)
340 .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.")
343 /// Derives a per-commitment-transaction revocation key from its constituent parts.
345 /// Only the cheating participant owns a valid witness to propagate a revoked
346 /// commitment transaction, thus per_commitment_secret always come from cheater
347 /// and revocation_base_secret always come from punisher, which is the broadcaster
348 /// of the transaction spending with this key knowledge.
349 pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>,
350 per_commitment_secret: &SecretKey, countersignatory_revocation_base_secret: &SecretKey)
352 let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
353 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
355 let rev_append_commit_hash_key = {
356 let mut sha = Sha256::engine();
357 sha.input(&countersignatory_revocation_base_point.serialize());
358 sha.input(&per_commitment_point.serialize());
360 Sha256::from_engine(sha).into_inner()
362 let commit_append_rev_hash_key = {
363 let mut sha = Sha256::engine();
364 sha.input(&per_commitment_point.serialize());
365 sha.input(&countersignatory_revocation_base_point.serialize());
367 Sha256::from_engine(sha).into_inner()
370 let countersignatory_contrib = countersignatory_revocation_base_secret.clone().mul_tweak(&Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
371 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
372 let broadcaster_contrib = per_commitment_secret.clone().mul_tweak(&Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
373 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
374 countersignatory_contrib.add_tweak(&Scalar::from_be_bytes(broadcaster_contrib.secret_bytes()).unwrap())
375 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
378 /// Derives a per-commitment-transaction revocation public key from its constituent parts. This is
379 /// the public equivalend of derive_private_revocation_key - using only public keys to derive a
380 /// public key instead of private keys.
382 /// Only the cheating participant owns a valid witness to propagate a revoked
383 /// commitment transaction, thus per_commitment_point always come from cheater
384 /// and revocation_base_point always come from punisher, which is the broadcaster
385 /// of the transaction spending with this key knowledge.
387 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
388 /// generated (ie our own).
389 pub fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp256k1<T>,
390 per_commitment_point: &PublicKey, countersignatory_revocation_base_point: &PublicKey)
392 let rev_append_commit_hash_key = {
393 let mut sha = Sha256::engine();
394 sha.input(&countersignatory_revocation_base_point.serialize());
395 sha.input(&per_commitment_point.serialize());
397 Sha256::from_engine(sha).into_inner()
399 let commit_append_rev_hash_key = {
400 let mut sha = Sha256::engine();
401 sha.input(&per_commitment_point.serialize());
402 sha.input(&countersignatory_revocation_base_point.serialize());
404 Sha256::from_engine(sha).into_inner()
407 let countersignatory_contrib = countersignatory_revocation_base_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
408 .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
409 let broadcaster_contrib = per_commitment_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
410 .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
411 countersignatory_contrib.combine(&broadcaster_contrib)
412 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
415 /// The set of public keys which are used in the creation of one commitment transaction.
416 /// These are derived from the channel base keys and per-commitment data.
418 /// A broadcaster key is provided from potential broadcaster of the computed transaction.
419 /// A countersignatory key is coming from a protocol participant unable to broadcast the
422 /// These keys are assumed to be good, either because the code derived them from
423 /// channel basepoints via the new function, or they were obtained via
424 /// CommitmentTransaction.trust().keys() because we trusted the source of the
425 /// pre-calculated keys.
426 #[derive(PartialEq, Eq, Clone)]
427 pub struct TxCreationKeys {
428 /// The broadcaster's per-commitment public key which was used to derive the other keys.
429 pub per_commitment_point: PublicKey,
430 /// The revocation key which is used to allow the broadcaster of the commitment
431 /// transaction to provide their counterparty the ability to punish them if they broadcast
433 pub revocation_key: PublicKey,
434 /// Broadcaster's HTLC Key
435 pub broadcaster_htlc_key: PublicKey,
436 /// Countersignatory's HTLC Key
437 pub countersignatory_htlc_key: PublicKey,
438 /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
439 pub broadcaster_delayed_payment_key: PublicKey,
442 impl_writeable_tlv_based!(TxCreationKeys, {
443 (0, per_commitment_point, required),
444 (2, revocation_key, required),
445 (4, broadcaster_htlc_key, required),
446 (6, countersignatory_htlc_key, required),
447 (8, broadcaster_delayed_payment_key, required),
450 /// One counterparty's public keys which do not change over the life of a channel.
451 #[derive(Clone, PartialEq, Eq)]
452 pub struct ChannelPublicKeys {
453 /// The public key which is used to sign all commitment transactions, as it appears in the
454 /// on-chain channel lock-in 2-of-2 multisig output.
455 pub funding_pubkey: PublicKey,
456 /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
457 /// revocation keys. This is combined with the per-commitment-secret generated by the
458 /// counterparty to create a secret which the counterparty can reveal to revoke previous
460 pub revocation_basepoint: PublicKey,
461 /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
462 /// spendable primary channel balance on the broadcaster's commitment transaction. This key is
463 /// static across every commitment transaction.
464 pub payment_point: PublicKey,
465 /// The base point which is used (with derive_public_key) to derive a per-commitment payment
466 /// public key which receives non-HTLC-encumbered funds which are only available for spending
467 /// after some delay (or can be claimed via the revocation path).
468 pub delayed_payment_basepoint: PublicKey,
469 /// The base point which is used (with derive_public_key) to derive a per-commitment public key
470 /// which is used to encumber HTLC-in-flight outputs.
471 pub htlc_basepoint: PublicKey,
474 impl_writeable_tlv_based!(ChannelPublicKeys, {
475 (0, funding_pubkey, required),
476 (2, revocation_basepoint, required),
477 (4, payment_point, required),
478 (6, delayed_payment_basepoint, required),
479 (8, htlc_basepoint, required),
482 impl TxCreationKeys {
483 /// Create per-state keys from channel base points and the per-commitment point.
484 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
485 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 {
487 per_commitment_point: per_commitment_point.clone(),
488 revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &countersignatory_revocation_base),
489 broadcaster_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_htlc_base),
490 countersignatory_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &countersignatory_htlc_base),
491 broadcaster_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_delayed_payment_base),
495 /// Generate per-state keys from channel static keys.
496 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
497 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 {
498 TxCreationKeys::derive_new(
500 &per_commitment_point,
501 &broadcaster_keys.delayed_payment_basepoint,
502 &broadcaster_keys.htlc_basepoint,
503 &countersignatory_keys.revocation_basepoint,
504 &countersignatory_keys.htlc_basepoint,
509 /// The maximum length of a script returned by get_revokeable_redeemscript.
510 // Calculated as 6 bytes of opcodes, 1 byte push plus 2 bytes for contest_delay, and two public
511 // keys of 33 bytes (+ 1 push).
512 pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 3 + 34*2;
514 /// A script either spendable by the revocation
515 /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
516 /// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
517 pub fn get_revokeable_redeemscript(revocation_key: &PublicKey, contest_delay: u16, broadcaster_delayed_payment_key: &PublicKey) -> Script {
518 let res = Builder::new().push_opcode(opcodes::all::OP_IF)
519 .push_slice(&revocation_key.serialize())
520 .push_opcode(opcodes::all::OP_ELSE)
521 .push_int(contest_delay as i64)
522 .push_opcode(opcodes::all::OP_CSV)
523 .push_opcode(opcodes::all::OP_DROP)
524 .push_slice(&broadcaster_delayed_payment_key.serialize())
525 .push_opcode(opcodes::all::OP_ENDIF)
526 .push_opcode(opcodes::all::OP_CHECKSIG)
528 debug_assert!(res.len() <= REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH);
532 /// Information about an HTLC as it appears in a commitment transaction
533 #[derive(Clone, Debug, PartialEq, Eq)]
534 pub struct HTLCOutputInCommitment {
535 /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
536 /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
537 /// need to compare this value to whether the commitment transaction in question is that of
538 /// the counterparty or our own.
540 /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
541 /// this divided by 1000.
542 pub amount_msat: u64,
543 /// The CLTV lock-time at which this HTLC expires.
544 pub cltv_expiry: u32,
545 /// The hash of the preimage which unlocks this HTLC.
546 pub payment_hash: PaymentHash,
547 /// The position within the commitment transactions' outputs. This may be None if the value is
548 /// below the dust limit (in which case no output appears in the commitment transaction and the
549 /// value is spent to additional transaction fees).
550 pub transaction_output_index: Option<u32>,
553 impl_writeable_tlv_based!(HTLCOutputInCommitment, {
554 (0, offered, required),
555 (2, amount_msat, required),
556 (4, cltv_expiry, required),
557 (6, payment_hash, required),
558 (8, transaction_output_index, option),
562 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 {
563 let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
565 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
566 .push_opcode(opcodes::all::OP_HASH160)
567 .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
568 .push_opcode(opcodes::all::OP_EQUAL)
569 .push_opcode(opcodes::all::OP_IF)
570 .push_opcode(opcodes::all::OP_CHECKSIG)
571 .push_opcode(opcodes::all::OP_ELSE)
572 .push_slice(&countersignatory_htlc_key.serialize()[..])
573 .push_opcode(opcodes::all::OP_SWAP)
574 .push_opcode(opcodes::all::OP_SIZE)
576 .push_opcode(opcodes::all::OP_EQUAL)
577 .push_opcode(opcodes::all::OP_NOTIF)
578 .push_opcode(opcodes::all::OP_DROP)
580 .push_opcode(opcodes::all::OP_SWAP)
581 .push_slice(&broadcaster_htlc_key.serialize()[..])
583 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
584 .push_opcode(opcodes::all::OP_ELSE)
585 .push_opcode(opcodes::all::OP_HASH160)
586 .push_slice(&payment_hash160)
587 .push_opcode(opcodes::all::OP_EQUALVERIFY)
588 .push_opcode(opcodes::all::OP_CHECKSIG)
589 .push_opcode(opcodes::all::OP_ENDIF);
591 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
592 .push_opcode(opcodes::all::OP_CSV)
593 .push_opcode(opcodes::all::OP_DROP);
595 bldr.push_opcode(opcodes::all::OP_ENDIF)
598 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
599 .push_opcode(opcodes::all::OP_HASH160)
600 .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
601 .push_opcode(opcodes::all::OP_EQUAL)
602 .push_opcode(opcodes::all::OP_IF)
603 .push_opcode(opcodes::all::OP_CHECKSIG)
604 .push_opcode(opcodes::all::OP_ELSE)
605 .push_slice(&countersignatory_htlc_key.serialize()[..])
606 .push_opcode(opcodes::all::OP_SWAP)
607 .push_opcode(opcodes::all::OP_SIZE)
609 .push_opcode(opcodes::all::OP_EQUAL)
610 .push_opcode(opcodes::all::OP_IF)
611 .push_opcode(opcodes::all::OP_HASH160)
612 .push_slice(&payment_hash160)
613 .push_opcode(opcodes::all::OP_EQUALVERIFY)
615 .push_opcode(opcodes::all::OP_SWAP)
616 .push_slice(&broadcaster_htlc_key.serialize()[..])
618 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
619 .push_opcode(opcodes::all::OP_ELSE)
620 .push_opcode(opcodes::all::OP_DROP)
621 .push_int(htlc.cltv_expiry as i64)
622 .push_opcode(opcodes::all::OP_CLTV)
623 .push_opcode(opcodes::all::OP_DROP)
624 .push_opcode(opcodes::all::OP_CHECKSIG)
625 .push_opcode(opcodes::all::OP_ENDIF);
627 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
628 .push_opcode(opcodes::all::OP_CSV)
629 .push_opcode(opcodes::all::OP_DROP);
631 bldr.push_opcode(opcodes::all::OP_ENDIF)
636 /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
637 /// does not need to have its previous_output_index filled.
639 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, opt_anchors: bool, keys: &TxCreationKeys) -> Script {
640 get_htlc_redeemscript_with_explicit_keys(htlc, opt_anchors, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
643 /// Gets the redeemscript for a funding output from the two funding public keys.
644 /// Note that the order of funding public keys does not matter.
645 pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> Script {
646 let broadcaster_funding_key = broadcaster.serialize();
647 let countersignatory_funding_key = countersignatory.serialize();
649 let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
650 if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
651 builder.push_slice(&broadcaster_funding_key)
652 .push_slice(&countersignatory_funding_key)
654 builder.push_slice(&countersignatory_funding_key)
655 .push_slice(&broadcaster_funding_key)
656 }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
659 /// Builds an unsigned HTLC-Success or HTLC-Timeout transaction from the given channel and HTLC
660 /// parameters. This is used by [`TrustedCommitmentTransaction::get_htlc_sigs`] to fetch the
661 /// transaction which needs signing, and can be used to construct an HTLC transaction which is
662 /// broadcastable given a counterparty HTLC signature.
664 /// Panics if htlc.transaction_output_index.is_none() (as such HTLCs do not appear in the
665 /// commitment transaction).
666 pub fn build_htlc_transaction(commitment_txid: &Txid, feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, opt_anchors: bool, use_non_zero_fee_anchors: bool, broadcaster_delayed_payment_key: &PublicKey, revocation_key: &PublicKey) -> Transaction {
667 let mut txins: Vec<TxIn> = Vec::new();
669 previous_output: OutPoint {
670 txid: commitment_txid.clone(),
671 vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
673 script_sig: Script::new(),
674 sequence: Sequence(if opt_anchors { 1 } else { 0 }),
675 witness: Witness::new(),
678 let weight = if htlc.offered {
679 htlc_timeout_tx_weight(opt_anchors)
681 htlc_success_tx_weight(opt_anchors)
683 let output_value = if opt_anchors && !use_non_zero_fee_anchors {
684 htlc.amount_msat / 1000
686 let total_fee = feerate_per_kw as u64 * weight / 1000;
687 htlc.amount_msat / 1000 - total_fee
690 let mut txouts: Vec<TxOut> = Vec::new();
692 script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_v0_p2wsh(),
698 lock_time: PackedLockTime(if htlc.offered { htlc.cltv_expiry } else { 0 }),
704 /// Gets the witnessScript for the to_remote output when anchors are enabled.
706 pub(crate) fn get_to_countersignatory_with_anchors_redeemscript(payment_point: &PublicKey) -> Script {
708 .push_slice(&payment_point.serialize()[..])
709 .push_opcode(opcodes::all::OP_CHECKSIGVERIFY)
711 .push_opcode(opcodes::all::OP_CSV)
715 /// Gets the witnessScript for an anchor output from the funding public key.
716 /// The witness in the spending input must be:
717 /// <BIP 143 funding_signature>
718 /// After 16 blocks of confirmation, an alternative satisfying witness could be:
720 /// (empty vector required to satisfy compliance with MINIMALIF-standard rule)
722 pub fn get_anchor_redeemscript(funding_pubkey: &PublicKey) -> Script {
723 Builder::new().push_slice(&funding_pubkey.serialize()[..])
724 .push_opcode(opcodes::all::OP_CHECKSIG)
725 .push_opcode(opcodes::all::OP_IFDUP)
726 .push_opcode(opcodes::all::OP_NOTIF)
728 .push_opcode(opcodes::all::OP_CSV)
729 .push_opcode(opcodes::all::OP_ENDIF)
734 /// Locates the output with an anchor script paying to `funding_pubkey` within `commitment_tx`.
735 pub(crate) fn get_anchor_output<'a>(commitment_tx: &'a Transaction, funding_pubkey: &PublicKey) -> Option<(u32, &'a TxOut)> {
736 let anchor_script = chan_utils::get_anchor_redeemscript(funding_pubkey).to_v0_p2wsh();
737 commitment_tx.output.iter().enumerate()
738 .find(|(_, txout)| txout.script_pubkey == anchor_script)
739 .map(|(idx, txout)| (idx as u32, txout))
742 /// Returns the witness required to satisfy and spend an anchor input.
743 pub fn build_anchor_input_witness(funding_key: &PublicKey, funding_sig: &Signature) -> Witness {
744 let anchor_redeem_script = chan_utils::get_anchor_redeemscript(funding_key);
745 let mut funding_sig = funding_sig.serialize_der().to_vec();
746 funding_sig.push(EcdsaSighashType::All as u8);
747 Witness::from_vec(vec![funding_sig, anchor_redeem_script.to_bytes()])
750 /// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
751 /// The fields are organized by holder/counterparty.
753 /// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
754 /// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
756 pub struct ChannelTransactionParameters {
757 /// Holder public keys
758 pub holder_pubkeys: ChannelPublicKeys,
759 /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
760 pub holder_selected_contest_delay: u16,
761 /// Whether the holder is the initiator of this channel.
762 /// This is an input to the commitment number obscure factor computation.
763 pub is_outbound_from_holder: bool,
764 /// The late-bound counterparty channel transaction parameters.
765 /// These parameters are populated at the point in the protocol where the counterparty provides them.
766 pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
767 /// The late-bound funding outpoint
768 pub funding_outpoint: Option<chain::transaction::OutPoint>,
769 /// Are anchors (zero fee HTLC transaction variant) used for this channel. Boolean is
770 /// serialization backwards-compatible.
771 pub opt_anchors: Option<()>,
772 /// Are non-zero-fee anchors are enabled (used in conjuction with opt_anchors)
773 /// It is intended merely for backwards compatibility with signers that need it.
774 /// There is no support for this feature in LDK channel negotiation.
775 pub opt_non_zero_fee_anchors: Option<()>,
778 /// Late-bound per-channel counterparty data used to build transactions.
780 pub struct CounterpartyChannelTransactionParameters {
781 /// Counter-party public keys
782 pub pubkeys: ChannelPublicKeys,
783 /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
784 pub selected_contest_delay: u16,
787 impl ChannelTransactionParameters {
788 /// Whether the late bound parameters are populated.
789 pub fn is_populated(&self) -> bool {
790 self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
793 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
794 /// given that the holder is the broadcaster.
796 /// self.is_populated() must be true before calling this function.
797 pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
798 assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
799 DirectedChannelTransactionParameters {
801 holder_is_broadcaster: true
805 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
806 /// given that the counterparty is the broadcaster.
808 /// self.is_populated() must be true before calling this function.
809 pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
810 assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
811 DirectedChannelTransactionParameters {
813 holder_is_broadcaster: false
818 impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, {
819 (0, pubkeys, required),
820 (2, selected_contest_delay, required),
823 impl_writeable_tlv_based!(ChannelTransactionParameters, {
824 (0, holder_pubkeys, required),
825 (2, holder_selected_contest_delay, required),
826 (4, is_outbound_from_holder, required),
827 (6, counterparty_parameters, option),
828 (8, funding_outpoint, option),
829 (10, opt_anchors, option),
830 (12, opt_non_zero_fee_anchors, option),
833 /// Static channel fields used to build transactions given per-commitment fields, organized by
834 /// broadcaster/countersignatory.
836 /// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
837 /// as_holder_broadcastable and as_counterparty_broadcastable functions.
838 pub struct DirectedChannelTransactionParameters<'a> {
839 /// The holder's channel static parameters
840 inner: &'a ChannelTransactionParameters,
841 /// Whether the holder is the broadcaster
842 holder_is_broadcaster: bool,
845 impl<'a> DirectedChannelTransactionParameters<'a> {
846 /// Get the channel pubkeys for the broadcaster
847 pub fn broadcaster_pubkeys(&self) -> &ChannelPublicKeys {
848 if self.holder_is_broadcaster {
849 &self.inner.holder_pubkeys
851 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
855 /// Get the channel pubkeys for the countersignatory
856 pub fn countersignatory_pubkeys(&self) -> &ChannelPublicKeys {
857 if self.holder_is_broadcaster {
858 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
860 &self.inner.holder_pubkeys
864 /// Get the contest delay applicable to the transactions.
865 /// Note that the contest delay was selected by the countersignatory.
866 pub fn contest_delay(&self) -> u16 {
867 let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
868 if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
871 /// Whether the channel is outbound from the broadcaster.
873 /// The boolean representing the side that initiated the channel is
874 /// an input to the commitment number obscure factor computation.
875 pub fn is_outbound(&self) -> bool {
876 if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
879 /// The funding outpoint
880 pub fn funding_outpoint(&self) -> OutPoint {
881 self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
884 /// Whether to use anchors for this channel
885 pub fn opt_anchors(&self) -> bool {
886 self.inner.opt_anchors.is_some()
890 /// Information needed to build and sign a holder's commitment transaction.
892 /// The transaction is only signed once we are ready to broadcast.
894 pub struct HolderCommitmentTransaction {
895 inner: CommitmentTransaction,
896 /// Our counterparty's signature for the transaction
897 pub counterparty_sig: Signature,
898 /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
899 pub counterparty_htlc_sigs: Vec<Signature>,
900 // Which order the signatures should go in when constructing the final commitment tx witness.
901 // The user should be able to reconstruct this themselves, so we don't bother to expose it.
902 holder_sig_first: bool,
905 impl Deref for HolderCommitmentTransaction {
906 type Target = CommitmentTransaction;
908 fn deref(&self) -> &Self::Target { &self.inner }
911 impl Eq for HolderCommitmentTransaction {}
912 impl PartialEq for HolderCommitmentTransaction {
913 // We dont care whether we are signed in equality comparison
914 fn eq(&self, o: &Self) -> bool {
915 self.inner == o.inner
919 impl_writeable_tlv_based!(HolderCommitmentTransaction, {
920 (0, inner, required),
921 (2, counterparty_sig, required),
922 (4, holder_sig_first, required),
923 (6, counterparty_htlc_sigs, vec_type),
926 impl HolderCommitmentTransaction {
928 pub fn dummy() -> Self {
929 let secp_ctx = Secp256k1::new();
930 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
931 let dummy_sig = sign(&secp_ctx, &secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
933 let keys = TxCreationKeys {
934 per_commitment_point: dummy_key.clone(),
935 revocation_key: dummy_key.clone(),
936 broadcaster_htlc_key: dummy_key.clone(),
937 countersignatory_htlc_key: dummy_key.clone(),
938 broadcaster_delayed_payment_key: dummy_key.clone(),
940 let channel_pubkeys = ChannelPublicKeys {
941 funding_pubkey: dummy_key.clone(),
942 revocation_basepoint: dummy_key.clone(),
943 payment_point: dummy_key.clone(),
944 delayed_payment_basepoint: dummy_key.clone(),
945 htlc_basepoint: dummy_key.clone()
947 let channel_parameters = ChannelTransactionParameters {
948 holder_pubkeys: channel_pubkeys.clone(),
949 holder_selected_contest_delay: 0,
950 is_outbound_from_holder: false,
951 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
952 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
954 opt_non_zero_fee_anchors: None,
956 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
957 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());
958 HolderCommitmentTransaction {
960 counterparty_sig: dummy_sig,
961 counterparty_htlc_sigs: Vec::new(),
962 holder_sig_first: false
966 /// Create a new holder transaction with the given counterparty signatures.
967 /// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
968 pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
970 inner: commitment_tx,
972 counterparty_htlc_sigs,
973 holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
977 pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
978 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
979 let mut tx = self.inner.built.transaction.clone();
980 tx.input[0].witness.push(Vec::new());
981 let mut ser_holder_sig = holder_sig.serialize_der().to_vec();
982 ser_holder_sig.push(EcdsaSighashType::All as u8);
983 let mut ser_cp_sig = self.counterparty_sig.serialize_der().to_vec();
984 ser_cp_sig.push(EcdsaSighashType::All as u8);
986 if self.holder_sig_first {
987 tx.input[0].witness.push(ser_holder_sig);
988 tx.input[0].witness.push(ser_cp_sig);
990 tx.input[0].witness.push(ser_cp_sig);
991 tx.input[0].witness.push(ser_holder_sig);
994 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
999 /// A pre-built Bitcoin commitment transaction and its txid.
1001 pub struct BuiltCommitmentTransaction {
1002 /// The commitment transaction
1003 pub transaction: Transaction,
1004 /// The txid for the commitment transaction.
1006 /// This is provided as a performance optimization, instead of calling transaction.txid()
1011 impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
1012 (0, transaction, required),
1013 (2, txid, required),
1016 impl BuiltCommitmentTransaction {
1017 /// Get the SIGHASH_ALL sighash value of the transaction.
1019 /// This can be used to verify a signature.
1020 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1021 let sighash = &sighash::SighashCache::new(&self.transaction).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1022 hash_to_message!(sighash)
1025 /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1026 /// because we are about to broadcast a holder transaction.
1027 pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1028 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1029 sign(secp_ctx, &sighash, funding_key)
1033 /// This class tracks the per-transaction information needed to build a closing transaction and will
1034 /// actually build it and sign.
1036 /// This class can be used inside a signer implementation to generate a signature given the relevant
1038 #[derive(Clone, Hash, PartialEq, Eq)]
1039 pub struct ClosingTransaction {
1040 to_holder_value_sat: u64,
1041 to_counterparty_value_sat: u64,
1042 to_holder_script: Script,
1043 to_counterparty_script: Script,
1047 impl ClosingTransaction {
1048 /// Construct an object of the class
1050 to_holder_value_sat: u64,
1051 to_counterparty_value_sat: u64,
1052 to_holder_script: Script,
1053 to_counterparty_script: Script,
1054 funding_outpoint: OutPoint,
1056 let built = build_closing_transaction(
1057 to_holder_value_sat, to_counterparty_value_sat,
1058 to_holder_script.clone(), to_counterparty_script.clone(),
1061 ClosingTransaction {
1062 to_holder_value_sat,
1063 to_counterparty_value_sat,
1065 to_counterparty_script,
1070 /// Trust our pre-built transaction.
1072 /// Applies a wrapper which allows access to the transaction.
1074 /// This should only be used if you fully trust the builder of this object. It should not
1075 /// be used by an external signer - instead use the verify function.
1076 pub fn trust(&self) -> TrustedClosingTransaction {
1077 TrustedClosingTransaction { inner: self }
1080 /// Verify our pre-built transaction.
1082 /// Applies a wrapper which allows access to the transaction.
1084 /// An external validating signer must call this method before signing
1085 /// or using the built transaction.
1086 pub fn verify(&self, funding_outpoint: OutPoint) -> Result<TrustedClosingTransaction, ()> {
1087 let built = build_closing_transaction(
1088 self.to_holder_value_sat, self.to_counterparty_value_sat,
1089 self.to_holder_script.clone(), self.to_counterparty_script.clone(),
1092 if self.built != built {
1095 Ok(TrustedClosingTransaction { inner: self })
1098 /// The value to be sent to the holder, or zero if the output will be omitted
1099 pub fn to_holder_value_sat(&self) -> u64 {
1100 self.to_holder_value_sat
1103 /// The value to be sent to the counterparty, or zero if the output will be omitted
1104 pub fn to_counterparty_value_sat(&self) -> u64 {
1105 self.to_counterparty_value_sat
1108 /// The destination of the holder's output
1109 pub fn to_holder_script(&self) -> &Script {
1110 &self.to_holder_script
1113 /// The destination of the counterparty's output
1114 pub fn to_counterparty_script(&self) -> &Script {
1115 &self.to_counterparty_script
1119 /// A wrapper on ClosingTransaction indicating that the built bitcoin
1120 /// transaction is trusted.
1122 /// See trust() and verify() functions on CommitmentTransaction.
1124 /// This structure implements Deref.
1125 pub struct TrustedClosingTransaction<'a> {
1126 inner: &'a ClosingTransaction,
1129 impl<'a> Deref for TrustedClosingTransaction<'a> {
1130 type Target = ClosingTransaction;
1132 fn deref(&self) -> &Self::Target { self.inner }
1135 impl<'a> TrustedClosingTransaction<'a> {
1136 /// The pre-built Bitcoin commitment transaction
1137 pub fn built_transaction(&self) -> &Transaction {
1141 /// Get the SIGHASH_ALL sighash value of the transaction.
1143 /// This can be used to verify a signature.
1144 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1145 let sighash = &sighash::SighashCache::new(&self.inner.built).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1146 hash_to_message!(sighash)
1149 /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1150 /// because we are about to broadcast a holder transaction.
1151 pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1152 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1153 sign(secp_ctx, &sighash, funding_key)
1157 /// This class tracks the per-transaction information needed to build a commitment transaction and will
1158 /// actually build it and sign. It is used for holder transactions that we sign only when needed
1159 /// and for transactions we sign for the counterparty.
1161 /// This class can be used inside a signer implementation to generate a signature given the relevant
1164 pub struct CommitmentTransaction {
1165 commitment_number: u64,
1166 to_broadcaster_value_sat: u64,
1167 to_countersignatory_value_sat: u64,
1168 feerate_per_kw: u32,
1169 htlcs: Vec<HTLCOutputInCommitment>,
1170 // A boolean that is serialization backwards-compatible
1171 opt_anchors: Option<()>,
1172 // Whether non-zero-fee anchors should be used
1173 opt_non_zero_fee_anchors: Option<()>,
1174 // A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
1175 keys: TxCreationKeys,
1176 // For access to the pre-built transaction, see doc for trust()
1177 built: BuiltCommitmentTransaction,
1180 impl Eq for CommitmentTransaction {}
1181 impl PartialEq for CommitmentTransaction {
1182 fn eq(&self, o: &Self) -> bool {
1183 let eq = self.commitment_number == o.commitment_number &&
1184 self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
1185 self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
1186 self.feerate_per_kw == o.feerate_per_kw &&
1187 self.htlcs == o.htlcs &&
1188 self.opt_anchors == o.opt_anchors &&
1189 self.keys == o.keys;
1191 debug_assert_eq!(self.built.transaction, o.built.transaction);
1192 debug_assert_eq!(self.built.txid, o.built.txid);
1198 impl_writeable_tlv_based!(CommitmentTransaction, {
1199 (0, commitment_number, required),
1200 (2, to_broadcaster_value_sat, required),
1201 (4, to_countersignatory_value_sat, required),
1202 (6, feerate_per_kw, required),
1203 (8, keys, required),
1204 (10, built, required),
1205 (12, htlcs, vec_type),
1206 (14, opt_anchors, option),
1207 (16, opt_non_zero_fee_anchors, option),
1210 impl CommitmentTransaction {
1211 /// Construct an object of the class while assigning transaction output indices to HTLCs.
1213 /// Populates HTLCOutputInCommitment.transaction_output_index in htlcs_with_aux.
1215 /// The generic T allows the caller to match the HTLC output index with auxiliary data.
1216 /// This auxiliary data is not stored in this object.
1218 /// Only include HTLCs that are above the dust limit for the channel.
1220 /// (C-not exported) due to the generic though we likely should expose a version without
1221 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 {
1222 // Sort outputs and populate output indices while keeping track of the auxiliary data
1223 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();
1225 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
1226 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1227 let txid = transaction.txid();
1228 CommitmentTransaction {
1230 to_broadcaster_value_sat,
1231 to_countersignatory_value_sat,
1234 opt_anchors: if opt_anchors { Some(()) } else { None },
1236 built: BuiltCommitmentTransaction {
1240 opt_non_zero_fee_anchors: None,
1244 /// Use non-zero fee anchors
1246 /// (C-not exported) due to move, and also not likely to be useful for binding users
1247 pub fn with_non_zero_fee_anchors(mut self) -> Self {
1248 self.opt_non_zero_fee_anchors = Some(());
1252 fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<BuiltCommitmentTransaction, ()> {
1253 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
1255 let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
1256 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)?;
1258 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1259 let txid = transaction.txid();
1260 let built_transaction = BuiltCommitmentTransaction {
1264 Ok(built_transaction)
1267 fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
1270 lock_time: PackedLockTime(((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32)),
1276 // This is used in two cases:
1277 // - initial sorting of outputs / HTLCs in the constructor, in which case T is auxiliary data the
1278 // caller needs to have sorted together with the HTLCs so it can keep track of the output index
1279 // - building of a bitcoin transaction during a verify() call, in which case T is just ()
1280 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>), ()> {
1281 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1282 let contest_delay = channel_parameters.contest_delay();
1284 let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
1286 if to_countersignatory_value_sat > 0 {
1287 let script = if opt_anchors {
1288 get_to_countersignatory_with_anchors_redeemscript(&countersignatory_pubkeys.payment_point).to_v0_p2wsh()
1290 get_p2wpkh_redeemscript(&countersignatory_pubkeys.payment_point)
1294 script_pubkey: script.clone(),
1295 value: to_countersignatory_value_sat,
1301 if to_broadcaster_value_sat > 0 {
1302 let redeem_script = get_revokeable_redeemscript(
1303 &keys.revocation_key,
1305 &keys.broadcaster_delayed_payment_key,
1309 script_pubkey: redeem_script.to_v0_p2wsh(),
1310 value: to_broadcaster_value_sat,
1317 if to_broadcaster_value_sat > 0 || !htlcs_with_aux.is_empty() {
1318 let anchor_script = get_anchor_redeemscript(broadcaster_funding_key);
1321 script_pubkey: anchor_script.to_v0_p2wsh(),
1322 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1328 if to_countersignatory_value_sat > 0 || !htlcs_with_aux.is_empty() {
1329 let anchor_script = get_anchor_redeemscript(countersignatory_funding_key);
1332 script_pubkey: anchor_script.to_v0_p2wsh(),
1333 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1340 let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
1341 for (htlc, _) in htlcs_with_aux {
1342 let script = chan_utils::get_htlc_redeemscript(&htlc, opt_anchors, &keys);
1344 script_pubkey: script.to_v0_p2wsh(),
1345 value: htlc.amount_msat / 1000,
1347 txouts.push((txout, Some(htlc)));
1350 // Sort output in BIP-69 order (amount, scriptPubkey). Tie-breaks based on HTLC
1351 // CLTV expiration height.
1352 sort_outputs(&mut txouts, |a, b| {
1353 if let &Some(ref a_htlcout) = a {
1354 if let &Some(ref b_htlcout) = b {
1355 a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
1356 // Note that due to hash collisions, we have to have a fallback comparison
1357 // here for fuzzing mode (otherwise at least chanmon_fail_consistency
1359 .then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
1360 // For non-HTLC outputs, if they're copying our SPK we don't really care if we
1361 // close the channel due to mismatches - they're doing something dumb:
1362 } else { cmp::Ordering::Equal }
1363 } else { cmp::Ordering::Equal }
1366 let mut outputs = Vec::with_capacity(txouts.len());
1367 for (idx, out) in txouts.drain(..).enumerate() {
1368 if let Some(htlc) = out.1 {
1369 htlc.transaction_output_index = Some(idx as u32);
1370 htlcs.push(htlc.clone());
1372 outputs.push(out.0);
1374 Ok((outputs, htlcs))
1377 fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
1378 let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
1379 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1380 let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
1381 &broadcaster_pubkeys.payment_point,
1382 &countersignatory_pubkeys.payment_point,
1383 channel_parameters.is_outbound(),
1386 let obscured_commitment_transaction_number =
1387 commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
1390 let mut ins: Vec<TxIn> = Vec::new();
1392 previous_output: channel_parameters.funding_outpoint(),
1393 script_sig: Script::new(),
1394 sequence: Sequence(((0x80 as u32) << 8 * 3)
1395 | ((obscured_commitment_transaction_number >> 3 * 8) as u32)),
1396 witness: Witness::new(),
1400 (obscured_commitment_transaction_number, txins)
1403 /// The backwards-counting commitment number
1404 pub fn commitment_number(&self) -> u64 {
1405 self.commitment_number
1408 /// The value to be sent to the broadcaster
1409 pub fn to_broadcaster_value_sat(&self) -> u64 {
1410 self.to_broadcaster_value_sat
1413 /// The value to be sent to the counterparty
1414 pub fn to_countersignatory_value_sat(&self) -> u64 {
1415 self.to_countersignatory_value_sat
1418 /// The feerate paid per 1000-weight-unit in this commitment transaction.
1419 pub fn feerate_per_kw(&self) -> u32 {
1423 /// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
1424 /// which were included in this commitment transaction in output order.
1425 /// The transaction index is always populated.
1427 /// (C-not exported) as we cannot currently convert Vec references to/from C, though we should
1428 /// expose a less effecient version which creates a Vec of references in the future.
1429 pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
1433 /// Trust our pre-built transaction and derived transaction creation public keys.
1435 /// Applies a wrapper which allows access to these fields.
1437 /// This should only be used if you fully trust the builder of this object. It should not
1438 /// be used by an external signer - instead use the verify function.
1439 pub fn trust(&self) -> TrustedCommitmentTransaction {
1440 TrustedCommitmentTransaction { inner: self }
1443 /// Verify our pre-built transaction and derived transaction creation public keys.
1445 /// Applies a wrapper which allows access to these fields.
1447 /// An external validating signer must call this method before signing
1448 /// or using the built transaction.
1449 pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
1450 // This is the only field of the key cache that we trust
1451 let per_commitment_point = self.keys.per_commitment_point;
1452 let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx);
1453 if keys != self.keys {
1456 let tx = self.internal_rebuild_transaction(&keys, channel_parameters, &broadcaster_keys.funding_pubkey, &countersignatory_keys.funding_pubkey)?;
1457 if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
1460 Ok(TrustedCommitmentTransaction { inner: self })
1464 /// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
1465 /// transaction and the transaction creation keys) are trusted.
1467 /// See trust() and verify() functions on CommitmentTransaction.
1469 /// This structure implements Deref.
1470 pub struct TrustedCommitmentTransaction<'a> {
1471 inner: &'a CommitmentTransaction,
1474 impl<'a> Deref for TrustedCommitmentTransaction<'a> {
1475 type Target = CommitmentTransaction;
1477 fn deref(&self) -> &Self::Target { self.inner }
1480 impl<'a> TrustedCommitmentTransaction<'a> {
1481 /// The transaction ID of the built Bitcoin transaction
1482 pub fn txid(&self) -> Txid {
1483 self.inner.built.txid
1486 /// The pre-built Bitcoin commitment transaction
1487 pub fn built_transaction(&self) -> &BuiltCommitmentTransaction {
1491 /// The pre-calculated transaction creation public keys.
1492 pub fn keys(&self) -> &TxCreationKeys {
1496 /// Should anchors be used.
1497 pub fn opt_anchors(&self) -> bool {
1498 self.opt_anchors.is_some()
1501 /// Get a signature for each HTLC which was included in the commitment transaction (ie for
1502 /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
1504 /// The returned Vec has one entry for each HTLC, and in the same order.
1506 /// This function is only valid in the holder commitment context, it always uses EcdsaSighashType::All.
1507 pub fn get_htlc_sigs<T: secp256k1::Signing>(&self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters, secp_ctx: &Secp256k1<T>) -> Result<Vec<Signature>, ()> {
1508 let inner = self.inner;
1509 let keys = &inner.keys;
1510 let txid = inner.built.txid;
1511 let mut ret = Vec::with_capacity(inner.htlcs.len());
1512 let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key);
1514 for this_htlc in inner.htlcs.iter() {
1515 assert!(this_htlc.transaction_output_index.is_some());
1516 let htlc_tx = build_htlc_transaction(&txid, inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc, self.opt_anchors(), self.opt_non_zero_fee_anchors.is_some(), &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
1518 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);
1520 let sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, EcdsaSighashType::All).unwrap()[..]);
1521 ret.push(sign(secp_ctx, &sighash, &holder_htlc_key));
1526 /// Gets a signed HTLC transaction given a preimage (for !htlc.offered) and the holder HTLC transaction signature.
1527 pub(crate) fn get_signed_htlc_tx(&self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature, preimage: &Option<PaymentPreimage>) -> Transaction {
1528 let inner = self.inner;
1529 let keys = &inner.keys;
1530 let txid = inner.built.txid;
1531 let this_htlc = &inner.htlcs[htlc_index];
1532 assert!(this_htlc.transaction_output_index.is_some());
1533 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
1534 if !this_htlc.offered && preimage.is_none() { unreachable!(); }
1535 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
1536 if this_htlc.offered && preimage.is_some() { unreachable!(); }
1538 let mut htlc_tx = build_htlc_transaction(&txid, inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc, self.opt_anchors(), self.opt_non_zero_fee_anchors.is_some(), &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
1540 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);
1542 let sighashtype = if self.opt_anchors() { EcdsaSighashType::SinglePlusAnyoneCanPay } else { EcdsaSighashType::All };
1544 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
1545 htlc_tx.input[0].witness.push(Vec::new());
1547 let mut cp_sig_ser = counterparty_signature.serialize_der().to_vec();
1548 cp_sig_ser.push(sighashtype as u8);
1549 htlc_tx.input[0].witness.push(cp_sig_ser);
1550 let mut holder_sig_ser = signature.serialize_der().to_vec();
1551 holder_sig_ser.push(EcdsaSighashType::All as u8);
1552 htlc_tx.input[0].witness.push(holder_sig_ser);
1554 if this_htlc.offered {
1555 // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
1556 htlc_tx.input[0].witness.push(Vec::new());
1558 htlc_tx.input[0].witness.push(preimage.unwrap().0.to_vec());
1561 htlc_tx.input[0].witness.push(htlc_redeemscript.as_bytes().to_vec());
1566 /// Commitment transaction numbers which appear in the transactions themselves are XOR'd with a
1567 /// shared secret first. This prevents on-chain observers from discovering how many commitment
1568 /// transactions occurred in a channel before it was closed.
1570 /// This function gets the shared secret from relevant channel public keys and can be used to
1571 /// "decrypt" the commitment transaction number given a commitment transaction on-chain.
1572 pub fn get_commitment_transaction_number_obscure_factor(
1573 broadcaster_payment_basepoint: &PublicKey,
1574 countersignatory_payment_basepoint: &PublicKey,
1575 outbound_from_broadcaster: bool,
1577 let mut sha = Sha256::engine();
1579 if outbound_from_broadcaster {
1580 sha.input(&broadcaster_payment_basepoint.serialize());
1581 sha.input(&countersignatory_payment_basepoint.serialize());
1583 sha.input(&countersignatory_payment_basepoint.serialize());
1584 sha.input(&broadcaster_payment_basepoint.serialize());
1586 let res = Sha256::from_engine(sha).into_inner();
1588 ((res[26] as u64) << 5 * 8)
1589 | ((res[27] as u64) << 4 * 8)
1590 | ((res[28] as u64) << 3 * 8)
1591 | ((res[29] as u64) << 2 * 8)
1592 | ((res[30] as u64) << 1 * 8)
1593 | ((res[31] as u64) << 0 * 8)
1596 fn get_p2wpkh_redeemscript(key: &PublicKey) -> Script {
1597 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1598 .push_slice(&WPubkeyHash::hash(&key.serialize())[..])
1604 use super::CounterpartyCommitmentSecrets;
1605 use crate::{hex, chain};
1606 use crate::prelude::*;
1607 use crate::ln::chan_utils::{get_htlc_redeemscript, get_to_countersignatory_with_anchors_redeemscript, get_p2wpkh_redeemscript, CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
1608 use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
1609 use crate::util::test_utils;
1610 use crate::chain::keysinterface::{KeysInterface, BaseSign};
1611 use bitcoin::{Network, Txid};
1612 use bitcoin::hashes::Hash;
1613 use crate::ln::PaymentHash;
1614 use bitcoin::hashes::hex::ToHex;
1618 let secp_ctx = Secp256k1::new();
1620 let seed = [42; 32];
1621 let network = Network::Testnet;
1622 let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
1623 let signer = keys_provider.get_channel_signer(false, 3000);
1624 let counterparty_signer = keys_provider.get_channel_signer(false, 3000);
1625 let delayed_payment_base = &signer.pubkeys().delayed_payment_basepoint;
1626 let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
1627 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
1628 let htlc_basepoint = &signer.pubkeys().htlc_basepoint;
1629 let holder_pubkeys = signer.pubkeys();
1630 let counterparty_pubkeys = counterparty_signer.pubkeys();
1631 let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint);
1632 let mut channel_parameters = ChannelTransactionParameters {
1633 holder_pubkeys: holder_pubkeys.clone(),
1634 holder_selected_contest_delay: 0,
1635 is_outbound_from_holder: false,
1636 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: counterparty_pubkeys.clone(), selected_contest_delay: 0 }),
1637 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1639 opt_non_zero_fee_anchors: None,
1642 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
1644 // Generate broadcaster and counterparty outputs
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(), 2);
1654 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_p2wpkh_redeemscript(&counterparty_pubkeys.payment_point));
1656 // Generate broadcaster and counterparty outputs as well as two anchors
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(), 4);
1666 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_to_countersignatory_with_anchors_redeemscript(&counterparty_pubkeys.payment_point).to_v0_p2wsh());
1668 // Generate broadcaster output and anchor
1669 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1672 holder_pubkeys.funding_pubkey,
1673 counterparty_pubkeys.funding_pubkey,
1675 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1677 assert_eq!(tx.built.transaction.output.len(), 2);
1679 // Generate counterparty output and anchor
1680 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1683 holder_pubkeys.funding_pubkey,
1684 counterparty_pubkeys.funding_pubkey,
1686 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1688 assert_eq!(tx.built.transaction.output.len(), 2);
1690 let received_htlc = HTLCOutputInCommitment {
1692 amount_msat: 400000,
1694 payment_hash: PaymentHash([42; 32]),
1695 transaction_output_index: None,
1698 let offered_htlc = HTLCOutputInCommitment {
1700 amount_msat: 600000,
1702 payment_hash: PaymentHash([43; 32]),
1703 transaction_output_index: None,
1706 // Generate broadcaster output and received and offered HTLC outputs, w/o anchors
1707 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1710 holder_pubkeys.funding_pubkey,
1711 counterparty_pubkeys.funding_pubkey,
1713 &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1714 &channel_parameters.as_holder_broadcastable()
1716 assert_eq!(tx.built.transaction.output.len(), 3);
1717 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_htlc_redeemscript(&received_htlc, false, &keys).to_v0_p2wsh());
1718 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&offered_htlc, false, &keys).to_v0_p2wsh());
1719 assert_eq!(get_htlc_redeemscript(&received_htlc, false, &keys).to_v0_p2wsh().to_hex(),
1720 "002085cf52e41ba7c099a39df504e7b61f6de122971ceb53b06731876eaeb85e8dc5");
1721 assert_eq!(get_htlc_redeemscript(&offered_htlc, false, &keys).to_v0_p2wsh().to_hex(),
1722 "002049f0736bb335c61a04d2623a24df878a7592a3c51fa7258d41b2c85318265e73");
1724 // Generate broadcaster output and received and offered HTLC outputs, with anchors
1725 channel_parameters.opt_anchors = Some(());
1726 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1729 holder_pubkeys.funding_pubkey,
1730 counterparty_pubkeys.funding_pubkey,
1732 &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1733 &channel_parameters.as_holder_broadcastable()
1735 assert_eq!(tx.built.transaction.output.len(), 5);
1736 assert_eq!(tx.built.transaction.output[2].script_pubkey, get_htlc_redeemscript(&received_htlc, true, &keys).to_v0_p2wsh());
1737 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_htlc_redeemscript(&offered_htlc, true, &keys).to_v0_p2wsh());
1738 assert_eq!(get_htlc_redeemscript(&received_htlc, true, &keys).to_v0_p2wsh().to_hex(),
1739 "002067114123af3f95405bae4fd930fc95de03e3c86baaee8b2dd29b43dd26cf613c");
1740 assert_eq!(get_htlc_redeemscript(&offered_htlc, true, &keys).to_v0_p2wsh().to_hex(),
1741 "0020a06e3b0d4fcf704f2b9c41e16a70099e39989466c3142b8573a1154542f28f57");
1745 fn test_per_commitment_storage() {
1746 // Test vectors from BOLT 3:
1747 let mut secrets: Vec<[u8; 32]> = Vec::new();
1750 macro_rules! test_secrets {
1752 let mut idx = 281474976710655;
1753 for secret in secrets.iter() {
1754 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1757 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1758 assert!(monitor.get_secret(idx).is_none());
1763 // insert_secret correct sequence
1764 monitor = CounterpartyCommitmentSecrets::new();
1767 secrets.push([0; 32]);
1768 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1769 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1772 secrets.push([0; 32]);
1773 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1774 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1777 secrets.push([0; 32]);
1778 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1779 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1782 secrets.push([0; 32]);
1783 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1784 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1787 secrets.push([0; 32]);
1788 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1789 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1792 secrets.push([0; 32]);
1793 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1794 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1797 secrets.push([0; 32]);
1798 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1799 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1802 secrets.push([0; 32]);
1803 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1804 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
1809 // insert_secret #1 incorrect
1810 monitor = CounterpartyCommitmentSecrets::new();
1813 secrets.push([0; 32]);
1814 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1815 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1818 secrets.push([0; 32]);
1819 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1820 assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
1824 // insert_secret #2 incorrect (#1 derived from incorrect)
1825 monitor = CounterpartyCommitmentSecrets::new();
1828 secrets.push([0; 32]);
1829 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1830 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1833 secrets.push([0; 32]);
1834 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1835 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1838 secrets.push([0; 32]);
1839 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1840 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1843 secrets.push([0; 32]);
1844 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1845 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1849 // insert_secret #3 incorrect
1850 monitor = CounterpartyCommitmentSecrets::new();
1853 secrets.push([0; 32]);
1854 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1855 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1858 secrets.push([0; 32]);
1859 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1860 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1863 secrets.push([0; 32]);
1864 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1865 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1868 secrets.push([0; 32]);
1869 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1870 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1874 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
1875 monitor = CounterpartyCommitmentSecrets::new();
1878 secrets.push([0; 32]);
1879 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1880 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1883 secrets.push([0; 32]);
1884 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1885 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1888 secrets.push([0; 32]);
1889 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1890 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1893 secrets.push([0; 32]);
1894 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
1895 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1898 secrets.push([0; 32]);
1899 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1900 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1903 secrets.push([0; 32]);
1904 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1905 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1908 secrets.push([0; 32]);
1909 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1910 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1913 secrets.push([0; 32]);
1914 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1915 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1919 // insert_secret #5 incorrect
1920 monitor = CounterpartyCommitmentSecrets::new();
1923 secrets.push([0; 32]);
1924 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1925 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1928 secrets.push([0; 32]);
1929 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1930 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1933 secrets.push([0; 32]);
1934 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1935 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1938 secrets.push([0; 32]);
1939 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1940 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1943 secrets.push([0; 32]);
1944 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1945 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1948 secrets.push([0; 32]);
1949 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1950 assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
1954 // insert_secret #6 incorrect (5 derived from incorrect)
1955 monitor = CounterpartyCommitmentSecrets::new();
1958 secrets.push([0; 32]);
1959 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1960 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1963 secrets.push([0; 32]);
1964 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1965 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1968 secrets.push([0; 32]);
1969 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1970 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1973 secrets.push([0; 32]);
1974 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1975 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1978 secrets.push([0; 32]);
1979 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1980 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1983 secrets.push([0; 32]);
1984 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
1985 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1988 secrets.push([0; 32]);
1989 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1990 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1993 secrets.push([0; 32]);
1994 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1995 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1999 // insert_secret #7 incorrect
2000 monitor = CounterpartyCommitmentSecrets::new();
2003 secrets.push([0; 32]);
2004 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2005 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2008 secrets.push([0; 32]);
2009 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2010 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2013 secrets.push([0; 32]);
2014 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2015 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2018 secrets.push([0; 32]);
2019 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2020 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2023 secrets.push([0; 32]);
2024 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2025 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2028 secrets.push([0; 32]);
2029 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2030 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2033 secrets.push([0; 32]);
2034 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2035 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2038 secrets.push([0; 32]);
2039 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2040 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2044 // insert_secret #8 incorrect
2045 monitor = CounterpartyCommitmentSecrets::new();
2048 secrets.push([0; 32]);
2049 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2050 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2053 secrets.push([0; 32]);
2054 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2055 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2058 secrets.push([0; 32]);
2059 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2060 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2063 secrets.push([0; 32]);
2064 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2065 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2068 secrets.push([0; 32]);
2069 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2070 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2073 secrets.push([0; 32]);
2074 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2075 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2078 secrets.push([0; 32]);
2079 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2080 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2083 secrets.push([0; 32]);
2084 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2085 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());