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 the traits on [`chain::keysinterface`] 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::transaction_utils;
29 use bitcoin::secp256k1::{SecretKey, PublicKey, Scalar};
30 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature, Message};
31 use bitcoin::{PackedLockTime, secp256k1, Sequence, Witness};
32 use bitcoin::PublicKey as BitcoinPublicKey;
35 use crate::prelude::*;
37 use crate::ln::chan_utils;
38 use crate::util::transaction_utils::sort_outputs;
39 use crate::ln::channel::{INITIAL_COMMITMENT_NUMBER, ANCHOR_OUTPUT_VALUE_SATOSHI};
42 use crate::util::crypto::sign;
44 /// Maximum number of one-way in-flight HTLC (protocol-level value).
45 pub const MAX_HTLCS: u16 = 483;
46 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, non-anchor variant.
47 pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
48 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, anchor variant.
49 pub const OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS: usize = 136;
51 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
52 /// We define a range that encompasses both its non-anchors and anchors variants.
53 pub(crate) const MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 136;
54 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
55 /// We define a range that encompasses both its non-anchors and anchors variants.
56 /// This is the maximum post-anchor value.
57 pub const MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 143;
59 /// Gets the weight for an HTLC-Success transaction.
61 pub fn htlc_success_tx_weight(opt_anchors: bool) -> u64 {
62 const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
63 const HTLC_SUCCESS_ANCHOR_TX_WEIGHT: u64 = 706;
64 if opt_anchors { HTLC_SUCCESS_ANCHOR_TX_WEIGHT } else { HTLC_SUCCESS_TX_WEIGHT }
67 /// Gets the weight for an HTLC-Timeout transaction.
69 pub fn htlc_timeout_tx_weight(opt_anchors: bool) -> u64 {
70 const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
71 const HTLC_TIMEOUT_ANCHOR_TX_WEIGHT: u64 = 666;
72 if opt_anchors { HTLC_TIMEOUT_ANCHOR_TX_WEIGHT } else { HTLC_TIMEOUT_TX_WEIGHT }
75 /// Describes the type of HTLC claim as determined by analyzing the witness.
76 #[derive(PartialEq, Eq)]
78 /// Claims an offered output on a commitment transaction through the timeout path.
80 /// Claims an offered output on a commitment transaction through the success path.
82 /// Claims an accepted output on a commitment transaction through the timeout path.
84 /// Claims an accepted output on a commitment transaction through the success path.
86 /// Claims an offered/accepted output on a commitment transaction through the revocation path.
91 /// Check if a given input witness attempts to claim a HTLC.
92 pub fn from_witness(witness: &Witness) -> Option<Self> {
93 debug_assert_eq!(OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS, MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT);
94 if witness.len() < 2 {
97 let witness_script = witness.last().unwrap();
98 let second_to_last = witness.second_to_last().unwrap();
99 if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT {
100 if witness.len() == 3 && second_to_last.len() == 33 {
101 // <revocation sig> <revocationpubkey> <witness_script>
102 Some(Self::Revocation)
103 } else if witness.len() == 3 && second_to_last.len() == 32 {
104 // <remotehtlcsig> <payment_preimage> <witness_script>
105 Some(Self::OfferedPreimage)
106 } else if witness.len() == 5 && second_to_last.len() == 0 {
107 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
108 Some(Self::OfferedTimeout)
112 } else if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS {
113 // It's possible for the weight of `offered_htlc_script` and `accepted_htlc_script` to
114 // match so we check for both here.
115 if witness.len() == 3 && second_to_last.len() == 33 {
116 // <revocation sig> <revocationpubkey> <witness_script>
117 Some(Self::Revocation)
118 } else if witness.len() == 3 && second_to_last.len() == 32 {
119 // <remotehtlcsig> <payment_preimage> <witness_script>
120 Some(Self::OfferedPreimage)
121 } else if witness.len() == 5 && second_to_last.len() == 0 {
122 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
123 Some(Self::OfferedTimeout)
124 } else if witness.len() == 3 && second_to_last.len() == 0 {
125 // <remotehtlcsig> <> <witness_script>
126 Some(Self::AcceptedTimeout)
127 } else if witness.len() == 5 && second_to_last.len() == 32 {
128 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
129 Some(Self::AcceptedPreimage)
133 } else if witness_script.len() > MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT &&
134 witness_script.len() <= MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT {
135 // Handle remaining range of ACCEPTED_HTLC_SCRIPT_WEIGHT.
136 if witness.len() == 3 && second_to_last.len() == 33 {
137 // <revocation sig> <revocationpubkey> <witness_script>
138 Some(Self::Revocation)
139 } else if witness.len() == 3 && second_to_last.len() == 0 {
140 // <remotehtlcsig> <> <witness_script>
141 Some(Self::AcceptedTimeout)
142 } else if witness.len() == 5 && second_to_last.len() == 32 {
143 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
144 Some(Self::AcceptedPreimage)
154 // Various functions for key derivation and transaction creation for use within channels. Primarily
155 // used in Channel and ChannelMonitor.
157 /// Build the commitment secret from the seed and the commitment number
158 pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
159 let mut res: [u8; 32] = commitment_seed.clone();
162 if idx & (1 << bitpos) == (1 << bitpos) {
163 res[bitpos / 8] ^= 1 << (bitpos & 7);
164 res = Sha256::hash(&res).into_inner();
170 /// Build a closing transaction
171 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 {
173 let mut ins: Vec<TxIn> = Vec::new();
175 previous_output: funding_outpoint,
176 script_sig: Script::new(),
177 sequence: Sequence::MAX,
178 witness: Witness::new(),
183 let mut txouts: Vec<(TxOut, ())> = Vec::new();
185 if to_counterparty_value_sat > 0 {
187 script_pubkey: to_counterparty_script,
188 value: to_counterparty_value_sat
192 if to_holder_value_sat > 0 {
194 script_pubkey: to_holder_script,
195 value: to_holder_value_sat
199 transaction_utils::sort_outputs(&mut txouts, |_, _| { cmp::Ordering::Equal }); // Ordering doesnt matter if they used our pubkey...
201 let mut outputs: Vec<TxOut> = Vec::new();
202 for out in txouts.drain(..) {
208 lock_time: PackedLockTime::ZERO,
214 /// Implements the per-commitment secret storage scheme from
215 /// [BOLT 3](https://github.com/lightning/bolts/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
217 /// Allows us to keep track of all of the revocation secrets of our counterparty in just 50*32 bytes
220 pub struct CounterpartyCommitmentSecrets {
221 old_secrets: [([u8; 32], u64); 49],
224 impl Eq for CounterpartyCommitmentSecrets {}
225 impl PartialEq for CounterpartyCommitmentSecrets {
226 fn eq(&self, other: &Self) -> bool {
227 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
228 if secret != o_secret || idx != o_idx {
236 impl CounterpartyCommitmentSecrets {
237 /// Creates a new empty `CounterpartyCommitmentSecrets` structure.
238 pub fn new() -> Self {
239 Self { old_secrets: [([0; 32], 1 << 48); 49], }
243 fn place_secret(idx: u64) -> u8 {
245 if idx & (1 << i) == (1 << i) {
252 /// Returns the minimum index of all stored secrets. Note that indexes start
253 /// at 1 << 48 and get decremented by one for each new secret.
254 pub fn get_min_seen_secret(&self) -> u64 {
255 //TODO This can be optimized?
256 let mut min = 1 << 48;
257 for &(_, idx) in self.old_secrets.iter() {
266 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
267 let mut res: [u8; 32] = secret;
269 let bitpos = bits - 1 - i;
270 if idx & (1 << bitpos) == (1 << bitpos) {
271 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
272 res = Sha256::hash(&res).into_inner();
278 /// Inserts the `secret` at `idx`. Returns `Ok(())` if the secret
279 /// was generated in accordance with BOLT 3 and is consistent with previous secrets.
280 pub fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
281 let pos = Self::place_secret(idx);
283 let (old_secret, old_idx) = self.old_secrets[i as usize];
284 if Self::derive_secret(secret, pos, old_idx) != old_secret {
288 if self.get_min_seen_secret() <= idx {
291 self.old_secrets[pos as usize] = (secret, idx);
295 /// Returns the secret at `idx`.
296 /// Returns `None` if `idx` is < [`CounterpartyCommitmentSecrets::get_min_seen_secret`].
297 pub fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
298 for i in 0..self.old_secrets.len() {
299 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
300 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
303 assert!(idx < self.get_min_seen_secret());
308 impl Writeable for CounterpartyCommitmentSecrets {
309 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
310 for &(ref secret, ref idx) in self.old_secrets.iter() {
311 writer.write_all(secret)?;
312 writer.write_all(&idx.to_be_bytes())?;
314 write_tlv_fields!(writer, {});
318 impl Readable for CounterpartyCommitmentSecrets {
319 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
320 let mut old_secrets = [([0; 32], 1 << 48); 49];
321 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
322 *secret = Readable::read(reader)?;
323 *idx = Readable::read(reader)?;
325 read_tlv_fields!(reader, {});
326 Ok(Self { old_secrets })
330 /// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
331 /// from the base secret and the per_commitment_point.
332 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> SecretKey {
333 let mut sha = Sha256::engine();
334 sha.input(&per_commitment_point.serialize());
335 sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
336 let res = Sha256::from_engine(sha).into_inner();
338 base_secret.clone().add_tweak(&Scalar::from_be_bytes(res).unwrap())
339 .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.")
342 /// Derives a per-commitment-transaction public key (eg an htlc key or a delayed_payment key)
343 /// from the base point and the per_commitment_key. This is the public equivalent of
344 /// derive_private_key - using only public keys to derive a public key instead of private keys.
345 pub fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> PublicKey {
346 let mut sha = Sha256::engine();
347 sha.input(&per_commitment_point.serialize());
348 sha.input(&base_point.serialize());
349 let res = Sha256::from_engine(sha).into_inner();
351 let hashkey = PublicKey::from_secret_key(&secp_ctx,
352 &SecretKey::from_slice(&res).expect("Hashes should always be valid keys unless SHA-256 is broken"));
353 base_point.combine(&hashkey)
354 .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.")
357 /// Derives a per-commitment-transaction revocation key from its constituent parts.
359 /// Only the cheating participant owns a valid witness to propagate a revoked
360 /// commitment transaction, thus per_commitment_secret always come from cheater
361 /// and revocation_base_secret always come from punisher, which is the broadcaster
362 /// of the transaction spending with this key knowledge.
363 pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>,
364 per_commitment_secret: &SecretKey, countersignatory_revocation_base_secret: &SecretKey)
366 let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
367 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
369 let rev_append_commit_hash_key = {
370 let mut sha = Sha256::engine();
371 sha.input(&countersignatory_revocation_base_point.serialize());
372 sha.input(&per_commitment_point.serialize());
374 Sha256::from_engine(sha).into_inner()
376 let commit_append_rev_hash_key = {
377 let mut sha = Sha256::engine();
378 sha.input(&per_commitment_point.serialize());
379 sha.input(&countersignatory_revocation_base_point.serialize());
381 Sha256::from_engine(sha).into_inner()
384 let countersignatory_contrib = countersignatory_revocation_base_secret.clone().mul_tweak(&Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
385 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
386 let broadcaster_contrib = per_commitment_secret.clone().mul_tweak(&Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
387 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
388 countersignatory_contrib.add_tweak(&Scalar::from_be_bytes(broadcaster_contrib.secret_bytes()).unwrap())
389 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
392 /// Derives a per-commitment-transaction revocation public key from its constituent parts. This is
393 /// the public equivalend of derive_private_revocation_key - using only public keys to derive a
394 /// public key instead of private keys.
396 /// Only the cheating participant owns a valid witness to propagate a revoked
397 /// commitment transaction, thus per_commitment_point always come from cheater
398 /// and revocation_base_point always come from punisher, which is the broadcaster
399 /// of the transaction spending with this key knowledge.
401 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
402 /// generated (ie our own).
403 pub fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp256k1<T>,
404 per_commitment_point: &PublicKey, countersignatory_revocation_base_point: &PublicKey)
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 .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
423 let broadcaster_contrib = per_commitment_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
424 .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
425 countersignatory_contrib.combine(&broadcaster_contrib)
426 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
429 /// The set of public keys which are used in the creation of one commitment transaction.
430 /// These are derived from the channel base keys and per-commitment data.
432 /// A broadcaster key is provided from potential broadcaster of the computed transaction.
433 /// A countersignatory key is coming from a protocol participant unable to broadcast the
436 /// These keys are assumed to be good, either because the code derived them from
437 /// channel basepoints via the new function, or they were obtained via
438 /// CommitmentTransaction.trust().keys() because we trusted the source of the
439 /// pre-calculated keys.
440 #[derive(PartialEq, Eq, Clone)]
441 pub struct TxCreationKeys {
442 /// The broadcaster's per-commitment public key which was used to derive the other keys.
443 pub per_commitment_point: PublicKey,
444 /// The revocation key which is used to allow the broadcaster of the commitment
445 /// transaction to provide their counterparty the ability to punish them if they broadcast
447 pub revocation_key: PublicKey,
448 /// Broadcaster's HTLC Key
449 pub broadcaster_htlc_key: PublicKey,
450 /// Countersignatory's HTLC Key
451 pub countersignatory_htlc_key: PublicKey,
452 /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
453 pub broadcaster_delayed_payment_key: PublicKey,
456 impl_writeable_tlv_based!(TxCreationKeys, {
457 (0, per_commitment_point, required),
458 (2, revocation_key, required),
459 (4, broadcaster_htlc_key, required),
460 (6, countersignatory_htlc_key, required),
461 (8, broadcaster_delayed_payment_key, required),
464 /// One counterparty's public keys which do not change over the life of a channel.
465 #[derive(Clone, Debug, PartialEq, Eq)]
466 pub struct ChannelPublicKeys {
467 /// The public key which is used to sign all commitment transactions, as it appears in the
468 /// on-chain channel lock-in 2-of-2 multisig output.
469 pub funding_pubkey: PublicKey,
470 /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
471 /// revocation keys. This is combined with the per-commitment-secret generated by the
472 /// counterparty to create a secret which the counterparty can reveal to revoke previous
474 pub revocation_basepoint: PublicKey,
475 /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
476 /// spendable primary channel balance on the broadcaster's commitment transaction. This key is
477 /// static across every commitment transaction.
478 pub payment_point: PublicKey,
479 /// The base point which is used (with derive_public_key) to derive a per-commitment payment
480 /// public key which receives non-HTLC-encumbered funds which are only available for spending
481 /// after some delay (or can be claimed via the revocation path).
482 pub delayed_payment_basepoint: PublicKey,
483 /// The base point which is used (with derive_public_key) to derive a per-commitment public key
484 /// which is used to encumber HTLC-in-flight outputs.
485 pub htlc_basepoint: PublicKey,
488 impl_writeable_tlv_based!(ChannelPublicKeys, {
489 (0, funding_pubkey, required),
490 (2, revocation_basepoint, required),
491 (4, payment_point, required),
492 (6, delayed_payment_basepoint, required),
493 (8, htlc_basepoint, required),
496 impl TxCreationKeys {
497 /// Create per-state keys from channel base points and the per-commitment point.
498 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
499 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 {
501 per_commitment_point: per_commitment_point.clone(),
502 revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &countersignatory_revocation_base),
503 broadcaster_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_htlc_base),
504 countersignatory_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &countersignatory_htlc_base),
505 broadcaster_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_delayed_payment_base),
509 /// Generate per-state keys from channel static keys.
510 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
511 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 {
512 TxCreationKeys::derive_new(
514 &per_commitment_point,
515 &broadcaster_keys.delayed_payment_basepoint,
516 &broadcaster_keys.htlc_basepoint,
517 &countersignatory_keys.revocation_basepoint,
518 &countersignatory_keys.htlc_basepoint,
523 /// The maximum length of a script returned by get_revokeable_redeemscript.
524 // Calculated as 6 bytes of opcodes, 1 byte push plus 2 bytes for contest_delay, and two public
525 // keys of 33 bytes (+ 1 push).
526 pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 3 + 34*2;
528 /// A script either spendable by the revocation
529 /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
530 /// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
531 pub fn get_revokeable_redeemscript(revocation_key: &PublicKey, contest_delay: u16, broadcaster_delayed_payment_key: &PublicKey) -> Script {
532 let res = Builder::new().push_opcode(opcodes::all::OP_IF)
533 .push_slice(&revocation_key.serialize())
534 .push_opcode(opcodes::all::OP_ELSE)
535 .push_int(contest_delay as i64)
536 .push_opcode(opcodes::all::OP_CSV)
537 .push_opcode(opcodes::all::OP_DROP)
538 .push_slice(&broadcaster_delayed_payment_key.serialize())
539 .push_opcode(opcodes::all::OP_ENDIF)
540 .push_opcode(opcodes::all::OP_CHECKSIG)
542 debug_assert!(res.len() <= REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH);
546 /// Information about an HTLC as it appears in a commitment transaction
547 #[derive(Clone, Debug, PartialEq, Eq)]
548 pub struct HTLCOutputInCommitment {
549 /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
550 /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
551 /// need to compare this value to whether the commitment transaction in question is that of
552 /// the counterparty or our own.
554 /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
555 /// this divided by 1000.
556 pub amount_msat: u64,
557 /// The CLTV lock-time at which this HTLC expires.
558 pub cltv_expiry: u32,
559 /// The hash of the preimage which unlocks this HTLC.
560 pub payment_hash: PaymentHash,
561 /// The position within the commitment transactions' outputs. This may be None if the value is
562 /// below the dust limit (in which case no output appears in the commitment transaction and the
563 /// value is spent to additional transaction fees).
564 pub transaction_output_index: Option<u32>,
567 impl_writeable_tlv_based!(HTLCOutputInCommitment, {
568 (0, offered, required),
569 (2, amount_msat, required),
570 (4, cltv_expiry, required),
571 (6, payment_hash, required),
572 (8, transaction_output_index, option),
576 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 {
577 let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
579 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
580 .push_opcode(opcodes::all::OP_HASH160)
581 .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
582 .push_opcode(opcodes::all::OP_EQUAL)
583 .push_opcode(opcodes::all::OP_IF)
584 .push_opcode(opcodes::all::OP_CHECKSIG)
585 .push_opcode(opcodes::all::OP_ELSE)
586 .push_slice(&countersignatory_htlc_key.serialize()[..])
587 .push_opcode(opcodes::all::OP_SWAP)
588 .push_opcode(opcodes::all::OP_SIZE)
590 .push_opcode(opcodes::all::OP_EQUAL)
591 .push_opcode(opcodes::all::OP_NOTIF)
592 .push_opcode(opcodes::all::OP_DROP)
594 .push_opcode(opcodes::all::OP_SWAP)
595 .push_slice(&broadcaster_htlc_key.serialize()[..])
597 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
598 .push_opcode(opcodes::all::OP_ELSE)
599 .push_opcode(opcodes::all::OP_HASH160)
600 .push_slice(&payment_hash160)
601 .push_opcode(opcodes::all::OP_EQUALVERIFY)
602 .push_opcode(opcodes::all::OP_CHECKSIG)
603 .push_opcode(opcodes::all::OP_ENDIF);
605 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
606 .push_opcode(opcodes::all::OP_CSV)
607 .push_opcode(opcodes::all::OP_DROP);
609 bldr.push_opcode(opcodes::all::OP_ENDIF)
612 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
613 .push_opcode(opcodes::all::OP_HASH160)
614 .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
615 .push_opcode(opcodes::all::OP_EQUAL)
616 .push_opcode(opcodes::all::OP_IF)
617 .push_opcode(opcodes::all::OP_CHECKSIG)
618 .push_opcode(opcodes::all::OP_ELSE)
619 .push_slice(&countersignatory_htlc_key.serialize()[..])
620 .push_opcode(opcodes::all::OP_SWAP)
621 .push_opcode(opcodes::all::OP_SIZE)
623 .push_opcode(opcodes::all::OP_EQUAL)
624 .push_opcode(opcodes::all::OP_IF)
625 .push_opcode(opcodes::all::OP_HASH160)
626 .push_slice(&payment_hash160)
627 .push_opcode(opcodes::all::OP_EQUALVERIFY)
629 .push_opcode(opcodes::all::OP_SWAP)
630 .push_slice(&broadcaster_htlc_key.serialize()[..])
632 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
633 .push_opcode(opcodes::all::OP_ELSE)
634 .push_opcode(opcodes::all::OP_DROP)
635 .push_int(htlc.cltv_expiry as i64)
636 .push_opcode(opcodes::all::OP_CLTV)
637 .push_opcode(opcodes::all::OP_DROP)
638 .push_opcode(opcodes::all::OP_CHECKSIG)
639 .push_opcode(opcodes::all::OP_ENDIF);
641 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
642 .push_opcode(opcodes::all::OP_CSV)
643 .push_opcode(opcodes::all::OP_DROP);
645 bldr.push_opcode(opcodes::all::OP_ENDIF)
650 /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
651 /// does not need to have its previous_output_index filled.
653 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, opt_anchors: bool, keys: &TxCreationKeys) -> Script {
654 get_htlc_redeemscript_with_explicit_keys(htlc, opt_anchors, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
657 /// Gets the redeemscript for a funding output from the two funding public keys.
658 /// Note that the order of funding public keys does not matter.
659 pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> Script {
660 let broadcaster_funding_key = broadcaster.serialize();
661 let countersignatory_funding_key = countersignatory.serialize();
663 make_funding_redeemscript_from_slices(&broadcaster_funding_key, &countersignatory_funding_key)
666 pub(crate) fn make_funding_redeemscript_from_slices(broadcaster_funding_key: &[u8], countersignatory_funding_key: &[u8]) -> Script {
667 let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
668 if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
669 builder.push_slice(broadcaster_funding_key)
670 .push_slice(countersignatory_funding_key)
672 builder.push_slice(countersignatory_funding_key)
673 .push_slice(broadcaster_funding_key)
674 }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
677 /// Builds an unsigned HTLC-Success or HTLC-Timeout transaction from the given channel and HTLC
678 /// parameters. This is used by [`TrustedCommitmentTransaction::get_htlc_sigs`] to fetch the
679 /// transaction which needs signing, and can be used to construct an HTLC transaction which is
680 /// broadcastable given a counterparty HTLC signature.
682 /// Panics if htlc.transaction_output_index.is_none() (as such HTLCs do not appear in the
683 /// commitment transaction).
684 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 {
685 let mut txins: Vec<TxIn> = Vec::new();
686 txins.push(build_htlc_input(commitment_txid, htlc, opt_anchors));
688 let mut txouts: Vec<TxOut> = Vec::new();
689 txouts.push(build_htlc_output(
690 feerate_per_kw, contest_delay, htlc, opt_anchors, use_non_zero_fee_anchors,
691 broadcaster_delayed_payment_key, revocation_key
696 lock_time: PackedLockTime(if htlc.offered { htlc.cltv_expiry } else { 0 }),
702 pub(crate) fn build_htlc_input(commitment_txid: &Txid, htlc: &HTLCOutputInCommitment, opt_anchors: bool) -> TxIn {
704 previous_output: OutPoint {
705 txid: commitment_txid.clone(),
706 vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
708 script_sig: Script::new(),
709 sequence: Sequence(if opt_anchors { 1 } else { 0 }),
710 witness: Witness::new(),
714 pub(crate) fn build_htlc_output(
715 feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, opt_anchors: bool,
716 use_non_zero_fee_anchors: bool, broadcaster_delayed_payment_key: &PublicKey, revocation_key: &PublicKey
718 let weight = if htlc.offered {
719 htlc_timeout_tx_weight(opt_anchors)
721 htlc_success_tx_weight(opt_anchors)
723 let output_value = if opt_anchors && !use_non_zero_fee_anchors {
724 htlc.amount_msat / 1000
726 let total_fee = feerate_per_kw as u64 * weight / 1000;
727 htlc.amount_msat / 1000 - total_fee
731 script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_v0_p2wsh(),
736 /// Returns the witness required to satisfy and spend a HTLC input.
737 pub fn build_htlc_input_witness(
738 local_sig: &Signature, remote_sig: &Signature, preimage: &Option<PaymentPreimage>,
739 redeem_script: &Script, opt_anchors: bool,
741 let remote_sighash_type = if opt_anchors {
742 EcdsaSighashType::SinglePlusAnyoneCanPay
744 EcdsaSighashType::All
747 let mut witness = Witness::new();
748 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
749 witness.push(vec![]);
750 witness.push_bitcoin_signature(&remote_sig.serialize_der(), remote_sighash_type);
751 witness.push_bitcoin_signature(&local_sig.serialize_der(), EcdsaSighashType::All);
752 if let Some(preimage) = preimage {
753 witness.push(preimage.0.to_vec());
755 // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
756 witness.push(vec![]);
758 witness.push(redeem_script.to_bytes());
762 /// Gets the witnessScript for the to_remote output when anchors are enabled.
764 pub fn get_to_countersignatory_with_anchors_redeemscript(payment_point: &PublicKey) -> Script {
766 .push_slice(&payment_point.serialize()[..])
767 .push_opcode(opcodes::all::OP_CHECKSIGVERIFY)
769 .push_opcode(opcodes::all::OP_CSV)
773 /// Gets the witnessScript for an anchor output from the funding public key.
774 /// The witness in the spending input must be:
775 /// <BIP 143 funding_signature>
776 /// After 16 blocks of confirmation, an alternative satisfying witness could be:
778 /// (empty vector required to satisfy compliance with MINIMALIF-standard rule)
780 pub fn get_anchor_redeemscript(funding_pubkey: &PublicKey) -> Script {
781 Builder::new().push_slice(&funding_pubkey.serialize()[..])
782 .push_opcode(opcodes::all::OP_CHECKSIG)
783 .push_opcode(opcodes::all::OP_IFDUP)
784 .push_opcode(opcodes::all::OP_NOTIF)
786 .push_opcode(opcodes::all::OP_CSV)
787 .push_opcode(opcodes::all::OP_ENDIF)
792 /// Locates the output with an anchor script paying to `funding_pubkey` within `commitment_tx`.
793 pub(crate) fn get_anchor_output<'a>(commitment_tx: &'a Transaction, funding_pubkey: &PublicKey) -> Option<(u32, &'a TxOut)> {
794 let anchor_script = chan_utils::get_anchor_redeemscript(funding_pubkey).to_v0_p2wsh();
795 commitment_tx.output.iter().enumerate()
796 .find(|(_, txout)| txout.script_pubkey == anchor_script)
797 .map(|(idx, txout)| (idx as u32, txout))
800 /// Returns the witness required to satisfy and spend an anchor input.
801 pub fn build_anchor_input_witness(funding_key: &PublicKey, funding_sig: &Signature) -> Witness {
802 let anchor_redeem_script = chan_utils::get_anchor_redeemscript(funding_key);
803 let mut ret = Witness::new();
804 ret.push_bitcoin_signature(&funding_sig.serialize_der(), EcdsaSighashType::All);
805 ret.push(anchor_redeem_script.as_bytes());
809 /// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
810 /// The fields are organized by holder/counterparty.
812 /// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
813 /// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
814 #[derive(Clone, Debug, PartialEq, Eq)]
815 pub struct ChannelTransactionParameters {
816 /// Holder public keys
817 pub holder_pubkeys: ChannelPublicKeys,
818 /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
819 pub holder_selected_contest_delay: u16,
820 /// Whether the holder is the initiator of this channel.
821 /// This is an input to the commitment number obscure factor computation.
822 pub is_outbound_from_holder: bool,
823 /// The late-bound counterparty channel transaction parameters.
824 /// These parameters are populated at the point in the protocol where the counterparty provides them.
825 pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
826 /// The late-bound funding outpoint
827 pub funding_outpoint: Option<chain::transaction::OutPoint>,
828 /// Are anchors (zero fee HTLC transaction variant) used for this channel. Boolean is
829 /// serialization backwards-compatible.
830 pub opt_anchors: Option<()>,
831 /// Are non-zero-fee anchors are enabled (used in conjuction with opt_anchors)
832 /// It is intended merely for backwards compatibility with signers that need it.
833 /// There is no support for this feature in LDK channel negotiation.
834 pub opt_non_zero_fee_anchors: Option<()>,
837 /// Late-bound per-channel counterparty data used to build transactions.
838 #[derive(Clone, Debug, PartialEq, Eq)]
839 pub struct CounterpartyChannelTransactionParameters {
840 /// Counter-party public keys
841 pub pubkeys: ChannelPublicKeys,
842 /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
843 pub selected_contest_delay: u16,
846 impl ChannelTransactionParameters {
847 /// Whether the late bound parameters are populated.
848 pub fn is_populated(&self) -> bool {
849 self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
852 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
853 /// given that the holder is the broadcaster.
855 /// self.is_populated() must be true before calling this function.
856 pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
857 assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
858 DirectedChannelTransactionParameters {
860 holder_is_broadcaster: true
864 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
865 /// given that the counterparty is the broadcaster.
867 /// self.is_populated() must be true before calling this function.
868 pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
869 assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
870 DirectedChannelTransactionParameters {
872 holder_is_broadcaster: false
877 impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, {
878 (0, pubkeys, required),
879 (2, selected_contest_delay, required),
882 impl_writeable_tlv_based!(ChannelTransactionParameters, {
883 (0, holder_pubkeys, required),
884 (2, holder_selected_contest_delay, required),
885 (4, is_outbound_from_holder, required),
886 (6, counterparty_parameters, option),
887 (8, funding_outpoint, option),
888 (10, opt_anchors, option),
889 (12, opt_non_zero_fee_anchors, option),
892 /// Static channel fields used to build transactions given per-commitment fields, organized by
893 /// broadcaster/countersignatory.
895 /// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
896 /// as_holder_broadcastable and as_counterparty_broadcastable functions.
897 pub struct DirectedChannelTransactionParameters<'a> {
898 /// The holder's channel static parameters
899 inner: &'a ChannelTransactionParameters,
900 /// Whether the holder is the broadcaster
901 holder_is_broadcaster: bool,
904 impl<'a> DirectedChannelTransactionParameters<'a> {
905 /// Get the channel pubkeys for the broadcaster
906 pub fn broadcaster_pubkeys(&self) -> &ChannelPublicKeys {
907 if self.holder_is_broadcaster {
908 &self.inner.holder_pubkeys
910 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
914 /// Get the channel pubkeys for the countersignatory
915 pub fn countersignatory_pubkeys(&self) -> &ChannelPublicKeys {
916 if self.holder_is_broadcaster {
917 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
919 &self.inner.holder_pubkeys
923 /// Get the contest delay applicable to the transactions.
924 /// Note that the contest delay was selected by the countersignatory.
925 pub fn contest_delay(&self) -> u16 {
926 let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
927 if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
930 /// Whether the channel is outbound from the broadcaster.
932 /// The boolean representing the side that initiated the channel is
933 /// an input to the commitment number obscure factor computation.
934 pub fn is_outbound(&self) -> bool {
935 if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
938 /// The funding outpoint
939 pub fn funding_outpoint(&self) -> OutPoint {
940 self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
943 /// Whether to use anchors for this channel
944 pub fn opt_anchors(&self) -> bool {
945 self.inner.opt_anchors.is_some()
949 /// Information needed to build and sign a holder's commitment transaction.
951 /// The transaction is only signed once we are ready to broadcast.
953 pub struct HolderCommitmentTransaction {
954 inner: CommitmentTransaction,
955 /// Our counterparty's signature for the transaction
956 pub counterparty_sig: Signature,
957 /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
958 pub counterparty_htlc_sigs: Vec<Signature>,
959 // Which order the signatures should go in when constructing the final commitment tx witness.
960 // The user should be able to reconstruct this themselves, so we don't bother to expose it.
961 holder_sig_first: bool,
964 impl Deref for HolderCommitmentTransaction {
965 type Target = CommitmentTransaction;
967 fn deref(&self) -> &Self::Target { &self.inner }
970 impl Eq for HolderCommitmentTransaction {}
971 impl PartialEq for HolderCommitmentTransaction {
972 // We dont care whether we are signed in equality comparison
973 fn eq(&self, o: &Self) -> bool {
974 self.inner == o.inner
978 impl_writeable_tlv_based!(HolderCommitmentTransaction, {
979 (0, inner, required),
980 (2, counterparty_sig, required),
981 (4, holder_sig_first, required),
982 (6, counterparty_htlc_sigs, vec_type),
985 impl HolderCommitmentTransaction {
987 pub fn dummy(htlcs: &mut Vec<(HTLCOutputInCommitment, ())>) -> Self {
988 let secp_ctx = Secp256k1::new();
989 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
990 let dummy_sig = sign(&secp_ctx, &secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
992 let keys = TxCreationKeys {
993 per_commitment_point: dummy_key.clone(),
994 revocation_key: dummy_key.clone(),
995 broadcaster_htlc_key: dummy_key.clone(),
996 countersignatory_htlc_key: dummy_key.clone(),
997 broadcaster_delayed_payment_key: dummy_key.clone(),
999 let channel_pubkeys = ChannelPublicKeys {
1000 funding_pubkey: dummy_key.clone(),
1001 revocation_basepoint: dummy_key.clone(),
1002 payment_point: dummy_key.clone(),
1003 delayed_payment_basepoint: dummy_key.clone(),
1004 htlc_basepoint: dummy_key.clone()
1006 let channel_parameters = ChannelTransactionParameters {
1007 holder_pubkeys: channel_pubkeys.clone(),
1008 holder_selected_contest_delay: 0,
1009 is_outbound_from_holder: false,
1010 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
1011 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1013 opt_non_zero_fee_anchors: None,
1015 let mut counterparty_htlc_sigs = Vec::new();
1016 for _ in 0..htlcs.len() {
1017 counterparty_htlc_sigs.push(dummy_sig);
1019 let inner = CommitmentTransaction::new_with_auxiliary_htlc_data(0, 0, 0, false, dummy_key.clone(), dummy_key.clone(), keys, 0, htlcs, &channel_parameters.as_counterparty_broadcastable());
1020 htlcs.sort_by_key(|htlc| htlc.0.transaction_output_index);
1021 HolderCommitmentTransaction {
1023 counterparty_sig: dummy_sig,
1024 counterparty_htlc_sigs,
1025 holder_sig_first: false
1029 /// Create a new holder transaction with the given counterparty signatures.
1030 /// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
1031 pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
1033 inner: commitment_tx,
1035 counterparty_htlc_sigs,
1036 holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
1040 pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
1041 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
1042 let mut tx = self.inner.built.transaction.clone();
1043 tx.input[0].witness.push(Vec::new());
1045 if self.holder_sig_first {
1046 tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1047 tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1049 tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1050 tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1053 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
1058 /// A pre-built Bitcoin commitment transaction and its txid.
1060 pub struct BuiltCommitmentTransaction {
1061 /// The commitment transaction
1062 pub transaction: Transaction,
1063 /// The txid for the commitment transaction.
1065 /// This is provided as a performance optimization, instead of calling transaction.txid()
1070 impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
1071 (0, transaction, required),
1072 (2, txid, required),
1075 impl BuiltCommitmentTransaction {
1076 /// Get the SIGHASH_ALL sighash value of the transaction.
1078 /// This can be used to verify a signature.
1079 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1080 let sighash = &sighash::SighashCache::new(&self.transaction).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1081 hash_to_message!(sighash)
1084 /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1085 /// because we are about to broadcast a holder transaction.
1086 pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1087 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1088 sign(secp_ctx, &sighash, funding_key)
1092 /// This class tracks the per-transaction information needed to build a closing transaction and will
1093 /// actually build it and sign.
1095 /// This class can be used inside a signer implementation to generate a signature given the relevant
1097 #[derive(Clone, Hash, PartialEq, Eq)]
1098 pub struct ClosingTransaction {
1099 to_holder_value_sat: u64,
1100 to_counterparty_value_sat: u64,
1101 to_holder_script: Script,
1102 to_counterparty_script: Script,
1106 impl ClosingTransaction {
1107 /// Construct an object of the class
1109 to_holder_value_sat: u64,
1110 to_counterparty_value_sat: u64,
1111 to_holder_script: Script,
1112 to_counterparty_script: Script,
1113 funding_outpoint: OutPoint,
1115 let built = build_closing_transaction(
1116 to_holder_value_sat, to_counterparty_value_sat,
1117 to_holder_script.clone(), to_counterparty_script.clone(),
1120 ClosingTransaction {
1121 to_holder_value_sat,
1122 to_counterparty_value_sat,
1124 to_counterparty_script,
1129 /// Trust our pre-built transaction.
1131 /// Applies a wrapper which allows access to the transaction.
1133 /// This should only be used if you fully trust the builder of this object. It should not
1134 /// be used by an external signer - instead use the verify function.
1135 pub fn trust(&self) -> TrustedClosingTransaction {
1136 TrustedClosingTransaction { inner: self }
1139 /// Verify our pre-built transaction.
1141 /// Applies a wrapper which allows access to the transaction.
1143 /// An external validating signer must call this method before signing
1144 /// or using the built transaction.
1145 pub fn verify(&self, funding_outpoint: OutPoint) -> Result<TrustedClosingTransaction, ()> {
1146 let built = build_closing_transaction(
1147 self.to_holder_value_sat, self.to_counterparty_value_sat,
1148 self.to_holder_script.clone(), self.to_counterparty_script.clone(),
1151 if self.built != built {
1154 Ok(TrustedClosingTransaction { inner: self })
1157 /// The value to be sent to the holder, or zero if the output will be omitted
1158 pub fn to_holder_value_sat(&self) -> u64 {
1159 self.to_holder_value_sat
1162 /// The value to be sent to the counterparty, or zero if the output will be omitted
1163 pub fn to_counterparty_value_sat(&self) -> u64 {
1164 self.to_counterparty_value_sat
1167 /// The destination of the holder's output
1168 pub fn to_holder_script(&self) -> &Script {
1169 &self.to_holder_script
1172 /// The destination of the counterparty's output
1173 pub fn to_counterparty_script(&self) -> &Script {
1174 &self.to_counterparty_script
1178 /// A wrapper on ClosingTransaction indicating that the built bitcoin
1179 /// transaction is trusted.
1181 /// See trust() and verify() functions on CommitmentTransaction.
1183 /// This structure implements Deref.
1184 pub struct TrustedClosingTransaction<'a> {
1185 inner: &'a ClosingTransaction,
1188 impl<'a> Deref for TrustedClosingTransaction<'a> {
1189 type Target = ClosingTransaction;
1191 fn deref(&self) -> &Self::Target { self.inner }
1194 impl<'a> TrustedClosingTransaction<'a> {
1195 /// The pre-built Bitcoin commitment transaction
1196 pub fn built_transaction(&self) -> &Transaction {
1200 /// Get the SIGHASH_ALL sighash value of the transaction.
1202 /// This can be used to verify a signature.
1203 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1204 let sighash = &sighash::SighashCache::new(&self.inner.built).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1205 hash_to_message!(sighash)
1208 /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1209 /// because we are about to broadcast a holder transaction.
1210 pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1211 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1212 sign(secp_ctx, &sighash, funding_key)
1216 /// This class tracks the per-transaction information needed to build a commitment transaction and will
1217 /// actually build it and sign. It is used for holder transactions that we sign only when needed
1218 /// and for transactions we sign for the counterparty.
1220 /// This class can be used inside a signer implementation to generate a signature given the relevant
1223 pub struct CommitmentTransaction {
1224 commitment_number: u64,
1225 to_broadcaster_value_sat: u64,
1226 to_countersignatory_value_sat: u64,
1227 feerate_per_kw: u32,
1228 htlcs: Vec<HTLCOutputInCommitment>,
1229 // A boolean that is serialization backwards-compatible
1230 opt_anchors: Option<()>,
1231 // Whether non-zero-fee anchors should be used
1232 opt_non_zero_fee_anchors: Option<()>,
1233 // A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
1234 keys: TxCreationKeys,
1235 // For access to the pre-built transaction, see doc for trust()
1236 built: BuiltCommitmentTransaction,
1239 impl Eq for CommitmentTransaction {}
1240 impl PartialEq for CommitmentTransaction {
1241 fn eq(&self, o: &Self) -> bool {
1242 let eq = self.commitment_number == o.commitment_number &&
1243 self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
1244 self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
1245 self.feerate_per_kw == o.feerate_per_kw &&
1246 self.htlcs == o.htlcs &&
1247 self.opt_anchors == o.opt_anchors &&
1248 self.keys == o.keys;
1250 debug_assert_eq!(self.built.transaction, o.built.transaction);
1251 debug_assert_eq!(self.built.txid, o.built.txid);
1257 impl_writeable_tlv_based!(CommitmentTransaction, {
1258 (0, commitment_number, required),
1259 (2, to_broadcaster_value_sat, required),
1260 (4, to_countersignatory_value_sat, required),
1261 (6, feerate_per_kw, required),
1262 (8, keys, required),
1263 (10, built, required),
1264 (12, htlcs, vec_type),
1265 (14, opt_anchors, option),
1266 (16, opt_non_zero_fee_anchors, option),
1269 impl CommitmentTransaction {
1270 /// Construct an object of the class while assigning transaction output indices to HTLCs.
1272 /// Populates HTLCOutputInCommitment.transaction_output_index in htlcs_with_aux.
1274 /// The generic T allows the caller to match the HTLC output index with auxiliary data.
1275 /// This auxiliary data is not stored in this object.
1277 /// Only include HTLCs that are above the dust limit for the channel.
1279 /// This is not exported to bindings users due to the generic though we likely should expose a version without
1280 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 {
1281 // Sort outputs and populate output indices while keeping track of the auxiliary data
1282 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();
1284 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
1285 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1286 let txid = transaction.txid();
1287 CommitmentTransaction {
1289 to_broadcaster_value_sat,
1290 to_countersignatory_value_sat,
1293 opt_anchors: if opt_anchors { Some(()) } else { None },
1295 built: BuiltCommitmentTransaction {
1299 opt_non_zero_fee_anchors: None,
1303 /// Use non-zero fee anchors
1305 /// This is not exported to bindings users due to move, and also not likely to be useful for binding users
1306 pub fn with_non_zero_fee_anchors(mut self) -> Self {
1307 self.opt_non_zero_fee_anchors = Some(());
1311 fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<BuiltCommitmentTransaction, ()> {
1312 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
1314 let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
1315 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)?;
1317 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1318 let txid = transaction.txid();
1319 let built_transaction = BuiltCommitmentTransaction {
1323 Ok(built_transaction)
1326 fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
1329 lock_time: PackedLockTime(((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32)),
1335 // This is used in two cases:
1336 // - initial sorting of outputs / HTLCs in the constructor, in which case T is auxiliary data the
1337 // caller needs to have sorted together with the HTLCs so it can keep track of the output index
1338 // - building of a bitcoin transaction during a verify() call, in which case T is just ()
1339 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>), ()> {
1340 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1341 let contest_delay = channel_parameters.contest_delay();
1343 let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
1345 if to_countersignatory_value_sat > 0 {
1346 let script = if opt_anchors {
1347 get_to_countersignatory_with_anchors_redeemscript(&countersignatory_pubkeys.payment_point).to_v0_p2wsh()
1349 Payload::p2wpkh(&BitcoinPublicKey::new(countersignatory_pubkeys.payment_point)).unwrap().script_pubkey()
1353 script_pubkey: script.clone(),
1354 value: to_countersignatory_value_sat,
1360 if to_broadcaster_value_sat > 0 {
1361 let redeem_script = get_revokeable_redeemscript(
1362 &keys.revocation_key,
1364 &keys.broadcaster_delayed_payment_key,
1368 script_pubkey: redeem_script.to_v0_p2wsh(),
1369 value: to_broadcaster_value_sat,
1376 if to_broadcaster_value_sat > 0 || !htlcs_with_aux.is_empty() {
1377 let anchor_script = get_anchor_redeemscript(broadcaster_funding_key);
1380 script_pubkey: anchor_script.to_v0_p2wsh(),
1381 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1387 if to_countersignatory_value_sat > 0 || !htlcs_with_aux.is_empty() {
1388 let anchor_script = get_anchor_redeemscript(countersignatory_funding_key);
1391 script_pubkey: anchor_script.to_v0_p2wsh(),
1392 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1399 let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
1400 for (htlc, _) in htlcs_with_aux {
1401 let script = chan_utils::get_htlc_redeemscript(&htlc, opt_anchors, &keys);
1403 script_pubkey: script.to_v0_p2wsh(),
1404 value: htlc.amount_msat / 1000,
1406 txouts.push((txout, Some(htlc)));
1409 // Sort output in BIP-69 order (amount, scriptPubkey). Tie-breaks based on HTLC
1410 // CLTV expiration height.
1411 sort_outputs(&mut txouts, |a, b| {
1412 if let &Some(ref a_htlcout) = a {
1413 if let &Some(ref b_htlcout) = b {
1414 a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
1415 // Note that due to hash collisions, we have to have a fallback comparison
1416 // here for fuzzing mode (otherwise at least chanmon_fail_consistency
1418 .then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
1419 // For non-HTLC outputs, if they're copying our SPK we don't really care if we
1420 // close the channel due to mismatches - they're doing something dumb:
1421 } else { cmp::Ordering::Equal }
1422 } else { cmp::Ordering::Equal }
1425 let mut outputs = Vec::with_capacity(txouts.len());
1426 for (idx, out) in txouts.drain(..).enumerate() {
1427 if let Some(htlc) = out.1 {
1428 htlc.transaction_output_index = Some(idx as u32);
1429 htlcs.push(htlc.clone());
1431 outputs.push(out.0);
1433 Ok((outputs, htlcs))
1436 fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
1437 let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
1438 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1439 let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
1440 &broadcaster_pubkeys.payment_point,
1441 &countersignatory_pubkeys.payment_point,
1442 channel_parameters.is_outbound(),
1445 let obscured_commitment_transaction_number =
1446 commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
1449 let mut ins: Vec<TxIn> = Vec::new();
1451 previous_output: channel_parameters.funding_outpoint(),
1452 script_sig: Script::new(),
1453 sequence: Sequence(((0x80 as u32) << 8 * 3)
1454 | ((obscured_commitment_transaction_number >> 3 * 8) as u32)),
1455 witness: Witness::new(),
1459 (obscured_commitment_transaction_number, txins)
1462 /// The backwards-counting commitment number
1463 pub fn commitment_number(&self) -> u64 {
1464 self.commitment_number
1467 /// The value to be sent to the broadcaster
1468 pub fn to_broadcaster_value_sat(&self) -> u64 {
1469 self.to_broadcaster_value_sat
1472 /// The value to be sent to the counterparty
1473 pub fn to_countersignatory_value_sat(&self) -> u64 {
1474 self.to_countersignatory_value_sat
1477 /// The feerate paid per 1000-weight-unit in this commitment transaction.
1478 pub fn feerate_per_kw(&self) -> u32 {
1482 /// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
1483 /// which were included in this commitment transaction in output order.
1484 /// The transaction index is always populated.
1486 /// This is not exported to bindings users as we cannot currently convert Vec references to/from C, though we should
1487 /// expose a less effecient version which creates a Vec of references in the future.
1488 pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
1492 /// Trust our pre-built transaction and derived transaction creation public keys.
1494 /// Applies a wrapper which allows access to these fields.
1496 /// This should only be used if you fully trust the builder of this object. It should not
1497 /// be used by an external signer - instead use the verify function.
1498 pub fn trust(&self) -> TrustedCommitmentTransaction {
1499 TrustedCommitmentTransaction { inner: self }
1502 /// Verify our pre-built transaction and derived transaction creation public keys.
1504 /// Applies a wrapper which allows access to these fields.
1506 /// An external validating signer must call this method before signing
1507 /// or using the built transaction.
1508 pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
1509 // This is the only field of the key cache that we trust
1510 let per_commitment_point = self.keys.per_commitment_point;
1511 let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx);
1512 if keys != self.keys {
1515 let tx = self.internal_rebuild_transaction(&keys, channel_parameters, &broadcaster_keys.funding_pubkey, &countersignatory_keys.funding_pubkey)?;
1516 if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
1519 Ok(TrustedCommitmentTransaction { inner: self })
1523 /// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
1524 /// transaction and the transaction creation keys) are trusted.
1526 /// See trust() and verify() functions on CommitmentTransaction.
1528 /// This structure implements Deref.
1529 pub struct TrustedCommitmentTransaction<'a> {
1530 inner: &'a CommitmentTransaction,
1533 impl<'a> Deref for TrustedCommitmentTransaction<'a> {
1534 type Target = CommitmentTransaction;
1536 fn deref(&self) -> &Self::Target { self.inner }
1539 impl<'a> TrustedCommitmentTransaction<'a> {
1540 /// The transaction ID of the built Bitcoin transaction
1541 pub fn txid(&self) -> Txid {
1542 self.inner.built.txid
1545 /// The pre-built Bitcoin commitment transaction
1546 pub fn built_transaction(&self) -> &BuiltCommitmentTransaction {
1550 /// The pre-calculated transaction creation public keys.
1551 pub fn keys(&self) -> &TxCreationKeys {
1555 /// Should anchors be used.
1556 pub fn opt_anchors(&self) -> bool {
1557 self.opt_anchors.is_some()
1560 /// Get a signature for each HTLC which was included in the commitment transaction (ie for
1561 /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
1563 /// The returned Vec has one entry for each HTLC, and in the same order.
1565 /// This function is only valid in the holder commitment context, it always uses EcdsaSighashType::All.
1566 pub fn get_htlc_sigs<T: secp256k1::Signing>(&self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters, secp_ctx: &Secp256k1<T>) -> Result<Vec<Signature>, ()> {
1567 let inner = self.inner;
1568 let keys = &inner.keys;
1569 let txid = inner.built.txid;
1570 let mut ret = Vec::with_capacity(inner.htlcs.len());
1571 let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key);
1573 for this_htlc in inner.htlcs.iter() {
1574 assert!(this_htlc.transaction_output_index.is_some());
1575 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);
1577 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);
1579 let sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, EcdsaSighashType::All).unwrap()[..]);
1580 ret.push(sign(secp_ctx, &sighash, &holder_htlc_key));
1585 /// Gets a signed HTLC transaction given a preimage (for !htlc.offered) and the holder HTLC transaction signature.
1586 pub(crate) fn get_signed_htlc_tx(&self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature, preimage: &Option<PaymentPreimage>) -> Transaction {
1587 let inner = self.inner;
1588 let keys = &inner.keys;
1589 let txid = inner.built.txid;
1590 let this_htlc = &inner.htlcs[htlc_index];
1591 assert!(this_htlc.transaction_output_index.is_some());
1592 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
1593 if !this_htlc.offered && preimage.is_none() { unreachable!(); }
1594 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
1595 if this_htlc.offered && preimage.is_some() { unreachable!(); }
1597 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);
1599 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);
1601 htlc_tx.input[0].witness = chan_utils::build_htlc_input_witness(
1602 signature, counterparty_signature, preimage, &htlc_redeemscript, self.opt_anchors(),
1608 /// Commitment transaction numbers which appear in the transactions themselves are XOR'd with a
1609 /// shared secret first. This prevents on-chain observers from discovering how many commitment
1610 /// transactions occurred in a channel before it was closed.
1612 /// This function gets the shared secret from relevant channel public keys and can be used to
1613 /// "decrypt" the commitment transaction number given a commitment transaction on-chain.
1614 pub fn get_commitment_transaction_number_obscure_factor(
1615 broadcaster_payment_basepoint: &PublicKey,
1616 countersignatory_payment_basepoint: &PublicKey,
1617 outbound_from_broadcaster: bool,
1619 let mut sha = Sha256::engine();
1621 if outbound_from_broadcaster {
1622 sha.input(&broadcaster_payment_basepoint.serialize());
1623 sha.input(&countersignatory_payment_basepoint.serialize());
1625 sha.input(&countersignatory_payment_basepoint.serialize());
1626 sha.input(&broadcaster_payment_basepoint.serialize());
1628 let res = Sha256::from_engine(sha).into_inner();
1630 ((res[26] as u64) << 5 * 8)
1631 | ((res[27] as u64) << 4 * 8)
1632 | ((res[28] as u64) << 3 * 8)
1633 | ((res[29] as u64) << 2 * 8)
1634 | ((res[30] as u64) << 1 * 8)
1635 | ((res[31] as u64) << 0 * 8)
1640 use super::CounterpartyCommitmentSecrets;
1641 use crate::{hex, chain};
1642 use crate::prelude::*;
1643 use crate::ln::chan_utils::{get_htlc_redeemscript, get_to_countersignatory_with_anchors_redeemscript, CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
1644 use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
1645 use crate::util::test_utils;
1646 use crate::chain::keysinterface::{ChannelSigner, SignerProvider};
1647 use bitcoin::{Network, Txid};
1648 use bitcoin::hashes::Hash;
1649 use crate::ln::PaymentHash;
1650 use bitcoin::hashes::hex::ToHex;
1651 use bitcoin::util::address::Payload;
1652 use bitcoin::PublicKey as BitcoinPublicKey;
1656 let secp_ctx = Secp256k1::new();
1658 let seed = [42; 32];
1659 let network = Network::Testnet;
1660 let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
1661 let signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(false, 1_000_000, 0));
1662 let counterparty_signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(true, 1_000_000, 1));
1663 let delayed_payment_base = &signer.pubkeys().delayed_payment_basepoint;
1664 let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
1665 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
1666 let htlc_basepoint = &signer.pubkeys().htlc_basepoint;
1667 let holder_pubkeys = signer.pubkeys();
1668 let counterparty_pubkeys = counterparty_signer.pubkeys();
1669 let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint);
1670 let mut channel_parameters = ChannelTransactionParameters {
1671 holder_pubkeys: holder_pubkeys.clone(),
1672 holder_selected_contest_delay: 0,
1673 is_outbound_from_holder: false,
1674 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: counterparty_pubkeys.clone(), selected_contest_delay: 0 }),
1675 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1677 opt_non_zero_fee_anchors: None,
1680 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
1682 // Generate broadcaster and counterparty outputs
1683 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1686 holder_pubkeys.funding_pubkey,
1687 counterparty_pubkeys.funding_pubkey,
1689 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1691 assert_eq!(tx.built.transaction.output.len(), 2);
1692 assert_eq!(tx.built.transaction.output[1].script_pubkey, Payload::p2wpkh(&BitcoinPublicKey::new(counterparty_pubkeys.payment_point)).unwrap().script_pubkey());
1694 // Generate broadcaster and counterparty outputs as well as two anchors
1695 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1698 holder_pubkeys.funding_pubkey,
1699 counterparty_pubkeys.funding_pubkey,
1701 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1703 assert_eq!(tx.built.transaction.output.len(), 4);
1704 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_to_countersignatory_with_anchors_redeemscript(&counterparty_pubkeys.payment_point).to_v0_p2wsh());
1706 // Generate broadcaster output and anchor
1707 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1710 holder_pubkeys.funding_pubkey,
1711 counterparty_pubkeys.funding_pubkey,
1713 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1715 assert_eq!(tx.built.transaction.output.len(), 2);
1717 // Generate counterparty output and anchor
1718 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1721 holder_pubkeys.funding_pubkey,
1722 counterparty_pubkeys.funding_pubkey,
1724 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1726 assert_eq!(tx.built.transaction.output.len(), 2);
1728 let received_htlc = HTLCOutputInCommitment {
1730 amount_msat: 400000,
1732 payment_hash: PaymentHash([42; 32]),
1733 transaction_output_index: None,
1736 let offered_htlc = HTLCOutputInCommitment {
1738 amount_msat: 600000,
1740 payment_hash: PaymentHash([43; 32]),
1741 transaction_output_index: None,
1744 // Generate broadcaster output and received and offered HTLC outputs, w/o anchors
1745 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1748 holder_pubkeys.funding_pubkey,
1749 counterparty_pubkeys.funding_pubkey,
1751 &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1752 &channel_parameters.as_holder_broadcastable()
1754 assert_eq!(tx.built.transaction.output.len(), 3);
1755 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_htlc_redeemscript(&received_htlc, false, &keys).to_v0_p2wsh());
1756 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&offered_htlc, false, &keys).to_v0_p2wsh());
1757 assert_eq!(get_htlc_redeemscript(&received_htlc, false, &keys).to_v0_p2wsh().to_hex(),
1758 "0020e43a7c068553003fe68fcae424fb7b28ec5ce48cd8b6744b3945631389bad2fb");
1759 assert_eq!(get_htlc_redeemscript(&offered_htlc, false, &keys).to_v0_p2wsh().to_hex(),
1760 "0020215d61bba56b19e9eadb6107f5a85d7f99c40f65992443f69229c290165bc00d");
1762 // Generate broadcaster output and received and offered HTLC outputs, with anchors
1763 channel_parameters.opt_anchors = Some(());
1764 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1767 holder_pubkeys.funding_pubkey,
1768 counterparty_pubkeys.funding_pubkey,
1770 &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1771 &channel_parameters.as_holder_broadcastable()
1773 assert_eq!(tx.built.transaction.output.len(), 5);
1774 assert_eq!(tx.built.transaction.output[2].script_pubkey, get_htlc_redeemscript(&received_htlc, true, &keys).to_v0_p2wsh());
1775 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_htlc_redeemscript(&offered_htlc, true, &keys).to_v0_p2wsh());
1776 assert_eq!(get_htlc_redeemscript(&received_htlc, true, &keys).to_v0_p2wsh().to_hex(),
1777 "0020b70d0649c72b38756885c7a30908d912a7898dd5d79457a7280b8e9a20f3f2bc");
1778 assert_eq!(get_htlc_redeemscript(&offered_htlc, true, &keys).to_v0_p2wsh().to_hex(),
1779 "002087a3faeb1950a469c0e2db4a79b093a41b9526e5a6fc6ef5cb949bde3be379c7");
1783 fn test_per_commitment_storage() {
1784 // Test vectors from BOLT 3:
1785 let mut secrets: Vec<[u8; 32]> = Vec::new();
1788 macro_rules! test_secrets {
1790 let mut idx = 281474976710655;
1791 for secret in secrets.iter() {
1792 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1795 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1796 assert!(monitor.get_secret(idx).is_none());
1801 // insert_secret correct sequence
1802 monitor = CounterpartyCommitmentSecrets::new();
1805 secrets.push([0; 32]);
1806 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1807 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1810 secrets.push([0; 32]);
1811 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1812 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1815 secrets.push([0; 32]);
1816 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1817 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1820 secrets.push([0; 32]);
1821 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1822 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1825 secrets.push([0; 32]);
1826 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1827 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1830 secrets.push([0; 32]);
1831 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1832 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1835 secrets.push([0; 32]);
1836 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1837 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1840 secrets.push([0; 32]);
1841 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1842 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
1847 // insert_secret #1 incorrect
1848 monitor = CounterpartyCommitmentSecrets::new();
1851 secrets.push([0; 32]);
1852 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1853 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1856 secrets.push([0; 32]);
1857 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1858 assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
1862 // insert_secret #2 incorrect (#1 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("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").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("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1883 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1887 // insert_secret #3 incorrect
1888 monitor = CounterpartyCommitmentSecrets::new();
1891 secrets.push([0; 32]);
1892 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1893 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1896 secrets.push([0; 32]);
1897 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1898 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1901 secrets.push([0; 32]);
1902 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1903 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1906 secrets.push([0; 32]);
1907 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1908 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
1912 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
1913 monitor = CounterpartyCommitmentSecrets::new();
1916 secrets.push([0; 32]);
1917 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1918 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1921 secrets.push([0; 32]);
1922 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1923 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1926 secrets.push([0; 32]);
1927 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
1928 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1931 secrets.push([0; 32]);
1932 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
1933 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1936 secrets.push([0; 32]);
1937 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1938 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1941 secrets.push([0; 32]);
1942 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1943 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1946 secrets.push([0; 32]);
1947 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1948 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1951 secrets.push([0; 32]);
1952 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1953 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
1957 // insert_secret #5 incorrect
1958 monitor = CounterpartyCommitmentSecrets::new();
1961 secrets.push([0; 32]);
1962 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1963 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1966 secrets.push([0; 32]);
1967 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1968 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1971 secrets.push([0; 32]);
1972 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1973 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1976 secrets.push([0; 32]);
1977 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1978 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1981 secrets.push([0; 32]);
1982 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
1983 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1986 secrets.push([0; 32]);
1987 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1988 assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
1992 // insert_secret #6 incorrect (5 derived from incorrect)
1993 monitor = CounterpartyCommitmentSecrets::new();
1996 secrets.push([0; 32]);
1997 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1998 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2001 secrets.push([0; 32]);
2002 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2003 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2006 secrets.push([0; 32]);
2007 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2008 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2011 secrets.push([0; 32]);
2012 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2013 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2016 secrets.push([0; 32]);
2017 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2018 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2021 secrets.push([0; 32]);
2022 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
2023 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2026 secrets.push([0; 32]);
2027 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2028 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2031 secrets.push([0; 32]);
2032 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2033 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2037 // insert_secret #7 incorrect
2038 monitor = CounterpartyCommitmentSecrets::new();
2041 secrets.push([0; 32]);
2042 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2043 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2046 secrets.push([0; 32]);
2047 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2048 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2051 secrets.push([0; 32]);
2052 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2053 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2056 secrets.push([0; 32]);
2057 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2058 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2061 secrets.push([0; 32]);
2062 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2063 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2066 secrets.push([0; 32]);
2067 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2068 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2071 secrets.push([0; 32]);
2072 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2073 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2076 secrets.push([0; 32]);
2077 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2078 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2082 // insert_secret #8 incorrect
2083 monitor = CounterpartyCommitmentSecrets::new();
2086 secrets.push([0; 32]);
2087 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2088 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2091 secrets.push([0; 32]);
2092 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2093 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2096 secrets.push([0; 32]);
2097 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2098 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2101 secrets.push([0; 32]);
2102 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2103 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2106 secrets.push([0; 32]);
2107 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2108 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2111 secrets.push([0; 32]);
2112 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2113 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2116 secrets.push([0; 32]);
2117 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2118 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2121 secrets.push([0; 32]);
2122 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2123 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());