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::blockdata::script::{Script, ScriptBuf, Builder};
14 use bitcoin::blockdata::opcodes;
15 use bitcoin::blockdata::transaction::{TxIn,TxOut,OutPoint,Transaction};
17 use bitcoin::sighash::EcdsaSighashType;
18 use bitcoin::address::Payload;
20 use bitcoin::hashes::{Hash, HashEngine};
21 use bitcoin::hashes::sha256::Hash as Sha256;
22 use bitcoin::hashes::ripemd160::Hash as Ripemd160;
23 use bitcoin::hash_types::{Txid, PubkeyHash, WPubkeyHash};
25 use crate::chain::chaininterface::fee_for_weight;
26 use crate::chain::package::WEIGHT_REVOKED_OUTPUT;
27 use crate::sign::EntropySource;
28 use crate::ln::{PaymentHash, PaymentPreimage};
29 use crate::ln::msgs::DecodeError;
30 use crate::util::ser::{Readable, RequiredWrapper, Writeable, Writer};
31 use crate::util::transaction_utils;
33 use bitcoin::blockdata::locktime::absolute::LockTime;
34 use bitcoin::secp256k1::{SecretKey, PublicKey, Scalar};
35 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature, Message};
36 use bitcoin::{secp256k1, Sequence, Witness};
37 use bitcoin::PublicKey as BitcoinPublicKey;
40 use crate::prelude::*;
42 use crate::ln::chan_utils;
43 use crate::util::transaction_utils::sort_outputs;
44 use crate::ln::channel::{INITIAL_COMMITMENT_NUMBER, ANCHOR_OUTPUT_VALUE_SATOSHI};
47 use crate::ln::features::ChannelTypeFeatures;
48 use crate::util::crypto::{sign, sign_with_aux_rand};
49 use super::channel_keys::{DelayedPaymentBasepoint, DelayedPaymentKey, HtlcKey, HtlcBasepoint, RevocationKey, RevocationBasepoint};
51 /// Maximum number of one-way in-flight HTLC (protocol-level value).
52 pub const MAX_HTLCS: u16 = 483;
53 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, non-anchor variant.
54 pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
55 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, anchor variant.
56 pub const OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS: usize = 136;
58 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
59 /// We define a range that encompasses both its non-anchors and anchors variants.
60 pub(crate) const MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 136;
61 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
62 /// We define a range that encompasses both its non-anchors and anchors variants.
63 /// This is the maximum post-anchor value.
64 pub const MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 143;
66 /// The upper bound weight of an anchor input.
67 pub const ANCHOR_INPUT_WITNESS_WEIGHT: u64 = 116;
68 /// The upper bound weight of an HTLC timeout input from a commitment transaction with anchor
70 pub const HTLC_TIMEOUT_INPUT_ANCHOR_WITNESS_WEIGHT: u64 = 288;
71 /// The upper bound weight of an HTLC success input from a commitment transaction with anchor
73 pub const HTLC_SUCCESS_INPUT_ANCHOR_WITNESS_WEIGHT: u64 = 327;
75 /// Gets the weight for an HTLC-Success transaction.
77 pub fn htlc_success_tx_weight(channel_type_features: &ChannelTypeFeatures) -> u64 {
78 const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
79 const HTLC_SUCCESS_ANCHOR_TX_WEIGHT: u64 = 706;
80 if channel_type_features.supports_anchors_zero_fee_htlc_tx() { HTLC_SUCCESS_ANCHOR_TX_WEIGHT } else { HTLC_SUCCESS_TX_WEIGHT }
83 /// Gets the weight for an HTLC-Timeout transaction.
85 pub fn htlc_timeout_tx_weight(channel_type_features: &ChannelTypeFeatures) -> u64 {
86 const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
87 const HTLC_TIMEOUT_ANCHOR_TX_WEIGHT: u64 = 666;
88 if channel_type_features.supports_anchors_zero_fee_htlc_tx() { HTLC_TIMEOUT_ANCHOR_TX_WEIGHT } else { HTLC_TIMEOUT_TX_WEIGHT }
91 /// Describes the type of HTLC claim as determined by analyzing the witness.
92 #[derive(PartialEq, Eq)]
94 /// Claims an offered output on a commitment transaction through the timeout path.
96 /// Claims an offered output on a commitment transaction through the success path.
98 /// Claims an accepted output on a commitment transaction through the timeout path.
100 /// Claims an accepted output on a commitment transaction through the success path.
102 /// Claims an offered/accepted output on a commitment transaction through the revocation path.
107 /// Check if a given input witness attempts to claim a HTLC.
108 pub fn from_witness(witness: &Witness) -> Option<Self> {
109 debug_assert_eq!(OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS, MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT);
110 if witness.len() < 2 {
113 let witness_script = witness.last().unwrap();
114 let second_to_last = witness.second_to_last().unwrap();
115 if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT {
116 if witness.len() == 3 && second_to_last.len() == 33 {
117 // <revocation sig> <revocationpubkey> <witness_script>
118 Some(Self::Revocation)
119 } else if witness.len() == 3 && second_to_last.len() == 32 {
120 // <remotehtlcsig> <payment_preimage> <witness_script>
121 Some(Self::OfferedPreimage)
122 } else if witness.len() == 5 && second_to_last.len() == 0 {
123 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
124 Some(Self::OfferedTimeout)
128 } else if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS {
129 // It's possible for the weight of `offered_htlc_script` and `accepted_htlc_script` to
130 // match so we check for both here.
131 if witness.len() == 3 && second_to_last.len() == 33 {
132 // <revocation sig> <revocationpubkey> <witness_script>
133 Some(Self::Revocation)
134 } else if witness.len() == 3 && second_to_last.len() == 32 {
135 // <remotehtlcsig> <payment_preimage> <witness_script>
136 Some(Self::OfferedPreimage)
137 } else if witness.len() == 5 && second_to_last.len() == 0 {
138 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
139 Some(Self::OfferedTimeout)
140 } else if witness.len() == 3 && second_to_last.len() == 0 {
141 // <remotehtlcsig> <> <witness_script>
142 Some(Self::AcceptedTimeout)
143 } else if witness.len() == 5 && second_to_last.len() == 32 {
144 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
145 Some(Self::AcceptedPreimage)
149 } else if witness_script.len() > MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT &&
150 witness_script.len() <= MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT {
151 // Handle remaining range of ACCEPTED_HTLC_SCRIPT_WEIGHT.
152 if witness.len() == 3 && second_to_last.len() == 33 {
153 // <revocation sig> <revocationpubkey> <witness_script>
154 Some(Self::Revocation)
155 } else if witness.len() == 3 && second_to_last.len() == 0 {
156 // <remotehtlcsig> <> <witness_script>
157 Some(Self::AcceptedTimeout)
158 } else if witness.len() == 5 && second_to_last.len() == 32 {
159 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
160 Some(Self::AcceptedPreimage)
170 // Various functions for key derivation and transaction creation for use within channels. Primarily
171 // used in Channel and ChannelMonitor.
173 /// Build the commitment secret from the seed and the commitment number
174 pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
175 let mut res: [u8; 32] = commitment_seed.clone();
178 if idx & (1 << bitpos) == (1 << bitpos) {
179 res[bitpos / 8] ^= 1 << (bitpos & 7);
180 res = Sha256::hash(&res).to_byte_array();
186 /// Build a closing transaction
187 pub fn build_closing_transaction(to_holder_value_sat: u64, to_counterparty_value_sat: u64, to_holder_script: ScriptBuf, to_counterparty_script: ScriptBuf, funding_outpoint: OutPoint) -> Transaction {
189 let mut ins: Vec<TxIn> = Vec::new();
191 previous_output: funding_outpoint,
192 script_sig: ScriptBuf::new(),
193 sequence: Sequence::MAX,
194 witness: Witness::new(),
199 let mut txouts: Vec<(TxOut, ())> = Vec::new();
201 if to_counterparty_value_sat > 0 {
203 script_pubkey: to_counterparty_script,
204 value: to_counterparty_value_sat
208 if to_holder_value_sat > 0 {
210 script_pubkey: to_holder_script,
211 value: to_holder_value_sat
215 transaction_utils::sort_outputs(&mut txouts, |_, _| { cmp::Ordering::Equal }); // Ordering doesnt matter if they used our pubkey...
217 let mut outputs: Vec<TxOut> = Vec::new();
218 for out in txouts.drain(..) {
224 lock_time: LockTime::ZERO,
230 /// Implements the per-commitment secret storage scheme from
231 /// [BOLT 3](https://github.com/lightning/bolts/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
233 /// Allows us to keep track of all of the revocation secrets of our counterparty in just 50*32 bytes
236 pub struct CounterpartyCommitmentSecrets {
237 old_secrets: [([u8; 32], u64); 49],
240 impl Eq for CounterpartyCommitmentSecrets {}
241 impl PartialEq for CounterpartyCommitmentSecrets {
242 fn eq(&self, other: &Self) -> bool {
243 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
244 if secret != o_secret || idx != o_idx {
252 impl CounterpartyCommitmentSecrets {
253 /// Creates a new empty `CounterpartyCommitmentSecrets` structure.
254 pub fn new() -> Self {
255 Self { old_secrets: [([0; 32], 1 << 48); 49], }
259 fn place_secret(idx: u64) -> u8 {
261 if idx & (1 << i) == (1 << i) {
268 /// Returns the minimum index of all stored secrets. Note that indexes start
269 /// at 1 << 48 and get decremented by one for each new secret.
270 pub fn get_min_seen_secret(&self) -> u64 {
271 //TODO This can be optimized?
272 let mut min = 1 << 48;
273 for &(_, idx) in self.old_secrets.iter() {
282 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
283 let mut res: [u8; 32] = secret;
285 let bitpos = bits - 1 - i;
286 if idx & (1 << bitpos) == (1 << bitpos) {
287 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
288 res = Sha256::hash(&res).to_byte_array();
294 /// Inserts the `secret` at `idx`. Returns `Ok(())` if the secret
295 /// was generated in accordance with BOLT 3 and is consistent with previous secrets.
296 pub fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
297 let pos = Self::place_secret(idx);
299 let (old_secret, old_idx) = self.old_secrets[i as usize];
300 if Self::derive_secret(secret, pos, old_idx) != old_secret {
304 if self.get_min_seen_secret() <= idx {
307 self.old_secrets[pos as usize] = (secret, idx);
311 /// Returns the secret at `idx`.
312 /// Returns `None` if `idx` is < [`CounterpartyCommitmentSecrets::get_min_seen_secret`].
313 pub fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
314 for i in 0..self.old_secrets.len() {
315 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
316 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
319 assert!(idx < self.get_min_seen_secret());
324 impl Writeable for CounterpartyCommitmentSecrets {
325 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
326 for &(ref secret, ref idx) in self.old_secrets.iter() {
327 writer.write_all(secret)?;
328 writer.write_all(&idx.to_be_bytes())?;
330 write_tlv_fields!(writer, {});
334 impl Readable for CounterpartyCommitmentSecrets {
335 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
336 let mut old_secrets = [([0; 32], 1 << 48); 49];
337 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
338 *secret = Readable::read(reader)?;
339 *idx = Readable::read(reader)?;
341 read_tlv_fields!(reader, {});
342 Ok(Self { old_secrets })
346 /// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
347 /// from the base secret and the per_commitment_point.
348 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> SecretKey {
349 let mut sha = Sha256::engine();
350 sha.input(&per_commitment_point.serialize());
351 sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
352 let res = Sha256::from_engine(sha).to_byte_array();
354 base_secret.clone().add_tweak(&Scalar::from_be_bytes(res).unwrap())
355 .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.")
358 /// Derives a per-commitment-transaction revocation key from its constituent parts.
360 /// Only the cheating participant owns a valid witness to propagate a revoked
361 /// commitment transaction, thus per_commitment_secret always come from cheater
362 /// and revocation_base_secret always come from punisher, which is the broadcaster
363 /// of the transaction spending with this key knowledge.
364 pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>,
365 per_commitment_secret: &SecretKey, countersignatory_revocation_base_secret: &SecretKey)
367 let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
368 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
370 let rev_append_commit_hash_key = {
371 let mut sha = Sha256::engine();
372 sha.input(&countersignatory_revocation_base_point.serialize());
373 sha.input(&per_commitment_point.serialize());
375 Sha256::from_engine(sha).to_byte_array()
377 let commit_append_rev_hash_key = {
378 let mut sha = Sha256::engine();
379 sha.input(&per_commitment_point.serialize());
380 sha.input(&countersignatory_revocation_base_point.serialize());
382 Sha256::from_engine(sha).to_byte_array()
385 let countersignatory_contrib = countersignatory_revocation_base_secret.clone().mul_tweak(&Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
386 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
387 let broadcaster_contrib = per_commitment_secret.clone().mul_tweak(&Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
388 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
389 countersignatory_contrib.add_tweak(&Scalar::from_be_bytes(broadcaster_contrib.secret_bytes()).unwrap())
390 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
393 /// The set of public keys which are used in the creation of one commitment transaction.
394 /// These are derived from the channel base keys and per-commitment data.
396 /// A broadcaster key is provided from potential broadcaster of the computed transaction.
397 /// A countersignatory key is coming from a protocol participant unable to broadcast the
400 /// These keys are assumed to be good, either because the code derived them from
401 /// channel basepoints via the new function, or they were obtained via
402 /// CommitmentTransaction.trust().keys() because we trusted the source of the
403 /// pre-calculated keys.
404 #[derive(PartialEq, Eq, Clone, Debug)]
405 pub struct TxCreationKeys {
406 /// The broadcaster's per-commitment public key which was used to derive the other keys.
407 pub per_commitment_point: PublicKey,
408 /// The revocation key which is used to allow the broadcaster of the commitment
409 /// transaction to provide their counterparty the ability to punish them if they broadcast
411 pub revocation_key: RevocationKey,
412 /// Broadcaster's HTLC Key
413 pub broadcaster_htlc_key: HtlcKey,
414 /// Countersignatory's HTLC Key
415 pub countersignatory_htlc_key: HtlcKey,
416 /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
417 pub broadcaster_delayed_payment_key: DelayedPaymentKey,
420 impl_writeable_tlv_based!(TxCreationKeys, {
421 (0, per_commitment_point, required),
422 (2, revocation_key, required),
423 (4, broadcaster_htlc_key, required),
424 (6, countersignatory_htlc_key, required),
425 (8, broadcaster_delayed_payment_key, required),
428 /// One counterparty's public keys which do not change over the life of a channel.
429 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
430 pub struct ChannelPublicKeys {
431 /// The public key which is used to sign all commitment transactions, as it appears in the
432 /// on-chain channel lock-in 2-of-2 multisig output.
433 pub funding_pubkey: PublicKey,
434 /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
435 /// revocation keys. This is combined with the per-commitment-secret generated by the
436 /// counterparty to create a secret which the counterparty can reveal to revoke previous
438 pub revocation_basepoint: RevocationBasepoint,
439 /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
440 /// spendable primary channel balance on the broadcaster's commitment transaction. This key is
441 /// static across every commitment transaction.
442 pub payment_point: PublicKey,
443 /// The base point which is used (with derive_public_key) to derive a per-commitment payment
444 /// public key which receives non-HTLC-encumbered funds which are only available for spending
445 /// after some delay (or can be claimed via the revocation path).
446 pub delayed_payment_basepoint: DelayedPaymentBasepoint,
447 /// The base point which is used (with derive_public_key) to derive a per-commitment public key
448 /// which is used to encumber HTLC-in-flight outputs.
449 pub htlc_basepoint: HtlcBasepoint,
452 impl_writeable_tlv_based!(ChannelPublicKeys, {
453 (0, funding_pubkey, required),
454 (2, revocation_basepoint, required),
455 (4, payment_point, required),
456 (6, delayed_payment_basepoint, required),
457 (8, htlc_basepoint, required),
460 impl TxCreationKeys {
461 /// Create per-state keys from channel base points and the per-commitment point.
462 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
463 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 {
465 per_commitment_point: per_commitment_point.clone(),
466 revocation_key: RevocationKey::from_basepoint(&secp_ctx, &countersignatory_revocation_base, &per_commitment_point),
467 broadcaster_htlc_key: HtlcKey::from_basepoint(&secp_ctx, &broadcaster_htlc_base, &per_commitment_point),
468 countersignatory_htlc_key: HtlcKey::from_basepoint(&secp_ctx, &countersignatory_htlc_base, &per_commitment_point),
469 broadcaster_delayed_payment_key: DelayedPaymentKey::from_basepoint(&secp_ctx, &broadcaster_delayed_payment_base, &per_commitment_point),
473 /// Generate per-state keys from channel static keys.
474 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
475 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 {
476 TxCreationKeys::derive_new(
478 &per_commitment_point,
479 &broadcaster_keys.delayed_payment_basepoint,
480 &broadcaster_keys.htlc_basepoint,
481 &countersignatory_keys.revocation_basepoint,
482 &countersignatory_keys.htlc_basepoint,
487 /// The maximum length of a script returned by get_revokeable_redeemscript.
488 // Calculated as 6 bytes of opcodes, 1 byte push plus 2 bytes for contest_delay, and two public
489 // keys of 33 bytes (+ 1 push).
490 pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 3 + 34*2;
492 /// A script either spendable by the revocation
493 /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
494 /// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
495 pub fn get_revokeable_redeemscript(revocation_key: &RevocationKey, contest_delay: u16, broadcaster_delayed_payment_key: &DelayedPaymentKey) -> ScriptBuf {
496 let res = Builder::new().push_opcode(opcodes::all::OP_IF)
497 .push_slice(&revocation_key.to_public_key().serialize())
498 .push_opcode(opcodes::all::OP_ELSE)
499 .push_int(contest_delay as i64)
500 .push_opcode(opcodes::all::OP_CSV)
501 .push_opcode(opcodes::all::OP_DROP)
502 .push_slice(&broadcaster_delayed_payment_key.to_public_key().serialize())
503 .push_opcode(opcodes::all::OP_ENDIF)
504 .push_opcode(opcodes::all::OP_CHECKSIG)
506 debug_assert!(res.len() <= REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH);
510 /// Returns the script for the counterparty's output on a holder's commitment transaction based on
511 /// the channel type.
512 pub fn get_counterparty_payment_script(channel_type_features: &ChannelTypeFeatures, payment_key: &PublicKey) -> ScriptBuf {
513 if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
514 get_to_countersignatory_with_anchors_redeemscript(payment_key).to_v0_p2wsh()
516 ScriptBuf::new_v0_p2wpkh(&WPubkeyHash::hash(&payment_key.serialize()))
520 /// Information about an HTLC as it appears in a commitment transaction
521 #[derive(Clone, Debug, PartialEq, Eq)]
522 pub struct HTLCOutputInCommitment {
523 /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
524 /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
525 /// need to compare this value to whether the commitment transaction in question is that of
526 /// the counterparty or our own.
528 /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
529 /// this divided by 1000.
530 pub amount_msat: u64,
531 /// The CLTV lock-time at which this HTLC expires.
532 pub cltv_expiry: u32,
533 /// The hash of the preimage which unlocks this HTLC.
534 pub payment_hash: PaymentHash,
535 /// The position within the commitment transactions' outputs. This may be None if the value is
536 /// below the dust limit (in which case no output appears in the commitment transaction and the
537 /// value is spent to additional transaction fees).
538 pub transaction_output_index: Option<u32>,
541 impl_writeable_tlv_based!(HTLCOutputInCommitment, {
542 (0, offered, required),
543 (2, amount_msat, required),
544 (4, cltv_expiry, required),
545 (6, payment_hash, required),
546 (8, transaction_output_index, option),
550 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 {
551 let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).to_byte_array();
553 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
554 .push_opcode(opcodes::all::OP_HASH160)
555 .push_slice(PubkeyHash::hash(&revocation_key.to_public_key().serialize()))
556 .push_opcode(opcodes::all::OP_EQUAL)
557 .push_opcode(opcodes::all::OP_IF)
558 .push_opcode(opcodes::all::OP_CHECKSIG)
559 .push_opcode(opcodes::all::OP_ELSE)
560 .push_slice(&countersignatory_htlc_key.to_public_key().serialize())
561 .push_opcode(opcodes::all::OP_SWAP)
562 .push_opcode(opcodes::all::OP_SIZE)
564 .push_opcode(opcodes::all::OP_EQUAL)
565 .push_opcode(opcodes::all::OP_NOTIF)
566 .push_opcode(opcodes::all::OP_DROP)
568 .push_opcode(opcodes::all::OP_SWAP)
569 .push_slice(&broadcaster_htlc_key.to_public_key().serialize())
571 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
572 .push_opcode(opcodes::all::OP_ELSE)
573 .push_opcode(opcodes::all::OP_HASH160)
574 .push_slice(&payment_hash160)
575 .push_opcode(opcodes::all::OP_EQUALVERIFY)
576 .push_opcode(opcodes::all::OP_CHECKSIG)
577 .push_opcode(opcodes::all::OP_ENDIF);
578 if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
579 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
580 .push_opcode(opcodes::all::OP_CSV)
581 .push_opcode(opcodes::all::OP_DROP);
583 bldr.push_opcode(opcodes::all::OP_ENDIF)
586 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
587 .push_opcode(opcodes::all::OP_HASH160)
588 .push_slice(&PubkeyHash::hash(&revocation_key.to_public_key().serialize()))
589 .push_opcode(opcodes::all::OP_EQUAL)
590 .push_opcode(opcodes::all::OP_IF)
591 .push_opcode(opcodes::all::OP_CHECKSIG)
592 .push_opcode(opcodes::all::OP_ELSE)
593 .push_slice(&countersignatory_htlc_key.to_public_key().serialize())
594 .push_opcode(opcodes::all::OP_SWAP)
595 .push_opcode(opcodes::all::OP_SIZE)
597 .push_opcode(opcodes::all::OP_EQUAL)
598 .push_opcode(opcodes::all::OP_IF)
599 .push_opcode(opcodes::all::OP_HASH160)
600 .push_slice(&payment_hash160)
601 .push_opcode(opcodes::all::OP_EQUALVERIFY)
603 .push_opcode(opcodes::all::OP_SWAP)
604 .push_slice(&broadcaster_htlc_key.to_public_key().serialize())
606 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
607 .push_opcode(opcodes::all::OP_ELSE)
608 .push_opcode(opcodes::all::OP_DROP)
609 .push_int(htlc.cltv_expiry as i64)
610 .push_opcode(opcodes::all::OP_CLTV)
611 .push_opcode(opcodes::all::OP_DROP)
612 .push_opcode(opcodes::all::OP_CHECKSIG)
613 .push_opcode(opcodes::all::OP_ENDIF);
614 if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
615 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
616 .push_opcode(opcodes::all::OP_CSV)
617 .push_opcode(opcodes::all::OP_DROP);
619 bldr.push_opcode(opcodes::all::OP_ENDIF)
624 /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
625 /// does not need to have its previous_output_index filled.
627 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, keys: &TxCreationKeys) -> ScriptBuf {
628 get_htlc_redeemscript_with_explicit_keys(htlc, channel_type_features, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
631 /// Gets the redeemscript for a funding output from the two funding public keys.
632 /// Note that the order of funding public keys does not matter.
633 pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> ScriptBuf {
634 let broadcaster_funding_key = broadcaster.serialize();
635 let countersignatory_funding_key = countersignatory.serialize();
637 make_funding_redeemscript_from_slices(&broadcaster_funding_key, &countersignatory_funding_key)
640 pub(crate) fn make_funding_redeemscript_from_slices(broadcaster_funding_key: &[u8; 33], countersignatory_funding_key: &[u8; 33]) -> ScriptBuf {
641 let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
642 if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
643 builder.push_slice(broadcaster_funding_key)
644 .push_slice(countersignatory_funding_key)
646 builder.push_slice(countersignatory_funding_key)
647 .push_slice(broadcaster_funding_key)
648 }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
651 /// Builds an unsigned HTLC-Success or HTLC-Timeout transaction from the given channel and HTLC
652 /// parameters. This is used by [`TrustedCommitmentTransaction::get_htlc_sigs`] to fetch the
653 /// transaction which needs signing, and can be used to construct an HTLC transaction which is
654 /// broadcastable given a counterparty HTLC signature.
656 /// Panics if htlc.transaction_output_index.is_none() (as such HTLCs do not appear in the
657 /// commitment transaction).
658 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 {
659 let mut txins: Vec<TxIn> = Vec::new();
660 txins.push(build_htlc_input(commitment_txid, htlc, channel_type_features));
662 let mut txouts: Vec<TxOut> = Vec::new();
663 txouts.push(build_htlc_output(
664 feerate_per_kw, contest_delay, htlc, channel_type_features,
665 broadcaster_delayed_payment_key, revocation_key
670 lock_time: LockTime::from_consensus(if htlc.offered { htlc.cltv_expiry } else { 0 }),
676 pub(crate) fn build_htlc_input(commitment_txid: &Txid, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures) -> TxIn {
678 previous_output: OutPoint {
679 txid: commitment_txid.clone(),
680 vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
682 script_sig: ScriptBuf::new(),
683 sequence: Sequence(if channel_type_features.supports_anchors_zero_fee_htlc_tx() { 1 } else { 0 }),
684 witness: Witness::new(),
688 pub(crate) fn build_htlc_output(
689 feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, broadcaster_delayed_payment_key: &DelayedPaymentKey, revocation_key: &RevocationKey
691 let weight = if htlc.offered {
692 htlc_timeout_tx_weight(channel_type_features)
694 htlc_success_tx_weight(channel_type_features)
696 let output_value = if channel_type_features.supports_anchors_zero_fee_htlc_tx() && !channel_type_features.supports_anchors_nonzero_fee_htlc_tx() {
697 htlc.amount_msat / 1000
699 let total_fee = feerate_per_kw as u64 * weight / 1000;
700 htlc.amount_msat / 1000 - total_fee
704 script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_v0_p2wsh(),
709 /// Returns the witness required to satisfy and spend a HTLC input.
710 pub fn build_htlc_input_witness(
711 local_sig: &Signature, remote_sig: &Signature, preimage: &Option<PaymentPreimage>,
712 redeem_script: &Script, channel_type_features: &ChannelTypeFeatures,
714 let remote_sighash_type = if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
715 EcdsaSighashType::SinglePlusAnyoneCanPay
717 EcdsaSighashType::All
720 let mut witness = Witness::new();
721 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
722 witness.push(vec![]);
723 witness.push_bitcoin_signature(&remote_sig.serialize_der(), remote_sighash_type);
724 witness.push_bitcoin_signature(&local_sig.serialize_der(), EcdsaSighashType::All);
725 if let Some(preimage) = preimage {
726 witness.push(preimage.0.to_vec());
728 // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
729 witness.push(vec![]);
731 witness.push(redeem_script.to_bytes());
735 /// Pre-anchors channel type features did not use to get serialized in the following six structs:
736 /// — [`ChannelTransactionParameters`]
737 /// — [`CommitmentTransaction`]
738 /// — [`CounterpartyOfferedHTLCOutput`]
739 /// — [`CounterpartyReceivedHTLCOutput`]
740 /// — [`HolderHTLCOutput`]
741 /// — [`HolderFundingOutput`]
743 /// To ensure a forwards-compatible serialization, we use odd TLV fields. However, if new features
744 /// are used that could break security, where old signers should be prevented from handling the
745 /// serialized data, an optional even-field TLV will be used as a stand-in to break compatibility.
747 /// This method determines whether or not that option needs to be set based on the chanenl type
748 /// features, and returns it.
750 /// [`CounterpartyOfferedHTLCOutput`]: crate::chain::package::CounterpartyOfferedHTLCOutput
751 /// [`CounterpartyReceivedHTLCOutput`]: crate::chain::package::CounterpartyReceivedHTLCOutput
752 /// [`HolderHTLCOutput`]: crate::chain::package::HolderHTLCOutput
753 /// [`HolderFundingOutput`]: crate::chain::package::HolderFundingOutput
754 pub(crate) fn legacy_deserialization_prevention_marker_for_channel_type_features(features: &ChannelTypeFeatures) -> Option<()> {
755 let mut legacy_version_bit_set = ChannelTypeFeatures::only_static_remote_key();
756 legacy_version_bit_set.set_scid_privacy_required();
757 legacy_version_bit_set.set_zero_conf_required();
759 if features.is_subset(&legacy_version_bit_set) {
766 /// Gets the witnessScript for the to_remote output when anchors are enabled.
768 pub fn get_to_countersignatory_with_anchors_redeemscript(payment_point: &PublicKey) -> ScriptBuf {
770 .push_slice(payment_point.serialize())
771 .push_opcode(opcodes::all::OP_CHECKSIGVERIFY)
773 .push_opcode(opcodes::all::OP_CSV)
777 /// Gets the witnessScript for an anchor output from the funding public key.
778 /// The witness in the spending input must be:
779 /// <BIP 143 funding_signature>
780 /// After 16 blocks of confirmation, an alternative satisfying witness could be:
782 /// (empty vector required to satisfy compliance with MINIMALIF-standard rule)
784 pub fn get_anchor_redeemscript(funding_pubkey: &PublicKey) -> ScriptBuf {
785 Builder::new().push_slice(funding_pubkey.serialize())
786 .push_opcode(opcodes::all::OP_CHECKSIG)
787 .push_opcode(opcodes::all::OP_IFDUP)
788 .push_opcode(opcodes::all::OP_NOTIF)
790 .push_opcode(opcodes::all::OP_CSV)
791 .push_opcode(opcodes::all::OP_ENDIF)
795 /// Locates the output with an anchor script paying to `funding_pubkey` within `commitment_tx`.
796 pub(crate) fn get_anchor_output<'a>(commitment_tx: &'a Transaction, funding_pubkey: &PublicKey) -> Option<(u32, &'a TxOut)> {
797 let anchor_script = chan_utils::get_anchor_redeemscript(funding_pubkey).to_v0_p2wsh();
798 commitment_tx.output.iter().enumerate()
799 .find(|(_, txout)| txout.script_pubkey == anchor_script)
800 .map(|(idx, txout)| (idx as u32, txout))
803 /// Returns the witness required to satisfy and spend an anchor input.
804 pub fn build_anchor_input_witness(funding_key: &PublicKey, funding_sig: &Signature) -> Witness {
805 let anchor_redeem_script = chan_utils::get_anchor_redeemscript(funding_key);
806 let mut ret = Witness::new();
807 ret.push_bitcoin_signature(&funding_sig.serialize_der(), EcdsaSighashType::All);
808 ret.push(anchor_redeem_script.as_bytes());
812 /// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
813 /// The fields are organized by holder/counterparty.
815 /// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
816 /// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
817 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
818 pub struct ChannelTransactionParameters {
819 /// Holder public keys
820 pub holder_pubkeys: ChannelPublicKeys,
821 /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
822 pub holder_selected_contest_delay: u16,
823 /// Whether the holder is the initiator of this channel.
824 /// This is an input to the commitment number obscure factor computation.
825 pub is_outbound_from_holder: bool,
826 /// The late-bound counterparty channel transaction parameters.
827 /// These parameters are populated at the point in the protocol where the counterparty provides them.
828 pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
829 /// The late-bound funding outpoint
830 pub funding_outpoint: Option<chain::transaction::OutPoint>,
831 /// This channel's type, as negotiated during channel open. For old objects where this field
832 /// wasn't serialized, it will default to static_remote_key at deserialization.
833 pub channel_type_features: ChannelTypeFeatures
836 /// Late-bound per-channel counterparty data used to build transactions.
837 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
838 pub struct CounterpartyChannelTransactionParameters {
839 /// Counter-party public keys
840 pub pubkeys: ChannelPublicKeys,
841 /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
842 pub selected_contest_delay: u16,
845 impl ChannelTransactionParameters {
846 /// Whether the late bound parameters are populated.
847 pub fn is_populated(&self) -> bool {
848 self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
851 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
852 /// given that the holder is the broadcaster.
854 /// self.is_populated() must be true before calling this function.
855 pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
856 assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
857 DirectedChannelTransactionParameters {
859 holder_is_broadcaster: true
863 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
864 /// given that the counterparty is the broadcaster.
866 /// self.is_populated() must be true before calling this function.
867 pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
868 assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
869 DirectedChannelTransactionParameters {
871 holder_is_broadcaster: false
876 impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, {
877 (0, pubkeys, required),
878 (2, selected_contest_delay, required),
881 impl Writeable for ChannelTransactionParameters {
882 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
883 let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
884 write_tlv_fields!(writer, {
885 (0, self.holder_pubkeys, required),
886 (2, self.holder_selected_contest_delay, required),
887 (4, self.is_outbound_from_holder, required),
888 (6, self.counterparty_parameters, option),
889 (8, self.funding_outpoint, option),
890 (10, legacy_deserialization_prevention_marker, option),
891 (11, self.channel_type_features, required),
897 impl Readable for ChannelTransactionParameters {
898 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
899 let mut holder_pubkeys = RequiredWrapper(None);
900 let mut holder_selected_contest_delay = RequiredWrapper(None);
901 let mut is_outbound_from_holder = RequiredWrapper(None);
902 let mut counterparty_parameters = None;
903 let mut funding_outpoint = None;
904 let mut _legacy_deserialization_prevention_marker: Option<()> = None;
905 let mut channel_type_features = None;
907 read_tlv_fields!(reader, {
908 (0, holder_pubkeys, required),
909 (2, holder_selected_contest_delay, required),
910 (4, is_outbound_from_holder, required),
911 (6, counterparty_parameters, option),
912 (8, funding_outpoint, option),
913 (10, _legacy_deserialization_prevention_marker, option),
914 (11, channel_type_features, option),
917 let mut additional_features = ChannelTypeFeatures::empty();
918 additional_features.set_anchors_nonzero_fee_htlc_tx_required();
919 chain::package::verify_channel_type_features(&channel_type_features, Some(&additional_features))?;
922 holder_pubkeys: holder_pubkeys.0.unwrap(),
923 holder_selected_contest_delay: holder_selected_contest_delay.0.unwrap(),
924 is_outbound_from_holder: is_outbound_from_holder.0.unwrap(),
925 counterparty_parameters,
927 channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
932 /// Static channel fields used to build transactions given per-commitment fields, organized by
933 /// broadcaster/countersignatory.
935 /// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
936 /// as_holder_broadcastable and as_counterparty_broadcastable functions.
937 pub struct DirectedChannelTransactionParameters<'a> {
938 /// The holder's channel static parameters
939 inner: &'a ChannelTransactionParameters,
940 /// Whether the holder is the broadcaster
941 holder_is_broadcaster: bool,
944 impl<'a> DirectedChannelTransactionParameters<'a> {
945 /// Get the channel pubkeys for the broadcaster
946 pub fn broadcaster_pubkeys(&self) -> &'a ChannelPublicKeys {
947 if self.holder_is_broadcaster {
948 &self.inner.holder_pubkeys
950 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
954 /// Get the channel pubkeys for the countersignatory
955 pub fn countersignatory_pubkeys(&self) -> &'a ChannelPublicKeys {
956 if self.holder_is_broadcaster {
957 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
959 &self.inner.holder_pubkeys
963 /// Get the contest delay applicable to the transactions.
964 /// Note that the contest delay was selected by the countersignatory.
965 pub fn contest_delay(&self) -> u16 {
966 let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
967 if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
970 /// Whether the channel is outbound from the broadcaster.
972 /// The boolean representing the side that initiated the channel is
973 /// an input to the commitment number obscure factor computation.
974 pub fn is_outbound(&self) -> bool {
975 if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
978 /// The funding outpoint
979 pub fn funding_outpoint(&self) -> OutPoint {
980 self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
983 /// Whether to use anchors for this channel
984 pub fn channel_type_features(&self) -> &'a ChannelTypeFeatures {
985 &self.inner.channel_type_features
989 /// Information needed to build and sign a holder's commitment transaction.
991 /// The transaction is only signed once we are ready to broadcast.
992 #[derive(Clone, Debug)]
993 pub struct HolderCommitmentTransaction {
994 inner: CommitmentTransaction,
995 /// Our counterparty's signature for the transaction
996 pub counterparty_sig: Signature,
997 /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
998 pub counterparty_htlc_sigs: Vec<Signature>,
999 // Which order the signatures should go in when constructing the final commitment tx witness.
1000 // The user should be able to reconstruct this themselves, so we don't bother to expose it.
1001 holder_sig_first: bool,
1004 impl Deref for HolderCommitmentTransaction {
1005 type Target = CommitmentTransaction;
1007 fn deref(&self) -> &Self::Target { &self.inner }
1010 impl Eq for HolderCommitmentTransaction {}
1011 impl PartialEq for HolderCommitmentTransaction {
1012 // We dont care whether we are signed in equality comparison
1013 fn eq(&self, o: &Self) -> bool {
1014 self.inner == o.inner
1018 impl_writeable_tlv_based!(HolderCommitmentTransaction, {
1019 (0, inner, required),
1020 (2, counterparty_sig, required),
1021 (4, holder_sig_first, required),
1022 (6, counterparty_htlc_sigs, required_vec),
1025 impl HolderCommitmentTransaction {
1027 pub fn dummy(htlcs: &mut Vec<(HTLCOutputInCommitment, ())>) -> Self {
1028 let secp_ctx = Secp256k1::new();
1029 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1030 let dummy_sig = sign(&secp_ctx, &secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
1032 let keys = TxCreationKeys {
1033 per_commitment_point: dummy_key.clone(),
1034 revocation_key: RevocationKey::from_basepoint(&secp_ctx, &RevocationBasepoint::from(dummy_key), &dummy_key),
1035 broadcaster_htlc_key: HtlcKey::from_basepoint(&secp_ctx, &HtlcBasepoint::from(dummy_key), &dummy_key),
1036 countersignatory_htlc_key: HtlcKey::from_basepoint(&secp_ctx, &HtlcBasepoint::from(dummy_key), &dummy_key),
1037 broadcaster_delayed_payment_key: DelayedPaymentKey::from_basepoint(&secp_ctx, &DelayedPaymentBasepoint::from(dummy_key), &dummy_key),
1039 let channel_pubkeys = ChannelPublicKeys {
1040 funding_pubkey: dummy_key.clone(),
1041 revocation_basepoint: RevocationBasepoint::from(dummy_key),
1042 payment_point: dummy_key.clone(),
1043 delayed_payment_basepoint: DelayedPaymentBasepoint::from(dummy_key.clone()),
1044 htlc_basepoint: HtlcBasepoint::from(dummy_key.clone())
1046 let channel_parameters = ChannelTransactionParameters {
1047 holder_pubkeys: channel_pubkeys.clone(),
1048 holder_selected_contest_delay: 0,
1049 is_outbound_from_holder: false,
1050 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
1051 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1052 channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
1054 let mut counterparty_htlc_sigs = Vec::new();
1055 for _ in 0..htlcs.len() {
1056 counterparty_htlc_sigs.push(dummy_sig);
1058 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());
1059 htlcs.sort_by_key(|htlc| htlc.0.transaction_output_index);
1060 HolderCommitmentTransaction {
1062 counterparty_sig: dummy_sig,
1063 counterparty_htlc_sigs,
1064 holder_sig_first: false
1068 /// Create a new holder transaction with the given counterparty signatures.
1069 /// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
1070 pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
1072 inner: commitment_tx,
1074 counterparty_htlc_sigs,
1075 holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
1079 pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
1080 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
1081 let mut tx = self.inner.built.transaction.clone();
1082 tx.input[0].witness.push(Vec::new());
1084 if self.holder_sig_first {
1085 tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1086 tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1088 tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1089 tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1092 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
1097 /// A pre-built Bitcoin commitment transaction and its txid.
1098 #[derive(Clone, Debug)]
1099 pub struct BuiltCommitmentTransaction {
1100 /// The commitment transaction
1101 pub transaction: Transaction,
1102 /// The txid for the commitment transaction.
1104 /// This is provided as a performance optimization, instead of calling transaction.txid()
1109 impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
1110 (0, transaction, required),
1111 (2, txid, required),
1114 impl BuiltCommitmentTransaction {
1115 /// Get the SIGHASH_ALL sighash value of the transaction.
1117 /// This can be used to verify a signature.
1118 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1119 let sighash = &sighash::SighashCache::new(&self.transaction).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1120 hash_to_message!(sighash)
1123 /// Signs the counterparty's commitment transaction.
1124 pub fn sign_counterparty_commitment<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1125 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1126 sign(secp_ctx, &sighash, funding_key)
1129 /// Signs the holder commitment transaction because we are about to broadcast it.
1130 pub fn sign_holder_commitment<T: secp256k1::Signing, ES: Deref>(
1131 &self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64,
1132 entropy_source: &ES, secp_ctx: &Secp256k1<T>
1133 ) -> Signature where ES::Target: EntropySource {
1134 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1135 sign_with_aux_rand(secp_ctx, &sighash, funding_key, entropy_source)
1139 /// This class tracks the per-transaction information needed to build a closing transaction and will
1140 /// actually build it and sign.
1142 /// This class can be used inside a signer implementation to generate a signature given the relevant
1144 #[derive(Clone, Hash, PartialEq, Eq)]
1145 pub struct ClosingTransaction {
1146 to_holder_value_sat: u64,
1147 to_counterparty_value_sat: u64,
1148 to_holder_script: ScriptBuf,
1149 to_counterparty_script: ScriptBuf,
1153 impl ClosingTransaction {
1154 /// Construct an object of the class
1156 to_holder_value_sat: u64,
1157 to_counterparty_value_sat: u64,
1158 to_holder_script: ScriptBuf,
1159 to_counterparty_script: ScriptBuf,
1160 funding_outpoint: OutPoint,
1162 let built = build_closing_transaction(
1163 to_holder_value_sat, to_counterparty_value_sat,
1164 to_holder_script.clone(), to_counterparty_script.clone(),
1167 ClosingTransaction {
1168 to_holder_value_sat,
1169 to_counterparty_value_sat,
1171 to_counterparty_script,
1176 /// Trust our pre-built transaction.
1178 /// Applies a wrapper which allows access to the transaction.
1180 /// This should only be used if you fully trust the builder of this object. It should not
1181 /// be used by an external signer - instead use the verify function.
1182 pub fn trust(&self) -> TrustedClosingTransaction {
1183 TrustedClosingTransaction { inner: self }
1186 /// Verify our pre-built transaction.
1188 /// Applies a wrapper which allows access to the transaction.
1190 /// An external validating signer must call this method before signing
1191 /// or using the built transaction.
1192 pub fn verify(&self, funding_outpoint: OutPoint) -> Result<TrustedClosingTransaction, ()> {
1193 let built = build_closing_transaction(
1194 self.to_holder_value_sat, self.to_counterparty_value_sat,
1195 self.to_holder_script.clone(), self.to_counterparty_script.clone(),
1198 if self.built != built {
1201 Ok(TrustedClosingTransaction { inner: self })
1204 /// The value to be sent to the holder, or zero if the output will be omitted
1205 pub fn to_holder_value_sat(&self) -> u64 {
1206 self.to_holder_value_sat
1209 /// The value to be sent to the counterparty, or zero if the output will be omitted
1210 pub fn to_counterparty_value_sat(&self) -> u64 {
1211 self.to_counterparty_value_sat
1214 /// The destination of the holder's output
1215 pub fn to_holder_script(&self) -> &Script {
1216 &self.to_holder_script
1219 /// The destination of the counterparty's output
1220 pub fn to_counterparty_script(&self) -> &Script {
1221 &self.to_counterparty_script
1225 /// A wrapper on ClosingTransaction indicating that the built bitcoin
1226 /// transaction is trusted.
1228 /// See trust() and verify() functions on CommitmentTransaction.
1230 /// This structure implements Deref.
1231 pub struct TrustedClosingTransaction<'a> {
1232 inner: &'a ClosingTransaction,
1235 impl<'a> Deref for TrustedClosingTransaction<'a> {
1236 type Target = ClosingTransaction;
1238 fn deref(&self) -> &Self::Target { self.inner }
1241 impl<'a> TrustedClosingTransaction<'a> {
1242 /// The pre-built Bitcoin commitment transaction
1243 pub fn built_transaction(&self) -> &'a Transaction {
1247 /// Get the SIGHASH_ALL sighash value of the transaction.
1249 /// This can be used to verify a signature.
1250 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1251 let sighash = &sighash::SighashCache::new(&self.inner.built).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1252 hash_to_message!(sighash)
1255 /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1256 /// because we are about to broadcast a holder transaction.
1257 pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1258 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1259 sign(secp_ctx, &sighash, funding_key)
1263 /// This class tracks the per-transaction information needed to build a commitment transaction and will
1264 /// actually build it and sign. It is used for holder transactions that we sign only when needed
1265 /// and for transactions we sign for the counterparty.
1267 /// This class can be used inside a signer implementation to generate a signature given the relevant
1269 #[derive(Clone, Debug)]
1270 pub struct CommitmentTransaction {
1271 commitment_number: u64,
1272 to_broadcaster_value_sat: u64,
1273 to_countersignatory_value_sat: u64,
1274 to_broadcaster_delay: Option<u16>, // Added in 0.0.117
1275 feerate_per_kw: u32,
1276 htlcs: Vec<HTLCOutputInCommitment>,
1277 // Note that on upgrades, some features of existing outputs may be missed.
1278 channel_type_features: ChannelTypeFeatures,
1279 // A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
1280 keys: TxCreationKeys,
1281 // For access to the pre-built transaction, see doc for trust()
1282 built: BuiltCommitmentTransaction,
1285 impl Eq for CommitmentTransaction {}
1286 impl PartialEq for CommitmentTransaction {
1287 fn eq(&self, o: &Self) -> bool {
1288 let eq = self.commitment_number == o.commitment_number &&
1289 self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
1290 self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
1291 self.feerate_per_kw == o.feerate_per_kw &&
1292 self.htlcs == o.htlcs &&
1293 self.channel_type_features == o.channel_type_features &&
1294 self.keys == o.keys;
1296 debug_assert_eq!(self.built.transaction, o.built.transaction);
1297 debug_assert_eq!(self.built.txid, o.built.txid);
1303 impl Writeable for CommitmentTransaction {
1304 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1305 let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
1306 write_tlv_fields!(writer, {
1307 (0, self.commitment_number, required),
1308 (1, self.to_broadcaster_delay, option),
1309 (2, self.to_broadcaster_value_sat, required),
1310 (4, self.to_countersignatory_value_sat, required),
1311 (6, self.feerate_per_kw, required),
1312 (8, self.keys, required),
1313 (10, self.built, required),
1314 (12, self.htlcs, required_vec),
1315 (14, legacy_deserialization_prevention_marker, option),
1316 (15, self.channel_type_features, required),
1322 impl Readable for CommitmentTransaction {
1323 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1324 _init_and_read_len_prefixed_tlv_fields!(reader, {
1325 (0, commitment_number, required),
1326 (1, to_broadcaster_delay, option),
1327 (2, to_broadcaster_value_sat, required),
1328 (4, to_countersignatory_value_sat, required),
1329 (6, feerate_per_kw, required),
1330 (8, keys, required),
1331 (10, built, required),
1332 (12, htlcs, required_vec),
1333 (14, _legacy_deserialization_prevention_marker, option),
1334 (15, channel_type_features, option),
1337 let mut additional_features = ChannelTypeFeatures::empty();
1338 additional_features.set_anchors_nonzero_fee_htlc_tx_required();
1339 chain::package::verify_channel_type_features(&channel_type_features, Some(&additional_features))?;
1342 commitment_number: commitment_number.0.unwrap(),
1343 to_broadcaster_value_sat: to_broadcaster_value_sat.0.unwrap(),
1344 to_countersignatory_value_sat: to_countersignatory_value_sat.0.unwrap(),
1345 to_broadcaster_delay,
1346 feerate_per_kw: feerate_per_kw.0.unwrap(),
1347 keys: keys.0.unwrap(),
1348 built: built.0.unwrap(),
1350 channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
1355 impl CommitmentTransaction {
1356 /// Construct an object of the class while assigning transaction output indices to HTLCs.
1358 /// Populates HTLCOutputInCommitment.transaction_output_index in htlcs_with_aux.
1360 /// The generic T allows the caller to match the HTLC output index with auxiliary data.
1361 /// This auxiliary data is not stored in this object.
1363 /// Only include HTLCs that are above the dust limit for the channel.
1365 /// This is not exported to bindings users due to the generic though we likely should expose a version without
1366 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 {
1367 // Sort outputs and populate output indices while keeping track of the auxiliary data
1368 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();
1370 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
1371 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1372 let txid = transaction.txid();
1373 CommitmentTransaction {
1375 to_broadcaster_value_sat,
1376 to_countersignatory_value_sat,
1377 to_broadcaster_delay: Some(channel_parameters.contest_delay()),
1380 channel_type_features: channel_parameters.channel_type_features().clone(),
1382 built: BuiltCommitmentTransaction {
1389 /// Use non-zero fee anchors
1391 /// This is not exported to bindings users due to move, and also not likely to be useful for binding users
1392 pub fn with_non_zero_fee_anchors(mut self) -> Self {
1393 self.channel_type_features.set_anchors_nonzero_fee_htlc_tx_required();
1397 fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<BuiltCommitmentTransaction, ()> {
1398 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
1400 let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
1401 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)?;
1403 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1404 let txid = transaction.txid();
1405 let built_transaction = BuiltCommitmentTransaction {
1409 Ok(built_transaction)
1412 fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
1415 lock_time: LockTime::from_consensus(((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32)),
1421 // This is used in two cases:
1422 // - initial sorting of outputs / HTLCs in the constructor, in which case T is auxiliary data the
1423 // caller needs to have sorted together with the HTLCs so it can keep track of the output index
1424 // - building of a bitcoin transaction during a verify() call, in which case T is just ()
1425 fn internal_build_outputs<T>(keys: &TxCreationKeys, to_broadcaster_value_sat: u64, to_countersignatory_value_sat: u64, htlcs_with_aux: &mut Vec<(HTLCOutputInCommitment, T)>, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<(Vec<TxOut>, Vec<HTLCOutputInCommitment>), ()> {
1426 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1427 let contest_delay = channel_parameters.contest_delay();
1429 let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
1431 if to_countersignatory_value_sat > 0 {
1432 let script = if channel_parameters.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
1433 get_to_countersignatory_with_anchors_redeemscript(&countersignatory_pubkeys.payment_point).to_v0_p2wsh()
1435 Payload::p2wpkh(&BitcoinPublicKey::new(countersignatory_pubkeys.payment_point)).unwrap().script_pubkey()
1439 script_pubkey: script.clone(),
1440 value: to_countersignatory_value_sat,
1446 if to_broadcaster_value_sat > 0 {
1447 let redeem_script = get_revokeable_redeemscript(
1448 &keys.revocation_key,
1450 &keys.broadcaster_delayed_payment_key,
1454 script_pubkey: redeem_script.to_v0_p2wsh(),
1455 value: to_broadcaster_value_sat,
1461 if channel_parameters.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
1462 if to_broadcaster_value_sat > 0 || !htlcs_with_aux.is_empty() {
1463 let anchor_script = get_anchor_redeemscript(broadcaster_funding_key);
1466 script_pubkey: anchor_script.to_v0_p2wsh(),
1467 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1473 if to_countersignatory_value_sat > 0 || !htlcs_with_aux.is_empty() {
1474 let anchor_script = get_anchor_redeemscript(countersignatory_funding_key);
1477 script_pubkey: anchor_script.to_v0_p2wsh(),
1478 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1485 let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
1486 for (htlc, _) in htlcs_with_aux {
1487 let script = chan_utils::get_htlc_redeemscript(&htlc, &channel_parameters.channel_type_features(), &keys);
1489 script_pubkey: script.to_v0_p2wsh(),
1490 value: htlc.amount_msat / 1000,
1492 txouts.push((txout, Some(htlc)));
1495 // Sort output in BIP-69 order (amount, scriptPubkey). Tie-breaks based on HTLC
1496 // CLTV expiration height.
1497 sort_outputs(&mut txouts, |a, b| {
1498 if let &Some(ref a_htlcout) = a {
1499 if let &Some(ref b_htlcout) = b {
1500 a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
1501 // Note that due to hash collisions, we have to have a fallback comparison
1502 // here for fuzzing mode (otherwise at least chanmon_fail_consistency
1504 .then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
1505 // For non-HTLC outputs, if they're copying our SPK we don't really care if we
1506 // close the channel due to mismatches - they're doing something dumb:
1507 } else { cmp::Ordering::Equal }
1508 } else { cmp::Ordering::Equal }
1511 let mut outputs = Vec::with_capacity(txouts.len());
1512 for (idx, out) in txouts.drain(..).enumerate() {
1513 if let Some(htlc) = out.1 {
1514 htlc.transaction_output_index = Some(idx as u32);
1515 htlcs.push(htlc.clone());
1517 outputs.push(out.0);
1519 Ok((outputs, htlcs))
1522 fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
1523 let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
1524 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1525 let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
1526 &broadcaster_pubkeys.payment_point,
1527 &countersignatory_pubkeys.payment_point,
1528 channel_parameters.is_outbound(),
1531 let obscured_commitment_transaction_number =
1532 commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
1535 let mut ins: Vec<TxIn> = Vec::new();
1537 previous_output: channel_parameters.funding_outpoint(),
1538 script_sig: ScriptBuf::new(),
1539 sequence: Sequence(((0x80 as u32) << 8 * 3)
1540 | ((obscured_commitment_transaction_number >> 3 * 8) as u32)),
1541 witness: Witness::new(),
1545 (obscured_commitment_transaction_number, txins)
1548 /// The backwards-counting commitment number
1549 pub fn commitment_number(&self) -> u64 {
1550 self.commitment_number
1553 /// The per commitment point used by the broadcaster.
1554 pub fn per_commitment_point(&self) -> PublicKey {
1555 self.keys.per_commitment_point
1558 /// The value to be sent to the broadcaster
1559 pub fn to_broadcaster_value_sat(&self) -> u64 {
1560 self.to_broadcaster_value_sat
1563 /// The value to be sent to the counterparty
1564 pub fn to_countersignatory_value_sat(&self) -> u64 {
1565 self.to_countersignatory_value_sat
1568 /// The feerate paid per 1000-weight-unit in this commitment transaction.
1569 pub fn feerate_per_kw(&self) -> u32 {
1573 /// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
1574 /// which were included in this commitment transaction in output order.
1575 /// The transaction index is always populated.
1577 /// This is not exported to bindings users as we cannot currently convert Vec references to/from C, though we should
1578 /// expose a less effecient version which creates a Vec of references in the future.
1579 pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
1583 /// Trust our pre-built transaction and derived transaction creation public keys.
1585 /// Applies a wrapper which allows access to these fields.
1587 /// This should only be used if you fully trust the builder of this object. It should not
1588 /// be used by an external signer - instead use the verify function.
1589 pub fn trust(&self) -> TrustedCommitmentTransaction {
1590 TrustedCommitmentTransaction { inner: self }
1593 /// Verify our pre-built transaction and derived transaction creation public keys.
1595 /// Applies a wrapper which allows access to these fields.
1597 /// An external validating signer must call this method before signing
1598 /// or using the built transaction.
1599 pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
1600 // This is the only field of the key cache that we trust
1601 let per_commitment_point = self.keys.per_commitment_point;
1602 let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx);
1603 if keys != self.keys {
1606 let tx = self.internal_rebuild_transaction(&keys, channel_parameters, &broadcaster_keys.funding_pubkey, &countersignatory_keys.funding_pubkey)?;
1607 if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
1610 Ok(TrustedCommitmentTransaction { inner: self })
1614 /// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
1615 /// transaction and the transaction creation keys) are trusted.
1617 /// See trust() and verify() functions on CommitmentTransaction.
1619 /// This structure implements Deref.
1620 pub struct TrustedCommitmentTransaction<'a> {
1621 inner: &'a CommitmentTransaction,
1624 impl<'a> Deref for TrustedCommitmentTransaction<'a> {
1625 type Target = CommitmentTransaction;
1627 fn deref(&self) -> &Self::Target { self.inner }
1630 impl<'a> TrustedCommitmentTransaction<'a> {
1631 /// The transaction ID of the built Bitcoin transaction
1632 pub fn txid(&self) -> Txid {
1633 self.inner.built.txid
1636 /// The pre-built Bitcoin commitment transaction
1637 pub fn built_transaction(&self) -> &'a BuiltCommitmentTransaction {
1641 /// The pre-calculated transaction creation public keys.
1642 pub fn keys(&self) -> &'a TxCreationKeys {
1646 /// Should anchors be used.
1647 pub fn channel_type_features(&self) -> &'a ChannelTypeFeatures {
1648 &self.inner.channel_type_features
1651 /// Get a signature for each HTLC which was included in the commitment transaction (ie for
1652 /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
1654 /// The returned Vec has one entry for each HTLC, and in the same order.
1656 /// This function is only valid in the holder commitment context, it always uses EcdsaSighashType::All.
1657 pub fn get_htlc_sigs<T: secp256k1::Signing, ES: Deref>(
1658 &self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters,
1659 entropy_source: &ES, secp_ctx: &Secp256k1<T>,
1660 ) -> Result<Vec<Signature>, ()> where ES::Target: EntropySource {
1661 let inner = self.inner;
1662 let keys = &inner.keys;
1663 let txid = inner.built.txid;
1664 let mut ret = Vec::with_capacity(inner.htlcs.len());
1665 let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key);
1667 for this_htlc in inner.htlcs.iter() {
1668 assert!(this_htlc.transaction_output_index.is_some());
1669 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);
1671 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);
1673 let sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, EcdsaSighashType::All).unwrap()[..]);
1674 ret.push(sign_with_aux_rand(secp_ctx, &sighash, &holder_htlc_key, entropy_source));
1679 /// Builds the second-level holder HTLC transaction for the HTLC with index `htlc_index`.
1680 pub(crate) fn build_unsigned_htlc_tx(
1681 &self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize,
1682 preimage: &Option<PaymentPreimage>,
1684 let keys = &self.inner.keys;
1685 let this_htlc = &self.inner.htlcs[htlc_index];
1686 assert!(this_htlc.transaction_output_index.is_some());
1687 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
1688 if !this_htlc.offered && preimage.is_none() { unreachable!(); }
1689 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
1690 if this_htlc.offered && preimage.is_some() { unreachable!(); }
1692 build_htlc_transaction(
1693 &self.inner.built.txid, self.inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc,
1694 &self.channel_type_features, &keys.broadcaster_delayed_payment_key, &keys.revocation_key
1699 /// Builds the witness required to spend the input for the HTLC with index `htlc_index` in a
1700 /// second-level holder HTLC transaction.
1701 pub(crate) fn build_htlc_input_witness(
1702 &self, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature,
1703 preimage: &Option<PaymentPreimage>
1705 let keys = &self.inner.keys;
1706 let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(
1707 &self.inner.htlcs[htlc_index], &self.channel_type_features, &keys.broadcaster_htlc_key,
1708 &keys.countersignatory_htlc_key, &keys.revocation_key
1710 chan_utils::build_htlc_input_witness(
1711 signature, counterparty_signature, preimage, &htlc_redeemscript, &self.channel_type_features,
1715 /// Returns the index of the revokeable output, i.e. the `to_local` output sending funds to
1716 /// the broadcaster, in the built transaction, if any exists.
1718 /// There are two cases where this may return `None`:
1719 /// - The balance of the revokeable output is below the dust limit (only found on commitments
1720 /// early in the channel's lifetime, i.e. before the channel reserve is met).
1721 /// - This commitment was created before LDK 0.0.117. In this case, the
1722 /// commitment transaction previously didn't contain enough information to locate the
1723 /// revokeable output.
1724 pub fn revokeable_output_index(&self) -> Option<usize> {
1725 let revokeable_redeemscript = get_revokeable_redeemscript(
1726 &self.keys.revocation_key,
1727 self.to_broadcaster_delay?,
1728 &self.keys.broadcaster_delayed_payment_key,
1730 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1731 let outputs = &self.inner.built.transaction.output;
1732 outputs.iter().enumerate()
1733 .find(|(_, out)| out.script_pubkey == revokeable_p2wsh)
1734 .map(|(idx, _)| idx)
1737 /// Helper method to build an unsigned justice transaction spending the revokeable
1738 /// `to_local` output to a destination script. Fee estimation accounts for the expected
1739 /// revocation witness data that will be added when signed.
1741 /// This method will error if the given fee rate results in a fee greater than the value
1742 /// of the output being spent, or if there exists no revokeable `to_local` output on this
1743 /// commitment transaction. See [`Self::revokeable_output_index`] for more details.
1745 /// The built transaction will allow fee bumping with RBF, and this method takes
1746 /// `feerate_per_kw` as an input such that multiple copies of a justice transaction at different
1747 /// fee rates may be built.
1748 pub fn build_to_local_justice_tx(&self, feerate_per_kw: u64, destination_script: ScriptBuf)
1749 -> Result<Transaction, ()> {
1750 let output_idx = self.revokeable_output_index().ok_or(())?;
1751 let input = vec![TxIn {
1752 previous_output: OutPoint {
1753 txid: self.trust().txid(),
1754 vout: output_idx as u32,
1756 script_sig: ScriptBuf::new(),
1757 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
1758 witness: Witness::new(),
1760 let value = self.inner.built.transaction.output[output_idx].value;
1761 let output = vec![TxOut {
1762 script_pubkey: destination_script,
1765 let mut justice_tx = Transaction {
1767 lock_time: LockTime::ZERO,
1771 let weight = justice_tx.weight().to_wu() + WEIGHT_REVOKED_OUTPUT;
1772 let fee = fee_for_weight(feerate_per_kw as u32, weight);
1773 justice_tx.output[0].value = value.checked_sub(fee).ok_or(())?;
1779 /// Commitment transaction numbers which appear in the transactions themselves are XOR'd with a
1780 /// shared secret first. This prevents on-chain observers from discovering how many commitment
1781 /// transactions occurred in a channel before it was closed.
1783 /// This function gets the shared secret from relevant channel public keys and can be used to
1784 /// "decrypt" the commitment transaction number given a commitment transaction on-chain.
1785 pub fn get_commitment_transaction_number_obscure_factor(
1786 broadcaster_payment_basepoint: &PublicKey,
1787 countersignatory_payment_basepoint: &PublicKey,
1788 outbound_from_broadcaster: bool,
1790 let mut sha = Sha256::engine();
1792 if outbound_from_broadcaster {
1793 sha.input(&broadcaster_payment_basepoint.serialize());
1794 sha.input(&countersignatory_payment_basepoint.serialize());
1796 sha.input(&countersignatory_payment_basepoint.serialize());
1797 sha.input(&broadcaster_payment_basepoint.serialize());
1799 let res = Sha256::from_engine(sha).to_byte_array();
1801 ((res[26] as u64) << 5 * 8)
1802 | ((res[27] as u64) << 4 * 8)
1803 | ((res[28] as u64) << 3 * 8)
1804 | ((res[29] as u64) << 2 * 8)
1805 | ((res[30] as u64) << 1 * 8)
1806 | ((res[31] as u64) << 0 * 8)
1811 use super::{CounterpartyCommitmentSecrets, ChannelPublicKeys};
1813 use crate::prelude::*;
1814 use crate::ln::chan_utils::{get_htlc_redeemscript, get_to_countersignatory_with_anchors_redeemscript, CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
1815 use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
1816 use crate::util::test_utils;
1817 use crate::sign::{ChannelSigner, SignerProvider};
1818 use bitcoin::{Network, Txid, ScriptBuf};
1819 use bitcoin::hashes::Hash;
1820 use bitcoin::hashes::hex::FromHex;
1821 use crate::ln::PaymentHash;
1822 use bitcoin::address::Payload;
1823 use bitcoin::PublicKey as BitcoinPublicKey;
1824 use crate::ln::features::ChannelTypeFeatures;
1826 struct TestCommitmentTxBuilder {
1827 commitment_number: u64,
1828 holder_funding_pubkey: PublicKey,
1829 counterparty_funding_pubkey: PublicKey,
1830 keys: TxCreationKeys,
1831 feerate_per_kw: u32,
1832 htlcs_with_aux: Vec<(HTLCOutputInCommitment, ())>,
1833 channel_parameters: ChannelTransactionParameters,
1834 counterparty_pubkeys: ChannelPublicKeys,
1837 impl TestCommitmentTxBuilder {
1839 let secp_ctx = Secp256k1::new();
1840 let seed = [42; 32];
1841 let network = Network::Testnet;
1842 let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
1843 let signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(false, 1_000_000, 0));
1844 let counterparty_signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(true, 1_000_000, 1));
1845 let delayed_payment_base = &signer.pubkeys().delayed_payment_basepoint;
1846 let per_commitment_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
1847 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
1848 let htlc_basepoint = &signer.pubkeys().htlc_basepoint;
1849 let holder_pubkeys = signer.pubkeys();
1850 let counterparty_pubkeys = counterparty_signer.pubkeys().clone();
1851 let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint);
1852 let channel_parameters = ChannelTransactionParameters {
1853 holder_pubkeys: holder_pubkeys.clone(),
1854 holder_selected_contest_delay: 0,
1855 is_outbound_from_holder: false,
1856 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: counterparty_pubkeys.clone(), selected_contest_delay: 0 }),
1857 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1858 channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
1860 let htlcs_with_aux = Vec::new();
1863 commitment_number: 0,
1864 holder_funding_pubkey: holder_pubkeys.funding_pubkey,
1865 counterparty_funding_pubkey: counterparty_pubkeys.funding_pubkey,
1870 counterparty_pubkeys,
1874 fn build(&mut self, to_broadcaster_sats: u64, to_countersignatory_sats: u64) -> CommitmentTransaction {
1875 CommitmentTransaction::new_with_auxiliary_htlc_data(
1876 self.commitment_number, to_broadcaster_sats, to_countersignatory_sats,
1877 self.holder_funding_pubkey.clone(),
1878 self.counterparty_funding_pubkey.clone(),
1879 self.keys.clone(), self.feerate_per_kw,
1880 &mut self.htlcs_with_aux, &self.channel_parameters.as_holder_broadcastable()
1887 let mut builder = TestCommitmentTxBuilder::new();
1889 // Generate broadcaster and counterparty outputs
1890 let tx = builder.build(1000, 2000);
1891 assert_eq!(tx.built.transaction.output.len(), 2);
1892 assert_eq!(tx.built.transaction.output[1].script_pubkey, Payload::p2wpkh(&BitcoinPublicKey::new(builder.counterparty_pubkeys.payment_point)).unwrap().script_pubkey());
1894 // Generate broadcaster and counterparty outputs as well as two anchors
1895 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
1896 let tx = builder.build(1000, 2000);
1897 assert_eq!(tx.built.transaction.output.len(), 4);
1898 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_to_countersignatory_with_anchors_redeemscript(&builder.counterparty_pubkeys.payment_point).to_v0_p2wsh());
1900 // Generate broadcaster output and anchor
1901 let tx = builder.build(3000, 0);
1902 assert_eq!(tx.built.transaction.output.len(), 2);
1904 // Generate counterparty output and anchor
1905 let tx = builder.build(0, 3000);
1906 assert_eq!(tx.built.transaction.output.len(), 2);
1908 let received_htlc = HTLCOutputInCommitment {
1910 amount_msat: 400000,
1912 payment_hash: PaymentHash([42; 32]),
1913 transaction_output_index: None,
1916 let offered_htlc = HTLCOutputInCommitment {
1918 amount_msat: 600000,
1920 payment_hash: PaymentHash([43; 32]),
1921 transaction_output_index: None,
1924 // Generate broadcaster output and received and offered HTLC outputs, w/o anchors
1925 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1926 builder.htlcs_with_aux = vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())];
1927 let tx = builder.build(3000, 0);
1928 let keys = &builder.keys.clone();
1929 assert_eq!(tx.built.transaction.output.len(), 3);
1930 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh());
1931 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh());
1932 assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh().to_hex_string(),
1933 "0020e43a7c068553003fe68fcae424fb7b28ec5ce48cd8b6744b3945631389bad2fb");
1934 assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh().to_hex_string(),
1935 "0020215d61bba56b19e9eadb6107f5a85d7f99c40f65992443f69229c290165bc00d");
1937 // Generate broadcaster output and received and offered HTLC outputs, with anchors
1938 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
1939 builder.htlcs_with_aux = vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())];
1940 let tx = builder.build(3000, 0);
1941 assert_eq!(tx.built.transaction.output.len(), 5);
1942 assert_eq!(tx.built.transaction.output[2].script_pubkey, get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_v0_p2wsh());
1943 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_v0_p2wsh());
1944 assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_v0_p2wsh().to_hex_string(),
1945 "0020b70d0649c72b38756885c7a30908d912a7898dd5d79457a7280b8e9a20f3f2bc");
1946 assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_v0_p2wsh().to_hex_string(),
1947 "002087a3faeb1950a469c0e2db4a79b093a41b9526e5a6fc6ef5cb949bde3be379c7");
1951 fn test_finding_revokeable_output_index() {
1952 let mut builder = TestCommitmentTxBuilder::new();
1954 // Revokeable output present
1955 let tx = builder.build(1000, 2000);
1956 assert_eq!(tx.built.transaction.output.len(), 2);
1957 assert_eq!(tx.trust().revokeable_output_index(), Some(0));
1959 // Revokeable output present (but to_broadcaster_delay missing)
1960 let tx = CommitmentTransaction { to_broadcaster_delay: None, ..tx };
1961 assert_eq!(tx.built.transaction.output.len(), 2);
1962 assert_eq!(tx.trust().revokeable_output_index(), None);
1964 // Revokeable output not present (our balance is dust)
1965 let tx = builder.build(0, 2000);
1966 assert_eq!(tx.built.transaction.output.len(), 1);
1967 assert_eq!(tx.trust().revokeable_output_index(), None);
1971 fn test_building_to_local_justice_tx() {
1972 let mut builder = TestCommitmentTxBuilder::new();
1974 // Revokeable output not present (our balance is dust)
1975 let tx = builder.build(0, 2000);
1976 assert_eq!(tx.built.transaction.output.len(), 1);
1977 assert!(tx.trust().build_to_local_justice_tx(253, ScriptBuf::new()).is_err());
1979 // Revokeable output present
1980 let tx = builder.build(1000, 2000);
1981 assert_eq!(tx.built.transaction.output.len(), 2);
1984 assert!(tx.trust().build_to_local_justice_tx(100_000, ScriptBuf::new()).is_err());
1986 // Generate a random public key for destination script
1987 let secret_key = SecretKey::from_slice(
1988 &<Vec<u8>>::from_hex("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100")
1989 .unwrap()[..]).unwrap();
1990 let pubkey_hash = BitcoinPublicKey::new(
1991 PublicKey::from_secret_key(&Secp256k1::new(), &secret_key)).wpubkey_hash().unwrap();
1992 let destination_script = ScriptBuf::new_v0_p2wpkh(&pubkey_hash);
1994 let justice_tx = tx.trust().build_to_local_justice_tx(253, destination_script.clone()).unwrap();
1995 assert_eq!(justice_tx.input.len(), 1);
1996 assert_eq!(justice_tx.input[0].previous_output.txid, tx.built.transaction.txid());
1997 assert_eq!(justice_tx.input[0].previous_output.vout, tx.trust().revokeable_output_index().unwrap() as u32);
1998 assert!(justice_tx.input[0].sequence.is_rbf());
2000 assert_eq!(justice_tx.output.len(), 1);
2001 assert!(justice_tx.output[0].value < 1000);
2002 assert_eq!(justice_tx.output[0].script_pubkey, destination_script);
2006 fn test_per_commitment_storage() {
2007 // Test vectors from BOLT 3:
2008 let mut secrets: Vec<[u8; 32]> = Vec::new();
2011 macro_rules! test_secrets {
2013 let mut idx = 281474976710655;
2014 for secret in secrets.iter() {
2015 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
2018 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
2019 assert!(monitor.get_secret(idx).is_none());
2024 // insert_secret correct sequence
2025 monitor = CounterpartyCommitmentSecrets::new();
2028 secrets.push([0; 32]);
2029 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2030 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2033 secrets.push([0; 32]);
2034 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2035 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2038 secrets.push([0; 32]);
2039 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2040 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2043 secrets.push([0; 32]);
2044 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2045 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2048 secrets.push([0; 32]);
2049 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2050 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2053 secrets.push([0; 32]);
2054 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2055 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2058 secrets.push([0; 32]);
2059 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2060 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2063 secrets.push([0; 32]);
2064 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2065 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
2070 // insert_secret #1 incorrect
2071 monitor = CounterpartyCommitmentSecrets::new();
2074 secrets.push([0; 32]);
2075 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2076 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2079 secrets.push([0; 32]);
2080 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2081 assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
2085 // insert_secret #2 incorrect (#1 derived from incorrect)
2086 monitor = CounterpartyCommitmentSecrets::new();
2089 secrets.push([0; 32]);
2090 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2091 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2094 secrets.push([0; 32]);
2095 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2096 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2099 secrets.push([0; 32]);
2100 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2101 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2104 secrets.push([0; 32]);
2105 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2106 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
2110 // insert_secret #3 incorrect
2111 monitor = CounterpartyCommitmentSecrets::new();
2114 secrets.push([0; 32]);
2115 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2116 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2119 secrets.push([0; 32]);
2120 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2121 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2124 secrets.push([0; 32]);
2125 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2126 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2129 secrets.push([0; 32]);
2130 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2131 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
2135 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
2136 monitor = CounterpartyCommitmentSecrets::new();
2139 secrets.push([0; 32]);
2140 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2141 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2144 secrets.push([0; 32]);
2145 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2146 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2149 secrets.push([0; 32]);
2150 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2151 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2154 secrets.push([0; 32]);
2155 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
2156 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2159 secrets.push([0; 32]);
2160 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2161 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2164 secrets.push([0; 32]);
2165 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2166 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2169 secrets.push([0; 32]);
2170 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2171 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2174 secrets.push([0; 32]);
2175 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2176 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2180 // insert_secret #5 incorrect
2181 monitor = CounterpartyCommitmentSecrets::new();
2184 secrets.push([0; 32]);
2185 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2186 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2189 secrets.push([0; 32]);
2190 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2191 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2194 secrets.push([0; 32]);
2195 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2196 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2199 secrets.push([0; 32]);
2200 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2201 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2204 secrets.push([0; 32]);
2205 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2206 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2209 secrets.push([0; 32]);
2210 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2211 assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
2215 // insert_secret #6 incorrect (5 derived from incorrect)
2216 monitor = CounterpartyCommitmentSecrets::new();
2219 secrets.push([0; 32]);
2220 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2221 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2224 secrets.push([0; 32]);
2225 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2226 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2229 secrets.push([0; 32]);
2230 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2231 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2234 secrets.push([0; 32]);
2235 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2236 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2239 secrets.push([0; 32]);
2240 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2241 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2244 secrets.push([0; 32]);
2245 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
2246 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2249 secrets.push([0; 32]);
2250 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2251 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2254 secrets.push([0; 32]);
2255 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2256 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2260 // insert_secret #7 incorrect
2261 monitor = CounterpartyCommitmentSecrets::new();
2264 secrets.push([0; 32]);
2265 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2266 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2269 secrets.push([0; 32]);
2270 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2271 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2274 secrets.push([0; 32]);
2275 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2276 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2279 secrets.push([0; 32]);
2280 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2281 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2284 secrets.push([0; 32]);
2285 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2286 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2289 secrets.push([0; 32]);
2290 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2291 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2294 secrets.push([0; 32]);
2295 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2296 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2299 secrets.push([0; 32]);
2300 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2301 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2305 // insert_secret #8 incorrect
2306 monitor = CounterpartyCommitmentSecrets::new();
2309 secrets.push([0; 32]);
2310 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2311 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2314 secrets.push([0; 32]);
2315 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2316 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2319 secrets.push([0; 32]);
2320 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2321 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2324 secrets.push([0; 32]);
2325 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2326 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2329 secrets.push([0; 32]);
2330 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2331 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2334 secrets.push([0; 32]);
2335 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2336 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2339 secrets.push([0; 32]);
2340 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2341 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2344 secrets.push([0; 32]);
2345 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2346 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());