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 related to channels. These are
11 //! largely of interest for those implementing the traits on [`crate::sign`] by hand.
13 use bitcoin::{PubkeyHash, WPubkeyHash};
14 use bitcoin::amount::Amount;
15 use bitcoin::blockdata::script::{Script, ScriptBuf, Builder};
16 use bitcoin::blockdata::opcodes;
17 use bitcoin::blockdata::transaction::{TxIn,TxOut,OutPoint,Transaction};
19 use bitcoin::sighash::EcdsaSighashType;
20 use bitcoin::transaction::Version;
22 use bitcoin::hashes::{Hash, HashEngine};
23 use bitcoin::hashes::hash160::Hash as Hash160;
24 use bitcoin::hashes::sha256::Hash as Sha256;
25 use bitcoin::hashes::ripemd160::Hash as Ripemd160;
26 use bitcoin::hash_types::Txid;
28 use crate::chain::chaininterface::fee_for_weight;
29 use crate::chain::package::WEIGHT_REVOKED_OUTPUT;
30 use crate::sign::EntropySource;
31 use crate::ln::types::{PaymentHash, PaymentPreimage};
32 use crate::ln::msgs::DecodeError;
33 use crate::util::ser::{Readable, RequiredWrapper, Writeable, Writer};
34 use crate::util::transaction_utils;
36 use bitcoin::blockdata::locktime::absolute::LockTime;
37 use bitcoin::ecdsa::Signature as BitcoinSignature;
38 use bitcoin::secp256k1::{SecretKey, PublicKey, Scalar};
39 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature, Message};
40 use bitcoin::{secp256k1, Sequence, Witness};
44 use crate::ln::chan_utils;
45 use crate::util::transaction_utils::sort_outputs;
46 use crate::ln::channel::{INITIAL_COMMITMENT_NUMBER, ANCHOR_OUTPUT_VALUE_SATOSHI};
49 use crate::ln::features::ChannelTypeFeatures;
50 use crate::crypto::utils::{sign, sign_with_aux_rand};
51 use super::channel_keys::{DelayedPaymentBasepoint, DelayedPaymentKey, HtlcKey, HtlcBasepoint, RevocationKey, RevocationBasepoint};
53 #[allow(unused_imports)]
54 use crate::prelude::*;
56 /// Maximum number of one-way in-flight HTLC (protocol-level value).
57 pub const MAX_HTLCS: u16 = 483;
58 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, non-anchor variant.
59 pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
60 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, anchor variant.
61 pub const OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS: usize = 136;
63 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
64 /// We define a range that encompasses both its non-anchors and anchors variants.
65 pub(crate) const MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 136;
66 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
67 /// We define a range that encompasses both its non-anchors and anchors variants.
68 /// This is the maximum post-anchor value.
69 pub const MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 143;
71 /// The upper bound weight of an anchor input.
72 pub const ANCHOR_INPUT_WITNESS_WEIGHT: u64 = 116;
73 /// The upper bound weight of an HTLC timeout input from a commitment transaction with anchor
75 pub const HTLC_TIMEOUT_INPUT_ANCHOR_WITNESS_WEIGHT: u64 = 288;
76 /// The upper bound weight of an HTLC success input from a commitment transaction with anchor
78 pub const HTLC_SUCCESS_INPUT_ANCHOR_WITNESS_WEIGHT: u64 = 327;
80 /// Gets the weight for an HTLC-Success transaction.
82 pub fn htlc_success_tx_weight(channel_type_features: &ChannelTypeFeatures) -> u64 {
83 const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
84 const HTLC_SUCCESS_ANCHOR_TX_WEIGHT: u64 = 706;
85 if channel_type_features.supports_anchors_zero_fee_htlc_tx() { HTLC_SUCCESS_ANCHOR_TX_WEIGHT } else { HTLC_SUCCESS_TX_WEIGHT }
88 /// Gets the weight for an HTLC-Timeout transaction.
90 pub fn htlc_timeout_tx_weight(channel_type_features: &ChannelTypeFeatures) -> u64 {
91 const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
92 const HTLC_TIMEOUT_ANCHOR_TX_WEIGHT: u64 = 666;
93 if channel_type_features.supports_anchors_zero_fee_htlc_tx() { HTLC_TIMEOUT_ANCHOR_TX_WEIGHT } else { HTLC_TIMEOUT_TX_WEIGHT }
96 /// Describes the type of HTLC claim as determined by analyzing the witness.
97 #[derive(PartialEq, Eq)]
99 /// Claims an offered output on a commitment transaction through the timeout path.
101 /// Claims an offered output on a commitment transaction through the success path.
103 /// Claims an accepted output on a commitment transaction through the timeout path.
105 /// Claims an accepted output on a commitment transaction through the success path.
107 /// Claims an offered/accepted output on a commitment transaction through the revocation path.
112 /// Check if a given input witness attempts to claim a HTLC.
113 pub fn from_witness(witness: &Witness) -> Option<Self> {
114 debug_assert_eq!(OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS, MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT);
115 if witness.len() < 2 {
118 let witness_script = witness.last().unwrap();
119 let second_to_last = witness.second_to_last().unwrap();
120 if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT {
121 if witness.len() == 3 && second_to_last.len() == 33 {
122 // <revocation sig> <revocationpubkey> <witness_script>
123 Some(Self::Revocation)
124 } else if witness.len() == 3 && second_to_last.len() == 32 {
125 // <remotehtlcsig> <payment_preimage> <witness_script>
126 Some(Self::OfferedPreimage)
127 } else if witness.len() == 5 && second_to_last.len() == 0 {
128 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
129 Some(Self::OfferedTimeout)
133 } else if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS {
134 // It's possible for the weight of `offered_htlc_script` and `accepted_htlc_script` to
135 // match so we check for both here.
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() == 32 {
140 // <remotehtlcsig> <payment_preimage> <witness_script>
141 Some(Self::OfferedPreimage)
142 } else if witness.len() == 5 && second_to_last.len() == 0 {
143 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
144 Some(Self::OfferedTimeout)
145 } else if witness.len() == 3 && second_to_last.len() == 0 {
146 // <remotehtlcsig> <> <witness_script>
147 Some(Self::AcceptedTimeout)
148 } else if witness.len() == 5 && second_to_last.len() == 32 {
149 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
150 Some(Self::AcceptedPreimage)
154 } else if witness_script.len() > MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT &&
155 witness_script.len() <= MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT {
156 // Handle remaining range of ACCEPTED_HTLC_SCRIPT_WEIGHT.
157 if witness.len() == 3 && second_to_last.len() == 33 {
158 // <revocation sig> <revocationpubkey> <witness_script>
159 Some(Self::Revocation)
160 } else if witness.len() == 3 && second_to_last.len() == 0 {
161 // <remotehtlcsig> <> <witness_script>
162 Some(Self::AcceptedTimeout)
163 } else if witness.len() == 5 && second_to_last.len() == 32 {
164 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
165 Some(Self::AcceptedPreimage)
175 // Various functions for key derivation and transaction creation for use within channels. Primarily
176 // used in Channel and ChannelMonitor.
178 /// Build the commitment secret from the seed and the commitment number
179 pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
180 let mut res: [u8; 32] = commitment_seed.clone();
183 if idx & (1 << bitpos) == (1 << bitpos) {
184 res[bitpos / 8] ^= 1 << (bitpos & 7);
185 res = Sha256::hash(&res).to_byte_array();
191 /// Build a closing transaction
192 pub fn build_closing_transaction(to_holder_value_sat: Amount, to_counterparty_value_sat: Amount, to_holder_script: ScriptBuf, to_counterparty_script: ScriptBuf, funding_outpoint: OutPoint) -> Transaction {
194 let mut ins: Vec<TxIn> = Vec::new();
196 previous_output: funding_outpoint,
197 script_sig: ScriptBuf::new(),
198 sequence: Sequence::MAX,
199 witness: Witness::new(),
204 let mut txouts: Vec<(TxOut, ())> = Vec::new();
206 if to_counterparty_value_sat > Amount::ZERO {
208 script_pubkey: to_counterparty_script,
209 value: to_counterparty_value_sat
213 if to_holder_value_sat > Amount::ZERO {
215 script_pubkey: to_holder_script,
216 value: to_holder_value_sat
220 transaction_utils::sort_outputs(&mut txouts, |_, _| { cmp::Ordering::Equal }); // Ordering doesnt matter if they used our pubkey...
222 let mut outputs: Vec<TxOut> = Vec::new();
223 for out in txouts.drain(..) {
228 version: Version::TWO,
229 lock_time: LockTime::ZERO,
235 /// Implements the per-commitment secret storage scheme from
236 /// [BOLT 3](https://github.com/lightning/bolts/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
238 /// Allows us to keep track of all of the revocation secrets of our counterparty in just 50*32 bytes
241 pub struct CounterpartyCommitmentSecrets {
242 old_secrets: [([u8; 32], u64); 49],
245 impl Eq for CounterpartyCommitmentSecrets {}
246 impl PartialEq for CounterpartyCommitmentSecrets {
247 fn eq(&self, other: &Self) -> bool {
248 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
249 if secret != o_secret || idx != o_idx {
257 impl CounterpartyCommitmentSecrets {
258 /// Creates a new empty `CounterpartyCommitmentSecrets` structure.
259 pub fn new() -> Self {
260 Self { old_secrets: [([0; 32], 1 << 48); 49], }
264 fn place_secret(idx: u64) -> u8 {
266 if idx & (1 << i) == (1 << i) {
273 /// Returns the minimum index of all stored secrets. Note that indexes start
274 /// at 1 << 48 and get decremented by one for each new secret.
275 pub fn get_min_seen_secret(&self) -> u64 {
276 //TODO This can be optimized?
277 let mut min = 1 << 48;
278 for &(_, idx) in self.old_secrets.iter() {
287 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
288 let mut res: [u8; 32] = secret;
290 let bitpos = bits - 1 - i;
291 if idx & (1 << bitpos) == (1 << bitpos) {
292 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
293 res = Sha256::hash(&res).to_byte_array();
299 /// Inserts the `secret` at `idx`. Returns `Ok(())` if the secret
300 /// was generated in accordance with BOLT 3 and is consistent with previous secrets.
301 pub fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
302 let pos = Self::place_secret(idx);
304 let (old_secret, old_idx) = self.old_secrets[i as usize];
305 if Self::derive_secret(secret, pos, old_idx) != old_secret {
309 if self.get_min_seen_secret() <= idx {
312 self.old_secrets[pos as usize] = (secret, idx);
316 /// Returns the secret at `idx`.
317 /// Returns `None` if `idx` is < [`CounterpartyCommitmentSecrets::get_min_seen_secret`].
318 pub fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
319 for i in 0..self.old_secrets.len() {
320 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
321 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
324 assert!(idx < self.get_min_seen_secret());
329 impl Writeable for CounterpartyCommitmentSecrets {
330 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
331 for &(ref secret, ref idx) in self.old_secrets.iter() {
332 writer.write_all(secret)?;
333 writer.write_all(&idx.to_be_bytes())?;
335 write_tlv_fields!(writer, {});
339 impl Readable for CounterpartyCommitmentSecrets {
340 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
341 let mut old_secrets = [([0; 32], 1 << 48); 49];
342 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
343 *secret = Readable::read(reader)?;
344 *idx = Readable::read(reader)?;
346 read_tlv_fields!(reader, {});
347 Ok(Self { old_secrets })
351 /// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
352 /// from the base secret and the per_commitment_point.
353 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> SecretKey {
354 let mut sha = Sha256::engine();
355 sha.input(&per_commitment_point.serialize());
356 sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
357 let res = Sha256::from_engine(sha).to_byte_array();
359 base_secret.clone().add_tweak(&Scalar::from_be_bytes(res).unwrap())
360 .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.")
363 /// Derives a per-commitment-transaction revocation key from its constituent parts.
365 /// Only the cheating participant owns a valid witness to propagate a revoked
366 /// commitment transaction, thus per_commitment_secret always come from cheater
367 /// and revocation_base_secret always come from punisher, which is the broadcaster
368 /// of the transaction spending with this key knowledge.
369 pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>,
370 per_commitment_secret: &SecretKey, countersignatory_revocation_base_secret: &SecretKey)
372 let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
373 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
375 let rev_append_commit_hash_key = {
376 let mut sha = Sha256::engine();
377 sha.input(&countersignatory_revocation_base_point.serialize());
378 sha.input(&per_commitment_point.serialize());
380 Sha256::from_engine(sha).to_byte_array()
382 let commit_append_rev_hash_key = {
383 let mut sha = Sha256::engine();
384 sha.input(&per_commitment_point.serialize());
385 sha.input(&countersignatory_revocation_base_point.serialize());
387 Sha256::from_engine(sha).to_byte_array()
390 let countersignatory_contrib = countersignatory_revocation_base_secret.clone().mul_tweak(&Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
391 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
392 let broadcaster_contrib = per_commitment_secret.clone().mul_tweak(&Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
393 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
394 countersignatory_contrib.add_tweak(&Scalar::from_be_bytes(broadcaster_contrib.secret_bytes()).unwrap())
395 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
398 /// The set of public keys which are used in the creation of one commitment transaction.
399 /// These are derived from the channel base keys and per-commitment data.
401 /// A broadcaster key is provided from potential broadcaster of the computed transaction.
402 /// A countersignatory key is coming from a protocol participant unable to broadcast the
405 /// These keys are assumed to be good, either because the code derived them from
406 /// channel basepoints via the new function, or they were obtained via
407 /// CommitmentTransaction.trust().keys() because we trusted the source of the
408 /// pre-calculated keys.
409 #[derive(PartialEq, Eq, Clone, Debug)]
410 pub struct TxCreationKeys {
411 /// The broadcaster's per-commitment public key which was used to derive the other keys.
412 pub per_commitment_point: PublicKey,
413 /// The revocation key which is used to allow the broadcaster of the commitment
414 /// transaction to provide their counterparty the ability to punish them if they broadcast
416 pub revocation_key: RevocationKey,
417 /// Broadcaster's HTLC Key
418 pub broadcaster_htlc_key: HtlcKey,
419 /// Countersignatory's HTLC Key
420 pub countersignatory_htlc_key: HtlcKey,
421 /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
422 pub broadcaster_delayed_payment_key: DelayedPaymentKey,
425 impl_writeable_tlv_based!(TxCreationKeys, {
426 (0, per_commitment_point, required),
427 (2, revocation_key, required),
428 (4, broadcaster_htlc_key, required),
429 (6, countersignatory_htlc_key, required),
430 (8, broadcaster_delayed_payment_key, required),
433 /// One counterparty's public keys which do not change over the life of a channel.
434 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
435 pub struct ChannelPublicKeys {
436 /// The public key which is used to sign all commitment transactions, as it appears in the
437 /// on-chain channel lock-in 2-of-2 multisig output.
438 pub funding_pubkey: PublicKey,
439 /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
440 /// revocation keys. This is combined with the per-commitment-secret generated by the
441 /// counterparty to create a secret which the counterparty can reveal to revoke previous
443 pub revocation_basepoint: RevocationBasepoint,
444 /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
445 /// spendable primary channel balance on the broadcaster's commitment transaction. This key is
446 /// static across every commitment transaction.
447 pub payment_point: PublicKey,
448 /// The base point which is used (with derive_public_key) to derive a per-commitment payment
449 /// public key which receives non-HTLC-encumbered funds which are only available for spending
450 /// after some delay (or can be claimed via the revocation path).
451 pub delayed_payment_basepoint: DelayedPaymentBasepoint,
452 /// The base point which is used (with derive_public_key) to derive a per-commitment public key
453 /// which is used to encumber HTLC-in-flight outputs.
454 pub htlc_basepoint: HtlcBasepoint,
457 impl_writeable_tlv_based!(ChannelPublicKeys, {
458 (0, funding_pubkey, required),
459 (2, revocation_basepoint, required),
460 (4, payment_point, required),
461 (6, delayed_payment_basepoint, required),
462 (8, htlc_basepoint, required),
465 impl TxCreationKeys {
466 /// Create per-state keys from channel base points and the per-commitment point.
467 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
468 pub fn derive_new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, broadcaster_delayed_payment_base: &DelayedPaymentBasepoint, broadcaster_htlc_base: &HtlcBasepoint, countersignatory_revocation_base: &RevocationBasepoint, countersignatory_htlc_base: &HtlcBasepoint) -> TxCreationKeys {
470 per_commitment_point: per_commitment_point.clone(),
471 revocation_key: RevocationKey::from_basepoint(&secp_ctx, &countersignatory_revocation_base, &per_commitment_point),
472 broadcaster_htlc_key: HtlcKey::from_basepoint(&secp_ctx, &broadcaster_htlc_base, &per_commitment_point),
473 countersignatory_htlc_key: HtlcKey::from_basepoint(&secp_ctx, &countersignatory_htlc_base, &per_commitment_point),
474 broadcaster_delayed_payment_key: DelayedPaymentKey::from_basepoint(&secp_ctx, &broadcaster_delayed_payment_base, &per_commitment_point),
478 /// Generate per-state keys from channel static keys.
479 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
480 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 {
481 TxCreationKeys::derive_new(
483 &per_commitment_point,
484 &broadcaster_keys.delayed_payment_basepoint,
485 &broadcaster_keys.htlc_basepoint,
486 &countersignatory_keys.revocation_basepoint,
487 &countersignatory_keys.htlc_basepoint,
492 /// The maximum length of a script returned by get_revokeable_redeemscript.
493 // Calculated as 6 bytes of opcodes, 1 byte push plus 3 bytes for contest_delay, and two public
494 // keys of 33 bytes (+ 1 push). Generally, pushes are only 2 bytes (for values below 0x7fff, i.e.
495 // around 7 months), however, a 7 month contest delay shouldn't result in being unable to reclaim
497 pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 4 + 34*2;
499 /// A script either spendable by the revocation
500 /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
501 /// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
502 pub fn get_revokeable_redeemscript(revocation_key: &RevocationKey, contest_delay: u16, broadcaster_delayed_payment_key: &DelayedPaymentKey) -> ScriptBuf {
503 let res = Builder::new().push_opcode(opcodes::all::OP_IF)
504 .push_slice(&revocation_key.to_public_key().serialize())
505 .push_opcode(opcodes::all::OP_ELSE)
506 .push_int(contest_delay as i64)
507 .push_opcode(opcodes::all::OP_CSV)
508 .push_opcode(opcodes::all::OP_DROP)
509 .push_slice(&broadcaster_delayed_payment_key.to_public_key().serialize())
510 .push_opcode(opcodes::all::OP_ENDIF)
511 .push_opcode(opcodes::all::OP_CHECKSIG)
513 debug_assert!(res.len() <= REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH);
517 /// Returns the script for the counterparty's output on a holder's commitment transaction based on
518 /// the channel type.
519 pub fn get_counterparty_payment_script(channel_type_features: &ChannelTypeFeatures, payment_key: &PublicKey) -> ScriptBuf {
520 if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
521 get_to_countersignatory_with_anchors_redeemscript(payment_key).to_p2wsh()
523 ScriptBuf::new_p2wpkh(&WPubkeyHash::hash(&payment_key.serialize()))
527 /// Information about an HTLC as it appears in a commitment transaction
528 #[derive(Clone, Debug, PartialEq, Eq)]
529 pub struct HTLCOutputInCommitment {
530 /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
531 /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
532 /// need to compare this value to whether the commitment transaction in question is that of
533 /// the counterparty or our own.
535 /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
536 /// this divided by 1000.
537 pub amount_msat: u64,
538 /// The CLTV lock-time at which this HTLC expires.
539 pub cltv_expiry: u32,
540 /// The hash of the preimage which unlocks this HTLC.
541 pub payment_hash: PaymentHash,
542 /// The position within the commitment transactions' outputs. This may be None if the value is
543 /// below the dust limit (in which case no output appears in the commitment transaction and the
544 /// value is spent to additional transaction fees).
545 pub transaction_output_index: Option<u32>,
548 impl HTLCOutputInCommitment {
549 /// Converts HTLC's value with millisatoshi precision into [bitcoin::Amount] with satoshi precision.
550 /// Typically this conversion is needed when transitioning from LN into base-layer Bitcoin,
551 /// e. g. in commitment transactions.
552 pub const fn to_bitcoin_amount(&self) -> Amount {
553 Amount::from_sat(self.amount_msat / 1000)
557 impl_writeable_tlv_based!(HTLCOutputInCommitment, {
558 (0, offered, required),
559 (2, amount_msat, required),
560 (4, cltv_expiry, required),
561 (6, payment_hash, required),
562 (8, transaction_output_index, option),
566 pub(crate) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, broadcaster_htlc_key: &HtlcKey, countersignatory_htlc_key: &HtlcKey, revocation_key: &RevocationKey) -> ScriptBuf {
567 let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).to_byte_array();
569 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
570 .push_opcode(opcodes::all::OP_HASH160)
571 .push_slice(PubkeyHash::hash(&revocation_key.to_public_key().serialize()))
572 .push_opcode(opcodes::all::OP_EQUAL)
573 .push_opcode(opcodes::all::OP_IF)
574 .push_opcode(opcodes::all::OP_CHECKSIG)
575 .push_opcode(opcodes::all::OP_ELSE)
576 .push_slice(&countersignatory_htlc_key.to_public_key().serialize())
577 .push_opcode(opcodes::all::OP_SWAP)
578 .push_opcode(opcodes::all::OP_SIZE)
580 .push_opcode(opcodes::all::OP_EQUAL)
581 .push_opcode(opcodes::all::OP_NOTIF)
582 .push_opcode(opcodes::all::OP_DROP)
584 .push_opcode(opcodes::all::OP_SWAP)
585 .push_slice(&broadcaster_htlc_key.to_public_key().serialize())
587 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
588 .push_opcode(opcodes::all::OP_ELSE)
589 .push_opcode(opcodes::all::OP_HASH160)
590 .push_slice(&payment_hash160)
591 .push_opcode(opcodes::all::OP_EQUALVERIFY)
592 .push_opcode(opcodes::all::OP_CHECKSIG)
593 .push_opcode(opcodes::all::OP_ENDIF);
594 if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
595 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
596 .push_opcode(opcodes::all::OP_CSV)
597 .push_opcode(opcodes::all::OP_DROP);
599 bldr.push_opcode(opcodes::all::OP_ENDIF)
602 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
603 .push_opcode(opcodes::all::OP_HASH160)
604 .push_slice(&PubkeyHash::hash(&revocation_key.to_public_key().serialize()))
605 .push_opcode(opcodes::all::OP_EQUAL)
606 .push_opcode(opcodes::all::OP_IF)
607 .push_opcode(opcodes::all::OP_CHECKSIG)
608 .push_opcode(opcodes::all::OP_ELSE)
609 .push_slice(&countersignatory_htlc_key.to_public_key().serialize())
610 .push_opcode(opcodes::all::OP_SWAP)
611 .push_opcode(opcodes::all::OP_SIZE)
613 .push_opcode(opcodes::all::OP_EQUAL)
614 .push_opcode(opcodes::all::OP_IF)
615 .push_opcode(opcodes::all::OP_HASH160)
616 .push_slice(&payment_hash160)
617 .push_opcode(opcodes::all::OP_EQUALVERIFY)
619 .push_opcode(opcodes::all::OP_SWAP)
620 .push_slice(&broadcaster_htlc_key.to_public_key().serialize())
622 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
623 .push_opcode(opcodes::all::OP_ELSE)
624 .push_opcode(opcodes::all::OP_DROP)
625 .push_int(htlc.cltv_expiry as i64)
626 .push_opcode(opcodes::all::OP_CLTV)
627 .push_opcode(opcodes::all::OP_DROP)
628 .push_opcode(opcodes::all::OP_CHECKSIG)
629 .push_opcode(opcodes::all::OP_ENDIF);
630 if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
631 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
632 .push_opcode(opcodes::all::OP_CSV)
633 .push_opcode(opcodes::all::OP_DROP);
635 bldr.push_opcode(opcodes::all::OP_ENDIF)
640 /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
641 /// does not need to have its previous_output_index filled.
643 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, keys: &TxCreationKeys) -> ScriptBuf {
644 get_htlc_redeemscript_with_explicit_keys(htlc, channel_type_features, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
647 /// Gets the redeemscript for a funding output from the two funding public keys.
648 /// Note that the order of funding public keys does not matter.
649 pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> ScriptBuf {
650 let broadcaster_funding_key = broadcaster.serialize();
651 let countersignatory_funding_key = countersignatory.serialize();
653 make_funding_redeemscript_from_slices(&broadcaster_funding_key, &countersignatory_funding_key)
656 pub(crate) fn make_funding_redeemscript_from_slices(broadcaster_funding_key: &[u8; 33], countersignatory_funding_key: &[u8; 33]) -> ScriptBuf {
657 let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
658 if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
659 builder.push_slice(broadcaster_funding_key)
660 .push_slice(countersignatory_funding_key)
662 builder.push_slice(countersignatory_funding_key)
663 .push_slice(broadcaster_funding_key)
664 }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
667 /// Builds an unsigned HTLC-Success or HTLC-Timeout transaction from the given channel and HTLC
668 /// parameters. This is used by [`TrustedCommitmentTransaction::get_htlc_sigs`] to fetch the
669 /// transaction which needs signing, and can be used to construct an HTLC transaction which is
670 /// broadcastable given a counterparty HTLC signature.
672 /// Panics if htlc.transaction_output_index.is_none() (as such HTLCs do not appear in the
673 /// commitment transaction).
674 pub fn build_htlc_transaction(commitment_txid: &Txid, feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, broadcaster_delayed_payment_key: &DelayedPaymentKey, revocation_key: &RevocationKey) -> Transaction {
675 let mut txins: Vec<TxIn> = Vec::new();
676 txins.push(build_htlc_input(commitment_txid, htlc, channel_type_features));
678 let mut txouts: Vec<TxOut> = Vec::new();
679 txouts.push(build_htlc_output(
680 feerate_per_kw, contest_delay, htlc, channel_type_features,
681 broadcaster_delayed_payment_key, revocation_key
685 version: Version::TWO,
686 lock_time: LockTime::from_consensus(if htlc.offered { htlc.cltv_expiry } else { 0 }),
692 pub(crate) fn build_htlc_input(commitment_txid: &Txid, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures) -> TxIn {
694 previous_output: OutPoint {
695 txid: commitment_txid.clone(),
696 vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
698 script_sig: ScriptBuf::new(),
699 sequence: Sequence(if channel_type_features.supports_anchors_zero_fee_htlc_tx() { 1 } else { 0 }),
700 witness: Witness::new(),
704 pub(crate) fn build_htlc_output(
705 feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, broadcaster_delayed_payment_key: &DelayedPaymentKey, revocation_key: &RevocationKey
707 let weight = if htlc.offered {
708 htlc_timeout_tx_weight(channel_type_features)
710 htlc_success_tx_weight(channel_type_features)
712 let output_value = if channel_type_features.supports_anchors_zero_fee_htlc_tx() && !channel_type_features.supports_anchors_nonzero_fee_htlc_tx() {
713 htlc.to_bitcoin_amount()
715 let total_fee = Amount::from_sat(feerate_per_kw as u64 * weight / 1000);
716 htlc.to_bitcoin_amount() - total_fee
720 script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_p2wsh(),
725 /// Returns the witness required to satisfy and spend a HTLC input.
726 pub fn build_htlc_input_witness(
727 local_sig: &Signature, remote_sig: &Signature, preimage: &Option<PaymentPreimage>,
728 redeem_script: &Script, channel_type_features: &ChannelTypeFeatures,
730 let remote_sighash_type = if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
731 EcdsaSighashType::SinglePlusAnyoneCanPay
733 EcdsaSighashType::All
736 let mut witness = Witness::new();
737 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
738 witness.push(vec![]);
739 witness.push_ecdsa_signature(&BitcoinSignature { sig: *remote_sig, hash_ty: remote_sighash_type });
740 witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(*local_sig));
741 if let Some(preimage) = preimage {
742 witness.push(preimage.0.to_vec());
744 // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
745 witness.push(vec![]);
747 witness.push(redeem_script.to_bytes());
751 /// Pre-anchors channel type features did not use to get serialized in the following six structs:
752 /// — [`ChannelTransactionParameters`]
753 /// — [`CommitmentTransaction`]
754 /// — [`CounterpartyOfferedHTLCOutput`]
755 /// — [`CounterpartyReceivedHTLCOutput`]
756 /// — [`HolderHTLCOutput`]
757 /// — [`HolderFundingOutput`]
759 /// To ensure a forwards-compatible serialization, we use odd TLV fields. However, if new features
760 /// are used that could break security, where old signers should be prevented from handling the
761 /// serialized data, an optional even-field TLV will be used as a stand-in to break compatibility.
763 /// This method determines whether or not that option needs to be set based on the chanenl type
764 /// features, and returns it.
766 /// [`CounterpartyOfferedHTLCOutput`]: crate::chain::package::CounterpartyOfferedHTLCOutput
767 /// [`CounterpartyReceivedHTLCOutput`]: crate::chain::package::CounterpartyReceivedHTLCOutput
768 /// [`HolderHTLCOutput`]: crate::chain::package::HolderHTLCOutput
769 /// [`HolderFundingOutput`]: crate::chain::package::HolderFundingOutput
770 pub(crate) fn legacy_deserialization_prevention_marker_for_channel_type_features(features: &ChannelTypeFeatures) -> Option<()> {
771 let mut legacy_version_bit_set = ChannelTypeFeatures::only_static_remote_key();
772 legacy_version_bit_set.set_scid_privacy_required();
773 legacy_version_bit_set.set_zero_conf_required();
775 if features.is_subset(&legacy_version_bit_set) {
782 /// Gets the witnessScript for the to_remote output when anchors are enabled.
784 pub fn get_to_countersignatory_with_anchors_redeemscript(payment_point: &PublicKey) -> ScriptBuf {
786 .push_slice(payment_point.serialize())
787 .push_opcode(opcodes::all::OP_CHECKSIGVERIFY)
789 .push_opcode(opcodes::all::OP_CSV)
793 /// Gets the witnessScript for an anchor output from the funding public key.
794 /// The witness in the spending input must be:
795 /// <BIP 143 funding_signature>
796 /// After 16 blocks of confirmation, an alternative satisfying witness could be:
798 /// (empty vector required to satisfy compliance with MINIMALIF-standard rule)
800 pub fn get_anchor_redeemscript(funding_pubkey: &PublicKey) -> ScriptBuf {
801 Builder::new().push_slice(funding_pubkey.serialize())
802 .push_opcode(opcodes::all::OP_CHECKSIG)
803 .push_opcode(opcodes::all::OP_IFDUP)
804 .push_opcode(opcodes::all::OP_NOTIF)
806 .push_opcode(opcodes::all::OP_CSV)
807 .push_opcode(opcodes::all::OP_ENDIF)
811 /// Locates the output with an anchor script paying to `funding_pubkey` within `commitment_tx`.
812 pub(crate) fn get_anchor_output<'a>(commitment_tx: &'a Transaction, funding_pubkey: &PublicKey) -> Option<(u32, &'a TxOut)> {
813 let anchor_script = chan_utils::get_anchor_redeemscript(funding_pubkey).to_p2wsh();
814 commitment_tx.output.iter().enumerate()
815 .find(|(_, txout)| txout.script_pubkey == anchor_script)
816 .map(|(idx, txout)| (idx as u32, txout))
819 /// Returns the witness required to satisfy and spend an anchor input.
820 pub fn build_anchor_input_witness(funding_key: &PublicKey, funding_sig: &Signature) -> Witness {
821 let anchor_redeem_script = chan_utils::get_anchor_redeemscript(funding_key);
822 let mut ret = Witness::new();
823 ret.push_ecdsa_signature(&BitcoinSignature::sighash_all(*funding_sig));
824 ret.push(anchor_redeem_script.as_bytes());
828 /// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
829 /// The fields are organized by holder/counterparty.
831 /// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
832 /// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
833 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
834 pub struct ChannelTransactionParameters {
835 /// Holder public keys
836 pub holder_pubkeys: ChannelPublicKeys,
837 /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
838 pub holder_selected_contest_delay: u16,
839 /// Whether the holder is the initiator of this channel.
840 /// This is an input to the commitment number obscure factor computation.
841 pub is_outbound_from_holder: bool,
842 /// The late-bound counterparty channel transaction parameters.
843 /// These parameters are populated at the point in the protocol where the counterparty provides them.
844 pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
845 /// The late-bound funding outpoint
846 pub funding_outpoint: Option<chain::transaction::OutPoint>,
847 /// This channel's type, as negotiated during channel open. For old objects where this field
848 /// wasn't serialized, it will default to static_remote_key at deserialization.
849 pub channel_type_features: ChannelTypeFeatures
852 /// Late-bound per-channel counterparty data used to build transactions.
853 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
854 pub struct CounterpartyChannelTransactionParameters {
855 /// Counter-party public keys
856 pub pubkeys: ChannelPublicKeys,
857 /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
858 pub selected_contest_delay: u16,
861 impl ChannelTransactionParameters {
862 /// Whether the late bound parameters are populated.
863 pub fn is_populated(&self) -> bool {
864 self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
867 /// Whether the channel supports zero-fee HTLC transaction anchors.
868 pub(crate) fn supports_anchors(&self) -> bool {
869 self.channel_type_features.supports_anchors_zero_fee_htlc_tx()
872 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
873 /// given that the holder is the broadcaster.
875 /// self.is_populated() must be true before calling this function.
876 pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
877 assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
878 DirectedChannelTransactionParameters {
880 holder_is_broadcaster: true
884 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
885 /// given that the counterparty is the broadcaster.
887 /// self.is_populated() must be true before calling this function.
888 pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
889 assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
890 DirectedChannelTransactionParameters {
892 holder_is_broadcaster: false
897 impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, {
898 (0, pubkeys, required),
899 (2, selected_contest_delay, required),
902 impl Writeable for ChannelTransactionParameters {
903 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
904 let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
905 write_tlv_fields!(writer, {
906 (0, self.holder_pubkeys, required),
907 (2, self.holder_selected_contest_delay, required),
908 (4, self.is_outbound_from_holder, required),
909 (6, self.counterparty_parameters, option),
910 (8, self.funding_outpoint, option),
911 (10, legacy_deserialization_prevention_marker, option),
912 (11, self.channel_type_features, required),
918 impl Readable for ChannelTransactionParameters {
919 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
920 let mut holder_pubkeys = RequiredWrapper(None);
921 let mut holder_selected_contest_delay = RequiredWrapper(None);
922 let mut is_outbound_from_holder = RequiredWrapper(None);
923 let mut counterparty_parameters = None;
924 let mut funding_outpoint = None;
925 let mut _legacy_deserialization_prevention_marker: Option<()> = None;
926 let mut channel_type_features = None;
928 read_tlv_fields!(reader, {
929 (0, holder_pubkeys, required),
930 (2, holder_selected_contest_delay, required),
931 (4, is_outbound_from_holder, required),
932 (6, counterparty_parameters, option),
933 (8, funding_outpoint, option),
934 (10, _legacy_deserialization_prevention_marker, option),
935 (11, channel_type_features, option),
938 let mut additional_features = ChannelTypeFeatures::empty();
939 additional_features.set_anchors_nonzero_fee_htlc_tx_required();
940 chain::package::verify_channel_type_features(&channel_type_features, Some(&additional_features))?;
943 holder_pubkeys: holder_pubkeys.0.unwrap(),
944 holder_selected_contest_delay: holder_selected_contest_delay.0.unwrap(),
945 is_outbound_from_holder: is_outbound_from_holder.0.unwrap(),
946 counterparty_parameters,
948 channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
953 /// Static channel fields used to build transactions given per-commitment fields, organized by
954 /// broadcaster/countersignatory.
956 /// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
957 /// as_holder_broadcastable and as_counterparty_broadcastable functions.
958 pub struct DirectedChannelTransactionParameters<'a> {
959 /// The holder's channel static parameters
960 inner: &'a ChannelTransactionParameters,
961 /// Whether the holder is the broadcaster
962 holder_is_broadcaster: bool,
965 impl<'a> DirectedChannelTransactionParameters<'a> {
966 /// Get the channel pubkeys for the broadcaster
967 pub fn broadcaster_pubkeys(&self) -> &'a ChannelPublicKeys {
968 if self.holder_is_broadcaster {
969 &self.inner.holder_pubkeys
971 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
975 /// Get the channel pubkeys for the countersignatory
976 pub fn countersignatory_pubkeys(&self) -> &'a ChannelPublicKeys {
977 if self.holder_is_broadcaster {
978 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
980 &self.inner.holder_pubkeys
984 /// Get the contest delay applicable to the transactions.
985 /// Note that the contest delay was selected by the countersignatory.
986 pub fn contest_delay(&self) -> u16 {
987 let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
988 if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
991 /// Whether the channel is outbound from the broadcaster.
993 /// The boolean representing the side that initiated the channel is
994 /// an input to the commitment number obscure factor computation.
995 pub fn is_outbound(&self) -> bool {
996 if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
999 /// The funding outpoint
1000 pub fn funding_outpoint(&self) -> OutPoint {
1001 self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
1004 /// Whether to use anchors for this channel
1005 pub fn channel_type_features(&self) -> &'a ChannelTypeFeatures {
1006 &self.inner.channel_type_features
1010 /// Information needed to build and sign a holder's commitment transaction.
1012 /// The transaction is only signed once we are ready to broadcast.
1013 #[derive(Clone, Debug)]
1014 pub struct HolderCommitmentTransaction {
1015 inner: CommitmentTransaction,
1016 /// Our counterparty's signature for the transaction
1017 pub counterparty_sig: Signature,
1018 /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
1019 pub counterparty_htlc_sigs: Vec<Signature>,
1020 // Which order the signatures should go in when constructing the final commitment tx witness.
1021 // The user should be able to reconstruct this themselves, so we don't bother to expose it.
1022 holder_sig_first: bool,
1025 impl Deref for HolderCommitmentTransaction {
1026 type Target = CommitmentTransaction;
1028 fn deref(&self) -> &Self::Target { &self.inner }
1031 impl Eq for HolderCommitmentTransaction {}
1032 impl PartialEq for HolderCommitmentTransaction {
1033 // We dont care whether we are signed in equality comparison
1034 fn eq(&self, o: &Self) -> bool {
1035 self.inner == o.inner
1039 impl_writeable_tlv_based!(HolderCommitmentTransaction, {
1040 (0, inner, required),
1041 (2, counterparty_sig, required),
1042 (4, holder_sig_first, required),
1043 (6, counterparty_htlc_sigs, required_vec),
1046 impl HolderCommitmentTransaction {
1048 pub fn dummy(htlcs: &mut Vec<(HTLCOutputInCommitment, ())>) -> Self {
1049 let secp_ctx = Secp256k1::new();
1050 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1051 let dummy_sig = sign(&secp_ctx, &secp256k1::Message::from_digest([42; 32]), &SecretKey::from_slice(&[42; 32]).unwrap());
1053 let keys = TxCreationKeys {
1054 per_commitment_point: dummy_key.clone(),
1055 revocation_key: RevocationKey::from_basepoint(&secp_ctx, &RevocationBasepoint::from(dummy_key), &dummy_key),
1056 broadcaster_htlc_key: HtlcKey::from_basepoint(&secp_ctx, &HtlcBasepoint::from(dummy_key), &dummy_key),
1057 countersignatory_htlc_key: HtlcKey::from_basepoint(&secp_ctx, &HtlcBasepoint::from(dummy_key), &dummy_key),
1058 broadcaster_delayed_payment_key: DelayedPaymentKey::from_basepoint(&secp_ctx, &DelayedPaymentBasepoint::from(dummy_key), &dummy_key),
1060 let channel_pubkeys = ChannelPublicKeys {
1061 funding_pubkey: dummy_key.clone(),
1062 revocation_basepoint: RevocationBasepoint::from(dummy_key),
1063 payment_point: dummy_key.clone(),
1064 delayed_payment_basepoint: DelayedPaymentBasepoint::from(dummy_key.clone()),
1065 htlc_basepoint: HtlcBasepoint::from(dummy_key.clone())
1067 let channel_parameters = ChannelTransactionParameters {
1068 holder_pubkeys: channel_pubkeys.clone(),
1069 holder_selected_contest_delay: 0,
1070 is_outbound_from_holder: false,
1071 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
1072 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1073 channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
1075 let mut counterparty_htlc_sigs = Vec::new();
1076 for _ in 0..htlcs.len() {
1077 counterparty_htlc_sigs.push(dummy_sig);
1079 let inner = CommitmentTransaction::new_with_auxiliary_htlc_data(0, 0, 0, dummy_key.clone(), dummy_key.clone(), keys, 0, htlcs, &channel_parameters.as_counterparty_broadcastable());
1080 htlcs.sort_by_key(|htlc| htlc.0.transaction_output_index);
1081 HolderCommitmentTransaction {
1083 counterparty_sig: dummy_sig,
1084 counterparty_htlc_sigs,
1085 holder_sig_first: false
1089 /// Create a new holder transaction with the given counterparty signatures.
1090 /// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
1091 pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
1093 inner: commitment_tx,
1095 counterparty_htlc_sigs,
1096 holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
1100 pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
1101 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
1102 let mut tx = self.inner.built.transaction.clone();
1103 tx.input[0].witness.push(Vec::new());
1105 if self.holder_sig_first {
1106 tx.input[0].witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(holder_sig));
1107 tx.input[0].witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(self.counterparty_sig));
1109 tx.input[0].witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(self.counterparty_sig));
1110 tx.input[0].witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(holder_sig));
1113 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
1118 /// A pre-built Bitcoin commitment transaction and its txid.
1119 #[derive(Clone, Debug)]
1120 pub struct BuiltCommitmentTransaction {
1121 /// The commitment transaction
1122 pub transaction: Transaction,
1123 /// The txid for the commitment transaction.
1125 /// This is provided as a performance optimization, instead of calling transaction.txid()
1130 impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
1131 (0, transaction, required),
1132 (2, txid, required),
1135 impl BuiltCommitmentTransaction {
1136 /// Get the SIGHASH_ALL sighash value of the transaction.
1138 /// This can be used to verify a signature.
1139 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1140 let sighash = &sighash::SighashCache::new(&self.transaction).p2wsh_signature_hash(0, funding_redeemscript, Amount::from_sat(channel_value_satoshis), EcdsaSighashType::All).unwrap()[..];
1141 hash_to_message!(sighash)
1144 /// Signs the counterparty's commitment transaction.
1145 pub fn sign_counterparty_commitment<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1146 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1147 sign(secp_ctx, &sighash, funding_key)
1150 /// Signs the holder commitment transaction because we are about to broadcast it.
1151 pub fn sign_holder_commitment<T: secp256k1::Signing, ES: Deref>(
1152 &self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64,
1153 entropy_source: &ES, secp_ctx: &Secp256k1<T>
1154 ) -> Signature where ES::Target: EntropySource {
1155 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1156 sign_with_aux_rand(secp_ctx, &sighash, funding_key, entropy_source)
1160 /// This class tracks the per-transaction information needed to build a closing transaction and will
1161 /// actually build it and sign.
1163 /// This class can be used inside a signer implementation to generate a signature given the relevant
1165 #[derive(Clone, Hash, PartialEq, Eq)]
1166 pub struct ClosingTransaction {
1167 to_holder_value_sat: Amount,
1168 to_counterparty_value_sat: Amount,
1169 to_holder_script: ScriptBuf,
1170 to_counterparty_script: ScriptBuf,
1174 impl ClosingTransaction {
1175 /// Construct an object of the class
1177 to_holder_value_sat: u64,
1178 to_counterparty_value_sat: u64,
1179 to_holder_script: ScriptBuf,
1180 to_counterparty_script: ScriptBuf,
1181 funding_outpoint: OutPoint,
1183 let to_holder_value_sat = Amount::from_sat(to_holder_value_sat);
1184 let to_counterparty_value_sat = Amount::from_sat(to_counterparty_value_sat);
1185 let built = build_closing_transaction(
1186 to_holder_value_sat, to_counterparty_value_sat,
1187 to_holder_script.clone(), to_counterparty_script.clone(),
1190 ClosingTransaction {
1191 to_holder_value_sat,
1192 to_counterparty_value_sat,
1194 to_counterparty_script,
1199 /// Trust our pre-built transaction.
1201 /// Applies a wrapper which allows access to the transaction.
1203 /// This should only be used if you fully trust the builder of this object. It should not
1204 /// be used by an external signer - instead use the verify function.
1205 pub fn trust(&self) -> TrustedClosingTransaction {
1206 TrustedClosingTransaction { inner: self }
1209 /// Verify our pre-built transaction.
1211 /// Applies a wrapper which allows access to the transaction.
1213 /// An external validating signer must call this method before signing
1214 /// or using the built transaction.
1215 pub fn verify(&self, funding_outpoint: OutPoint) -> Result<TrustedClosingTransaction, ()> {
1216 let built = build_closing_transaction(
1217 self.to_holder_value_sat, self.to_counterparty_value_sat,
1218 self.to_holder_script.clone(), self.to_counterparty_script.clone(),
1221 if self.built != built {
1224 Ok(TrustedClosingTransaction { inner: self })
1227 /// The value to be sent to the holder, or zero if the output will be omitted
1228 pub fn to_holder_value_sat(&self) -> u64 {
1229 self.to_holder_value_sat.to_sat()
1232 /// The value to be sent to the counterparty, or zero if the output will be omitted
1233 pub fn to_counterparty_value_sat(&self) -> u64 {
1234 self.to_counterparty_value_sat.to_sat()
1237 /// The destination of the holder's output
1238 pub fn to_holder_script(&self) -> &Script {
1239 &self.to_holder_script
1242 /// The destination of the counterparty's output
1243 pub fn to_counterparty_script(&self) -> &Script {
1244 &self.to_counterparty_script
1248 /// A wrapper on ClosingTransaction indicating that the built bitcoin
1249 /// transaction is trusted.
1251 /// See trust() and verify() functions on CommitmentTransaction.
1253 /// This structure implements Deref.
1254 pub struct TrustedClosingTransaction<'a> {
1255 inner: &'a ClosingTransaction,
1258 impl<'a> Deref for TrustedClosingTransaction<'a> {
1259 type Target = ClosingTransaction;
1261 fn deref(&self) -> &Self::Target { self.inner }
1264 impl<'a> TrustedClosingTransaction<'a> {
1265 /// The pre-built Bitcoin commitment transaction
1266 pub fn built_transaction(&self) -> &'a Transaction {
1270 /// Get the SIGHASH_ALL sighash value of the transaction.
1272 /// This can be used to verify a signature.
1273 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1274 let sighash = &sighash::SighashCache::new(&self.inner.built).p2wsh_signature_hash(0, funding_redeemscript, Amount::from_sat(channel_value_satoshis), EcdsaSighashType::All).unwrap()[..];
1275 hash_to_message!(sighash)
1278 /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1279 /// because we are about to broadcast a holder transaction.
1280 pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1281 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1282 sign(secp_ctx, &sighash, funding_key)
1286 /// This class tracks the per-transaction information needed to build a commitment transaction and will
1287 /// actually build it and sign. It is used for holder transactions that we sign only when needed
1288 /// and for transactions we sign for the counterparty.
1290 /// This class can be used inside a signer implementation to generate a signature given the relevant
1292 #[derive(Clone, Debug)]
1293 pub struct CommitmentTransaction {
1294 commitment_number: u64,
1295 to_broadcaster_value_sat: Amount,
1296 to_countersignatory_value_sat: Amount,
1297 to_broadcaster_delay: Option<u16>, // Added in 0.0.117
1298 feerate_per_kw: u32,
1299 htlcs: Vec<HTLCOutputInCommitment>,
1300 // Note that on upgrades, some features of existing outputs may be missed.
1301 channel_type_features: ChannelTypeFeatures,
1302 // A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
1303 keys: TxCreationKeys,
1304 // For access to the pre-built transaction, see doc for trust()
1305 built: BuiltCommitmentTransaction,
1308 impl Eq for CommitmentTransaction {}
1309 impl PartialEq for CommitmentTransaction {
1310 fn eq(&self, o: &Self) -> bool {
1311 let eq = self.commitment_number == o.commitment_number &&
1312 self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
1313 self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
1314 self.feerate_per_kw == o.feerate_per_kw &&
1315 self.htlcs == o.htlcs &&
1316 self.channel_type_features == o.channel_type_features &&
1317 self.keys == o.keys;
1319 debug_assert_eq!(self.built.transaction, o.built.transaction);
1320 debug_assert_eq!(self.built.txid, o.built.txid);
1326 impl Writeable for CommitmentTransaction {
1327 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1328 let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
1329 write_tlv_fields!(writer, {
1330 (0, self.commitment_number, required),
1331 (1, self.to_broadcaster_delay, option),
1332 (2, self.to_broadcaster_value_sat, required),
1333 (4, self.to_countersignatory_value_sat, required),
1334 (6, self.feerate_per_kw, required),
1335 (8, self.keys, required),
1336 (10, self.built, required),
1337 (12, self.htlcs, required_vec),
1338 (14, legacy_deserialization_prevention_marker, option),
1339 (15, self.channel_type_features, required),
1345 impl Readable for CommitmentTransaction {
1346 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1347 _init_and_read_len_prefixed_tlv_fields!(reader, {
1348 (0, commitment_number, required),
1349 (1, to_broadcaster_delay, option),
1350 (2, to_broadcaster_value_sat, required),
1351 (4, to_countersignatory_value_sat, required),
1352 (6, feerate_per_kw, required),
1353 (8, keys, required),
1354 (10, built, required),
1355 (12, htlcs, required_vec),
1356 (14, _legacy_deserialization_prevention_marker, option),
1357 (15, channel_type_features, option),
1360 let mut additional_features = ChannelTypeFeatures::empty();
1361 additional_features.set_anchors_nonzero_fee_htlc_tx_required();
1362 chain::package::verify_channel_type_features(&channel_type_features, Some(&additional_features))?;
1365 commitment_number: commitment_number.0.unwrap(),
1366 to_broadcaster_value_sat: to_broadcaster_value_sat.0.unwrap(),
1367 to_countersignatory_value_sat: to_countersignatory_value_sat.0.unwrap(),
1368 to_broadcaster_delay,
1369 feerate_per_kw: feerate_per_kw.0.unwrap(),
1370 keys: keys.0.unwrap(),
1371 built: built.0.unwrap(),
1373 channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
1378 impl CommitmentTransaction {
1379 /// Construct an object of the class while assigning transaction output indices to HTLCs.
1381 /// Populates HTLCOutputInCommitment.transaction_output_index in htlcs_with_aux.
1383 /// The generic T allows the caller to match the HTLC output index with auxiliary data.
1384 /// This auxiliary data is not stored in this object.
1386 /// Only include HTLCs that are above the dust limit for the channel.
1388 /// This is not exported to bindings users due to the generic though we likely should expose a version without
1389 pub fn new_with_auxiliary_htlc_data<T>(commitment_number: u64, to_broadcaster_value_sat: u64, to_countersignatory_value_sat: u64, broadcaster_funding_key: PublicKey, countersignatory_funding_key: PublicKey, keys: TxCreationKeys, feerate_per_kw: u32, htlcs_with_aux: &mut Vec<(HTLCOutputInCommitment, T)>, channel_parameters: &DirectedChannelTransactionParameters) -> CommitmentTransaction {
1390 let to_broadcaster_value_sat = Amount::from_sat(to_broadcaster_value_sat);
1391 let to_countersignatory_value_sat = Amount::from_sat(to_countersignatory_value_sat);
1393 // Sort outputs and populate output indices while keeping track of the auxiliary data
1394 let (outputs, htlcs) = Self::internal_build_outputs(&keys, to_broadcaster_value_sat, to_countersignatory_value_sat, htlcs_with_aux, channel_parameters, &broadcaster_funding_key, &countersignatory_funding_key).unwrap();
1396 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
1397 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1398 let txid = transaction.txid();
1399 CommitmentTransaction {
1401 to_broadcaster_value_sat,
1402 to_countersignatory_value_sat,
1403 to_broadcaster_delay: Some(channel_parameters.contest_delay()),
1406 channel_type_features: channel_parameters.channel_type_features().clone(),
1408 built: BuiltCommitmentTransaction {
1415 /// Use non-zero fee anchors
1417 /// This is not exported to bindings users due to move, and also not likely to be useful for binding users
1418 pub fn with_non_zero_fee_anchors(mut self) -> Self {
1419 self.channel_type_features.set_anchors_nonzero_fee_htlc_tx_required();
1423 fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<BuiltCommitmentTransaction, ()> {
1424 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
1426 let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
1427 let (outputs, _) = Self::internal_build_outputs(keys, self.to_broadcaster_value_sat, self.to_countersignatory_value_sat, &mut htlcs_with_aux, channel_parameters, broadcaster_funding_key, countersignatory_funding_key)?;
1429 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1430 let txid = transaction.txid();
1431 let built_transaction = BuiltCommitmentTransaction {
1435 Ok(built_transaction)
1438 fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
1440 version: Version::TWO,
1441 lock_time: LockTime::from_consensus(((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32)),
1447 // This is used in two cases:
1448 // - initial sorting of outputs / HTLCs in the constructor, in which case T is auxiliary data the
1449 // caller needs to have sorted together with the HTLCs so it can keep track of the output index
1450 // - building of a bitcoin transaction during a verify() call, in which case T is just ()
1451 fn internal_build_outputs<T>(keys: &TxCreationKeys, to_broadcaster_value_sat: Amount, to_countersignatory_value_sat: Amount, htlcs_with_aux: &mut Vec<(HTLCOutputInCommitment, T)>, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<(Vec<TxOut>, Vec<HTLCOutputInCommitment>), ()> {
1452 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1453 let contest_delay = channel_parameters.contest_delay();
1455 let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
1457 if to_countersignatory_value_sat > Amount::ZERO {
1458 let script = if channel_parameters.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
1459 get_to_countersignatory_with_anchors_redeemscript(&countersignatory_pubkeys.payment_point).to_p2wsh()
1461 ScriptBuf::new_p2wpkh(&Hash160::hash(&countersignatory_pubkeys.payment_point.serialize()).into())
1465 script_pubkey: script.clone(),
1466 value: to_countersignatory_value_sat,
1472 if to_broadcaster_value_sat > Amount::ZERO {
1473 let redeem_script = get_revokeable_redeemscript(
1474 &keys.revocation_key,
1476 &keys.broadcaster_delayed_payment_key,
1480 script_pubkey: redeem_script.to_p2wsh(),
1481 value: to_broadcaster_value_sat,
1487 if channel_parameters.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
1488 if to_broadcaster_value_sat > Amount::ZERO || !htlcs_with_aux.is_empty() {
1489 let anchor_script = get_anchor_redeemscript(broadcaster_funding_key);
1492 script_pubkey: anchor_script.to_p2wsh(),
1493 value: Amount::from_sat(ANCHOR_OUTPUT_VALUE_SATOSHI),
1499 if to_countersignatory_value_sat > Amount::ZERO || !htlcs_with_aux.is_empty() {
1500 let anchor_script = get_anchor_redeemscript(countersignatory_funding_key);
1503 script_pubkey: anchor_script.to_p2wsh(),
1504 value: Amount::from_sat(ANCHOR_OUTPUT_VALUE_SATOSHI),
1511 let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
1512 for (htlc, _) in htlcs_with_aux {
1513 let script = chan_utils::get_htlc_redeemscript(&htlc, &channel_parameters.channel_type_features(), &keys);
1515 script_pubkey: script.to_p2wsh(),
1516 value: htlc.to_bitcoin_amount(),
1518 txouts.push((txout, Some(htlc)));
1521 // Sort output in BIP-69 order (amount, scriptPubkey). Tie-breaks based on HTLC
1522 // CLTV expiration height.
1523 sort_outputs(&mut txouts, |a, b| {
1524 if let &Some(ref a_htlcout) = a {
1525 if let &Some(ref b_htlcout) = b {
1526 a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
1527 // Note that due to hash collisions, we have to have a fallback comparison
1528 // here for fuzzing mode (otherwise at least chanmon_fail_consistency
1530 .then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
1531 // For non-HTLC outputs, if they're copying our SPK we don't really care if we
1532 // close the channel due to mismatches - they're doing something dumb:
1533 } else { cmp::Ordering::Equal }
1534 } else { cmp::Ordering::Equal }
1537 let mut outputs = Vec::with_capacity(txouts.len());
1538 for (idx, out) in txouts.drain(..).enumerate() {
1539 if let Some(htlc) = out.1 {
1540 htlc.transaction_output_index = Some(idx as u32);
1541 htlcs.push(htlc.clone());
1543 outputs.push(out.0);
1545 Ok((outputs, htlcs))
1548 fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
1549 let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
1550 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1551 let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
1552 &broadcaster_pubkeys.payment_point,
1553 &countersignatory_pubkeys.payment_point,
1554 channel_parameters.is_outbound(),
1557 let obscured_commitment_transaction_number =
1558 commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
1561 let mut ins: Vec<TxIn> = Vec::new();
1563 previous_output: channel_parameters.funding_outpoint(),
1564 script_sig: ScriptBuf::new(),
1565 sequence: Sequence(((0x80 as u32) << 8 * 3)
1566 | ((obscured_commitment_transaction_number >> 3 * 8) as u32)),
1567 witness: Witness::new(),
1571 (obscured_commitment_transaction_number, txins)
1574 /// The backwards-counting commitment number
1575 pub fn commitment_number(&self) -> u64 {
1576 self.commitment_number
1579 /// The per commitment point used by the broadcaster.
1580 pub fn per_commitment_point(&self) -> PublicKey {
1581 self.keys.per_commitment_point
1584 /// The value to be sent to the broadcaster
1585 pub fn to_broadcaster_value_sat(&self) -> u64 {
1586 self.to_broadcaster_value_sat.to_sat()
1589 /// The value to be sent to the counterparty
1590 pub fn to_countersignatory_value_sat(&self) -> u64 {
1591 self.to_countersignatory_value_sat.to_sat()
1594 /// The feerate paid per 1000-weight-unit in this commitment transaction.
1595 pub fn feerate_per_kw(&self) -> u32 {
1599 /// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
1600 /// which were included in this commitment transaction in output order.
1601 /// The transaction index is always populated.
1603 /// This is not exported to bindings users as we cannot currently convert Vec references to/from C, though we should
1604 /// expose a less effecient version which creates a Vec of references in the future.
1605 pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
1609 /// Trust our pre-built transaction and derived transaction creation public keys.
1611 /// Applies a wrapper which allows access to these fields.
1613 /// This should only be used if you fully trust the builder of this object. It should not
1614 /// be used by an external signer - instead use the verify function.
1615 pub fn trust(&self) -> TrustedCommitmentTransaction {
1616 TrustedCommitmentTransaction { inner: self }
1619 /// Verify our pre-built transaction and derived transaction creation public keys.
1621 /// Applies a wrapper which allows access to these fields.
1623 /// An external validating signer must call this method before signing
1624 /// or using the built transaction.
1625 pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
1626 // This is the only field of the key cache that we trust
1627 let per_commitment_point = self.keys.per_commitment_point;
1628 let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx);
1629 if keys != self.keys {
1632 let tx = self.internal_rebuild_transaction(&keys, channel_parameters, &broadcaster_keys.funding_pubkey, &countersignatory_keys.funding_pubkey)?;
1633 if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
1636 Ok(TrustedCommitmentTransaction { inner: self })
1640 /// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
1641 /// transaction and the transaction creation keys) are trusted.
1643 /// See trust() and verify() functions on CommitmentTransaction.
1645 /// This structure implements Deref.
1646 pub struct TrustedCommitmentTransaction<'a> {
1647 inner: &'a CommitmentTransaction,
1650 impl<'a> Deref for TrustedCommitmentTransaction<'a> {
1651 type Target = CommitmentTransaction;
1653 fn deref(&self) -> &Self::Target { self.inner }
1656 impl<'a> TrustedCommitmentTransaction<'a> {
1657 /// The transaction ID of the built Bitcoin transaction
1658 pub fn txid(&self) -> Txid {
1659 self.inner.built.txid
1662 /// The pre-built Bitcoin commitment transaction
1663 pub fn built_transaction(&self) -> &'a BuiltCommitmentTransaction {
1667 /// The pre-calculated transaction creation public keys.
1668 pub fn keys(&self) -> &'a TxCreationKeys {
1672 /// Should anchors be used.
1673 pub fn channel_type_features(&self) -> &'a ChannelTypeFeatures {
1674 &self.inner.channel_type_features
1677 /// Get a signature for each HTLC which was included in the commitment transaction (ie for
1678 /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
1680 /// The returned Vec has one entry for each HTLC, and in the same order.
1682 /// This function is only valid in the holder commitment context, it always uses EcdsaSighashType::All.
1683 pub fn get_htlc_sigs<T: secp256k1::Signing, ES: Deref>(
1684 &self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters,
1685 entropy_source: &ES, secp_ctx: &Secp256k1<T>,
1686 ) -> Result<Vec<Signature>, ()> where ES::Target: EntropySource {
1687 let inner = self.inner;
1688 let keys = &inner.keys;
1689 let txid = inner.built.txid;
1690 let mut ret = Vec::with_capacity(inner.htlcs.len());
1691 let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key);
1693 for this_htlc in inner.htlcs.iter() {
1694 assert!(this_htlc.transaction_output_index.is_some());
1695 let htlc_tx = build_htlc_transaction(&txid, inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc, &self.channel_type_features, &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
1697 let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&this_htlc, &self.channel_type_features, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key);
1699 let sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).p2wsh_signature_hash(0, &htlc_redeemscript, this_htlc.to_bitcoin_amount(), EcdsaSighashType::All).unwrap()[..]);
1700 ret.push(sign_with_aux_rand(secp_ctx, &sighash, &holder_htlc_key, entropy_source));
1705 /// Builds the second-level holder HTLC transaction for the HTLC with index `htlc_index`.
1706 pub(crate) fn build_unsigned_htlc_tx(
1707 &self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize,
1708 preimage: &Option<PaymentPreimage>,
1710 let keys = &self.inner.keys;
1711 let this_htlc = &self.inner.htlcs[htlc_index];
1712 assert!(this_htlc.transaction_output_index.is_some());
1713 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
1714 if !this_htlc.offered && preimage.is_none() { unreachable!(); }
1715 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
1716 if this_htlc.offered && preimage.is_some() { unreachable!(); }
1718 build_htlc_transaction(
1719 &self.inner.built.txid, self.inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc,
1720 &self.channel_type_features, &keys.broadcaster_delayed_payment_key, &keys.revocation_key
1725 /// Builds the witness required to spend the input for the HTLC with index `htlc_index` in a
1726 /// second-level holder HTLC transaction.
1727 pub(crate) fn build_htlc_input_witness(
1728 &self, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature,
1729 preimage: &Option<PaymentPreimage>
1731 let keys = &self.inner.keys;
1732 let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(
1733 &self.inner.htlcs[htlc_index], &self.channel_type_features, &keys.broadcaster_htlc_key,
1734 &keys.countersignatory_htlc_key, &keys.revocation_key
1736 chan_utils::build_htlc_input_witness(
1737 signature, counterparty_signature, preimage, &htlc_redeemscript, &self.channel_type_features,
1741 /// Returns the index of the revokeable output, i.e. the `to_local` output sending funds to
1742 /// the broadcaster, in the built transaction, if any exists.
1744 /// There are two cases where this may return `None`:
1745 /// - The balance of the revokeable output is below the dust limit (only found on commitments
1746 /// early in the channel's lifetime, i.e. before the channel reserve is met).
1747 /// - This commitment was created before LDK 0.0.117. In this case, the
1748 /// commitment transaction previously didn't contain enough information to locate the
1749 /// revokeable output.
1750 pub fn revokeable_output_index(&self) -> Option<usize> {
1751 let revokeable_redeemscript = get_revokeable_redeemscript(
1752 &self.keys.revocation_key,
1753 self.to_broadcaster_delay?,
1754 &self.keys.broadcaster_delayed_payment_key,
1756 let revokeable_p2wsh = revokeable_redeemscript.to_p2wsh();
1757 let outputs = &self.inner.built.transaction.output;
1758 outputs.iter().enumerate()
1759 .find(|(_, out)| out.script_pubkey == revokeable_p2wsh)
1760 .map(|(idx, _)| idx)
1763 /// Helper method to build an unsigned justice transaction spending the revokeable
1764 /// `to_local` output to a destination script. Fee estimation accounts for the expected
1765 /// revocation witness data that will be added when signed.
1767 /// This method will error if the given fee rate results in a fee greater than the value
1768 /// of the output being spent, or if there exists no revokeable `to_local` output on this
1769 /// commitment transaction. See [`Self::revokeable_output_index`] for more details.
1771 /// The built transaction will allow fee bumping with RBF, and this method takes
1772 /// `feerate_per_kw` as an input such that multiple copies of a justice transaction at different
1773 /// fee rates may be built.
1774 pub fn build_to_local_justice_tx(&self, feerate_per_kw: u64, destination_script: ScriptBuf)
1775 -> Result<Transaction, ()> {
1776 let output_idx = self.revokeable_output_index().ok_or(())?;
1777 let input = vec![TxIn {
1778 previous_output: OutPoint {
1779 txid: self.trust().txid(),
1780 vout: output_idx as u32,
1782 script_sig: ScriptBuf::new(),
1783 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
1784 witness: Witness::new(),
1786 let value = self.inner.built.transaction.output[output_idx].value;
1787 let output = vec![TxOut {
1788 script_pubkey: destination_script,
1791 let mut justice_tx = Transaction {
1792 version: Version::TWO,
1793 lock_time: LockTime::ZERO,
1797 let weight = justice_tx.weight().to_wu() + WEIGHT_REVOKED_OUTPUT;
1798 let fee = Amount::from_sat(fee_for_weight(feerate_per_kw as u32, weight));
1799 justice_tx.output[0].value = value.checked_sub(fee).ok_or(())?;
1805 /// Commitment transaction numbers which appear in the transactions themselves are XOR'd with a
1806 /// shared secret first. This prevents on-chain observers from discovering how many commitment
1807 /// transactions occurred in a channel before it was closed.
1809 /// This function gets the shared secret from relevant channel public keys and can be used to
1810 /// "decrypt" the commitment transaction number given a commitment transaction on-chain.
1811 pub fn get_commitment_transaction_number_obscure_factor(
1812 broadcaster_payment_basepoint: &PublicKey,
1813 countersignatory_payment_basepoint: &PublicKey,
1814 outbound_from_broadcaster: bool,
1816 let mut sha = Sha256::engine();
1818 if outbound_from_broadcaster {
1819 sha.input(&broadcaster_payment_basepoint.serialize());
1820 sha.input(&countersignatory_payment_basepoint.serialize());
1822 sha.input(&countersignatory_payment_basepoint.serialize());
1823 sha.input(&broadcaster_payment_basepoint.serialize());
1825 let res = Sha256::from_engine(sha).to_byte_array();
1827 ((res[26] as u64) << 5 * 8)
1828 | ((res[27] as u64) << 4 * 8)
1829 | ((res[28] as u64) << 3 * 8)
1830 | ((res[29] as u64) << 2 * 8)
1831 | ((res[30] as u64) << 1 * 8)
1832 | ((res[31] as u64) << 0 * 8)
1837 use super::{CounterpartyCommitmentSecrets, ChannelPublicKeys};
1839 use crate::ln::chan_utils::{get_htlc_redeemscript, get_to_countersignatory_with_anchors_redeemscript, CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
1840 use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
1841 use crate::util::test_utils;
1842 use crate::sign::{ChannelSigner, SignerProvider};
1843 use bitcoin::{Network, Txid, ScriptBuf};
1844 use bitcoin::hashes::Hash;
1845 use bitcoin::hashes::hex::FromHex;
1846 use crate::ln::types::PaymentHash;
1847 use bitcoin::address::Payload;
1848 use bitcoin::PublicKey as BitcoinPublicKey;
1849 use crate::ln::features::ChannelTypeFeatures;
1851 #[allow(unused_imports)]
1852 use crate::prelude::*;
1854 struct TestCommitmentTxBuilder {
1855 commitment_number: u64,
1856 holder_funding_pubkey: PublicKey,
1857 counterparty_funding_pubkey: PublicKey,
1858 keys: TxCreationKeys,
1859 feerate_per_kw: u32,
1860 htlcs_with_aux: Vec<(HTLCOutputInCommitment, ())>,
1861 channel_parameters: ChannelTransactionParameters,
1862 counterparty_pubkeys: ChannelPublicKeys,
1865 impl TestCommitmentTxBuilder {
1867 let secp_ctx = Secp256k1::new();
1868 let seed = [42; 32];
1869 let network = Network::Testnet;
1870 let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
1871 let signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(false, 1_000_000, 0));
1872 let counterparty_signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(true, 1_000_000, 1));
1873 let delayed_payment_base = &signer.pubkeys().delayed_payment_basepoint;
1874 let per_commitment_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
1875 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
1876 let htlc_basepoint = &signer.pubkeys().htlc_basepoint;
1877 let holder_pubkeys = signer.pubkeys();
1878 let counterparty_pubkeys = counterparty_signer.pubkeys().clone();
1879 let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint);
1880 let channel_parameters = ChannelTransactionParameters {
1881 holder_pubkeys: holder_pubkeys.clone(),
1882 holder_selected_contest_delay: 0,
1883 is_outbound_from_holder: false,
1884 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: counterparty_pubkeys.clone(), selected_contest_delay: 0 }),
1885 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1886 channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
1888 let htlcs_with_aux = Vec::new();
1891 commitment_number: 0,
1892 holder_funding_pubkey: holder_pubkeys.funding_pubkey,
1893 counterparty_funding_pubkey: counterparty_pubkeys.funding_pubkey,
1898 counterparty_pubkeys,
1902 fn build(&mut self, to_broadcaster_sats: u64, to_countersignatory_sats: u64) -> CommitmentTransaction {
1903 CommitmentTransaction::new_with_auxiliary_htlc_data(
1904 self.commitment_number, to_broadcaster_sats, to_countersignatory_sats,
1905 self.holder_funding_pubkey.clone(),
1906 self.counterparty_funding_pubkey.clone(),
1907 self.keys.clone(), self.feerate_per_kw,
1908 &mut self.htlcs_with_aux, &self.channel_parameters.as_holder_broadcastable()
1915 let mut builder = TestCommitmentTxBuilder::new();
1917 // Generate broadcaster and counterparty outputs
1918 let tx = builder.build(1000, 2000);
1919 assert_eq!(tx.built.transaction.output.len(), 2);
1920 assert_eq!(tx.built.transaction.output[1].script_pubkey, Payload::p2wpkh(&BitcoinPublicKey::new(builder.counterparty_pubkeys.payment_point)).unwrap().script_pubkey());
1922 // Generate broadcaster and counterparty outputs as well as two anchors
1923 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
1924 let tx = builder.build(1000, 2000);
1925 assert_eq!(tx.built.transaction.output.len(), 4);
1926 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_to_countersignatory_with_anchors_redeemscript(&builder.counterparty_pubkeys.payment_point).to_p2wsh());
1928 // Generate broadcaster output and anchor
1929 let tx = builder.build(3000, 0);
1930 assert_eq!(tx.built.transaction.output.len(), 2);
1932 // Generate counterparty output and anchor
1933 let tx = builder.build(0, 3000);
1934 assert_eq!(tx.built.transaction.output.len(), 2);
1936 let received_htlc = HTLCOutputInCommitment {
1938 amount_msat: 400000,
1940 payment_hash: PaymentHash([42; 32]),
1941 transaction_output_index: None,
1944 let offered_htlc = HTLCOutputInCommitment {
1946 amount_msat: 600000,
1948 payment_hash: PaymentHash([43; 32]),
1949 transaction_output_index: None,
1952 // Generate broadcaster output and received and offered HTLC outputs, w/o anchors
1953 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1954 builder.htlcs_with_aux = vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())];
1955 let tx = builder.build(3000, 0);
1956 let keys = &builder.keys.clone();
1957 assert_eq!(tx.built.transaction.output.len(), 3);
1958 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_p2wsh());
1959 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_p2wsh());
1960 assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_p2wsh().to_hex_string(),
1961 "0020e43a7c068553003fe68fcae424fb7b28ec5ce48cd8b6744b3945631389bad2fb");
1962 assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_p2wsh().to_hex_string(),
1963 "0020215d61bba56b19e9eadb6107f5a85d7f99c40f65992443f69229c290165bc00d");
1965 // Generate broadcaster output and received and offered HTLC outputs, with anchors
1966 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
1967 builder.htlcs_with_aux = vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())];
1968 let tx = builder.build(3000, 0);
1969 assert_eq!(tx.built.transaction.output.len(), 5);
1970 assert_eq!(tx.built.transaction.output[2].script_pubkey, get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_p2wsh());
1971 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_p2wsh());
1972 assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_p2wsh().to_hex_string(),
1973 "0020b70d0649c72b38756885c7a30908d912a7898dd5d79457a7280b8e9a20f3f2bc");
1974 assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_p2wsh().to_hex_string(),
1975 "002087a3faeb1950a469c0e2db4a79b093a41b9526e5a6fc6ef5cb949bde3be379c7");
1979 fn test_finding_revokeable_output_index() {
1980 let mut builder = TestCommitmentTxBuilder::new();
1982 // Revokeable output present
1983 let tx = builder.build(1000, 2000);
1984 assert_eq!(tx.built.transaction.output.len(), 2);
1985 assert_eq!(tx.trust().revokeable_output_index(), Some(0));
1987 // Revokeable output present (but to_broadcaster_delay missing)
1988 let tx = CommitmentTransaction { to_broadcaster_delay: None, ..tx };
1989 assert_eq!(tx.built.transaction.output.len(), 2);
1990 assert_eq!(tx.trust().revokeable_output_index(), None);
1992 // Revokeable output not present (our balance is dust)
1993 let tx = builder.build(0, 2000);
1994 assert_eq!(tx.built.transaction.output.len(), 1);
1995 assert_eq!(tx.trust().revokeable_output_index(), None);
1999 fn test_building_to_local_justice_tx() {
2000 let mut builder = TestCommitmentTxBuilder::new();
2002 // Revokeable output not present (our balance is dust)
2003 let tx = builder.build(0, 2000);
2004 assert_eq!(tx.built.transaction.output.len(), 1);
2005 assert!(tx.trust().build_to_local_justice_tx(253, ScriptBuf::new()).is_err());
2007 // Revokeable output present
2008 let tx = builder.build(1000, 2000);
2009 assert_eq!(tx.built.transaction.output.len(), 2);
2012 assert!(tx.trust().build_to_local_justice_tx(100_000, ScriptBuf::new()).is_err());
2014 // Generate a random public key for destination script
2015 let secret_key = SecretKey::from_slice(
2016 &<Vec<u8>>::from_hex("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100")
2017 .unwrap()[..]).unwrap();
2018 let pubkey_hash = BitcoinPublicKey::new(
2019 PublicKey::from_secret_key(&Secp256k1::new(), &secret_key)).wpubkey_hash().unwrap();
2020 let destination_script = ScriptBuf::new_p2wpkh(&pubkey_hash);
2022 let justice_tx = tx.trust().build_to_local_justice_tx(253, destination_script.clone()).unwrap();
2023 assert_eq!(justice_tx.input.len(), 1);
2024 assert_eq!(justice_tx.input[0].previous_output.txid, tx.built.transaction.txid());
2025 assert_eq!(justice_tx.input[0].previous_output.vout, tx.trust().revokeable_output_index().unwrap() as u32);
2026 assert!(justice_tx.input[0].sequence.is_rbf());
2028 assert_eq!(justice_tx.output.len(), 1);
2029 assert!(justice_tx.output[0].value.to_sat() < 1000);
2030 assert_eq!(justice_tx.output[0].script_pubkey, destination_script);
2034 fn test_per_commitment_storage() {
2035 // Test vectors from BOLT 3:
2036 let mut secrets: Vec<[u8; 32]> = Vec::new();
2039 macro_rules! test_secrets {
2041 let mut idx = 281474976710655;
2042 for secret in secrets.iter() {
2043 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
2046 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
2047 assert!(monitor.get_secret(idx).is_none());
2052 // insert_secret correct sequence
2053 monitor = CounterpartyCommitmentSecrets::new();
2056 secrets.push([0; 32]);
2057 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2058 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2061 secrets.push([0; 32]);
2062 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2063 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2066 secrets.push([0; 32]);
2067 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2068 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2071 secrets.push([0; 32]);
2072 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2073 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2076 secrets.push([0; 32]);
2077 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2078 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2081 secrets.push([0; 32]);
2082 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2083 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2086 secrets.push([0; 32]);
2087 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2088 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2091 secrets.push([0; 32]);
2092 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2093 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
2098 // insert_secret #1 incorrect
2099 monitor = CounterpartyCommitmentSecrets::new();
2102 secrets.push([0; 32]);
2103 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2104 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2107 secrets.push([0; 32]);
2108 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2109 assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
2113 // insert_secret #2 incorrect (#1 derived from incorrect)
2114 monitor = CounterpartyCommitmentSecrets::new();
2117 secrets.push([0; 32]);
2118 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2119 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2122 secrets.push([0; 32]);
2123 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2124 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2127 secrets.push([0; 32]);
2128 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2129 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2132 secrets.push([0; 32]);
2133 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2134 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
2138 // insert_secret #3 incorrect
2139 monitor = CounterpartyCommitmentSecrets::new();
2142 secrets.push([0; 32]);
2143 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2144 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2147 secrets.push([0; 32]);
2148 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2149 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2152 secrets.push([0; 32]);
2153 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2154 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2157 secrets.push([0; 32]);
2158 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2159 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
2163 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
2164 monitor = CounterpartyCommitmentSecrets::new();
2167 secrets.push([0; 32]);
2168 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2169 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2172 secrets.push([0; 32]);
2173 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2174 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2177 secrets.push([0; 32]);
2178 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2179 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2182 secrets.push([0; 32]);
2183 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
2184 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2187 secrets.push([0; 32]);
2188 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2189 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2192 secrets.push([0; 32]);
2193 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2194 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2197 secrets.push([0; 32]);
2198 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2199 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2202 secrets.push([0; 32]);
2203 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2204 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2208 // insert_secret #5 incorrect
2209 monitor = CounterpartyCommitmentSecrets::new();
2212 secrets.push([0; 32]);
2213 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2214 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2217 secrets.push([0; 32]);
2218 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2219 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2222 secrets.push([0; 32]);
2223 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2224 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2227 secrets.push([0; 32]);
2228 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2229 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2232 secrets.push([0; 32]);
2233 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2234 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2237 secrets.push([0; 32]);
2238 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2239 assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
2243 // insert_secret #6 incorrect (5 derived from incorrect)
2244 monitor = CounterpartyCommitmentSecrets::new();
2247 secrets.push([0; 32]);
2248 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2249 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2252 secrets.push([0; 32]);
2253 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2254 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2257 secrets.push([0; 32]);
2258 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2259 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2262 secrets.push([0; 32]);
2263 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2264 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2267 secrets.push([0; 32]);
2268 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2269 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2272 secrets.push([0; 32]);
2273 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
2274 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2277 secrets.push([0; 32]);
2278 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2279 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2282 secrets.push([0; 32]);
2283 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2284 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2288 // insert_secret #7 incorrect
2289 monitor = CounterpartyCommitmentSecrets::new();
2292 secrets.push([0; 32]);
2293 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2294 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2297 secrets.push([0; 32]);
2298 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2299 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2302 secrets.push([0; 32]);
2303 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2304 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2307 secrets.push([0; 32]);
2308 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2309 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2312 secrets.push([0; 32]);
2313 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2314 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2317 secrets.push([0; 32]);
2318 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2319 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2322 secrets.push([0; 32]);
2323 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2324 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2327 secrets.push([0; 32]);
2328 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2329 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2333 // insert_secret #8 incorrect
2334 monitor = CounterpartyCommitmentSecrets::new();
2337 secrets.push([0; 32]);
2338 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2339 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2342 secrets.push([0; 32]);
2343 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2344 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2347 secrets.push([0; 32]);
2348 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2349 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2352 secrets.push([0; 32]);
2353 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2354 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2357 secrets.push([0; 32]);
2358 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2359 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2362 secrets.push([0; 32]);
2363 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2364 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2367 secrets.push([0; 32]);
2368 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2369 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2372 secrets.push([0; 32]);
2373 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2374 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());