1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Various utilities for building scripts and deriving keys related to channels. These are
11 //! largely of interest for those implementing the traits on [`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};
50 /// Maximum number of one-way in-flight HTLC (protocol-level value).
51 pub const MAX_HTLCS: u16 = 483;
52 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, non-anchor variant.
53 pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
54 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, anchor variant.
55 pub const OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS: usize = 136;
57 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
58 /// We define a range that encompasses both its non-anchors and anchors variants.
59 pub(crate) const MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 136;
60 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
61 /// We define a range that encompasses both its non-anchors and anchors variants.
62 /// This is the maximum post-anchor value.
63 pub const MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 143;
65 /// The upper bound weight of an anchor input.
66 pub const ANCHOR_INPUT_WITNESS_WEIGHT: u64 = 116;
67 /// The upper bound weight of an HTLC timeout input from a commitment transaction with anchor
69 pub const HTLC_TIMEOUT_INPUT_ANCHOR_WITNESS_WEIGHT: u64 = 288;
70 /// The upper bound weight of an HTLC success input from a commitment transaction with anchor
72 pub const HTLC_SUCCESS_INPUT_ANCHOR_WITNESS_WEIGHT: u64 = 327;
74 /// Gets the weight for an HTLC-Success transaction.
76 pub fn htlc_success_tx_weight(channel_type_features: &ChannelTypeFeatures) -> u64 {
77 const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
78 const HTLC_SUCCESS_ANCHOR_TX_WEIGHT: u64 = 706;
79 if channel_type_features.supports_anchors_zero_fee_htlc_tx() { HTLC_SUCCESS_ANCHOR_TX_WEIGHT } else { HTLC_SUCCESS_TX_WEIGHT }
82 /// Gets the weight for an HTLC-Timeout transaction.
84 pub fn htlc_timeout_tx_weight(channel_type_features: &ChannelTypeFeatures) -> u64 {
85 const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
86 const HTLC_TIMEOUT_ANCHOR_TX_WEIGHT: u64 = 666;
87 if channel_type_features.supports_anchors_zero_fee_htlc_tx() { HTLC_TIMEOUT_ANCHOR_TX_WEIGHT } else { HTLC_TIMEOUT_TX_WEIGHT }
90 /// Describes the type of HTLC claim as determined by analyzing the witness.
91 #[derive(PartialEq, Eq)]
93 /// Claims an offered output on a commitment transaction through the timeout path.
95 /// Claims an offered output on a commitment transaction through the success path.
97 /// Claims an accepted output on a commitment transaction through the timeout path.
99 /// Claims an accepted output on a commitment transaction through the success path.
101 /// Claims an offered/accepted output on a commitment transaction through the revocation path.
106 /// Check if a given input witness attempts to claim a HTLC.
107 pub fn from_witness(witness: &Witness) -> Option<Self> {
108 debug_assert_eq!(OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS, MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT);
109 if witness.len() < 2 {
112 let witness_script = witness.last().unwrap();
113 let second_to_last = witness.second_to_last().unwrap();
114 if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT {
115 if witness.len() == 3 && second_to_last.len() == 33 {
116 // <revocation sig> <revocationpubkey> <witness_script>
117 Some(Self::Revocation)
118 } else if witness.len() == 3 && second_to_last.len() == 32 {
119 // <remotehtlcsig> <payment_preimage> <witness_script>
120 Some(Self::OfferedPreimage)
121 } else if witness.len() == 5 && second_to_last.len() == 0 {
122 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
123 Some(Self::OfferedTimeout)
127 } else if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS {
128 // It's possible for the weight of `offered_htlc_script` and `accepted_htlc_script` to
129 // match so we check for both here.
130 if witness.len() == 3 && second_to_last.len() == 33 {
131 // <revocation sig> <revocationpubkey> <witness_script>
132 Some(Self::Revocation)
133 } else if witness.len() == 3 && second_to_last.len() == 32 {
134 // <remotehtlcsig> <payment_preimage> <witness_script>
135 Some(Self::OfferedPreimage)
136 } else if witness.len() == 5 && second_to_last.len() == 0 {
137 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
138 Some(Self::OfferedTimeout)
139 } else if witness.len() == 3 && second_to_last.len() == 0 {
140 // <remotehtlcsig> <> <witness_script>
141 Some(Self::AcceptedTimeout)
142 } else if witness.len() == 5 && second_to_last.len() == 32 {
143 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
144 Some(Self::AcceptedPreimage)
148 } else if witness_script.len() > MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT &&
149 witness_script.len() <= MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT {
150 // Handle remaining range of ACCEPTED_HTLC_SCRIPT_WEIGHT.
151 if witness.len() == 3 && second_to_last.len() == 33 {
152 // <revocation sig> <revocationpubkey> <witness_script>
153 Some(Self::Revocation)
154 } else if witness.len() == 3 && second_to_last.len() == 0 {
155 // <remotehtlcsig> <> <witness_script>
156 Some(Self::AcceptedTimeout)
157 } else if witness.len() == 5 && second_to_last.len() == 32 {
158 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
159 Some(Self::AcceptedPreimage)
169 // Various functions for key derivation and transaction creation for use within channels. Primarily
170 // used in Channel and ChannelMonitor.
172 /// Build the commitment secret from the seed and the commitment number
173 pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
174 let mut res: [u8; 32] = commitment_seed.clone();
177 if idx & (1 << bitpos) == (1 << bitpos) {
178 res[bitpos / 8] ^= 1 << (bitpos & 7);
179 res = Sha256::hash(&res).to_byte_array();
185 /// Build a closing transaction
186 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 {
188 let mut ins: Vec<TxIn> = Vec::new();
190 previous_output: funding_outpoint,
191 script_sig: ScriptBuf::new(),
192 sequence: Sequence::MAX,
193 witness: Witness::new(),
198 let mut txouts: Vec<(TxOut, ())> = Vec::new();
200 if to_counterparty_value_sat > 0 {
202 script_pubkey: to_counterparty_script,
203 value: to_counterparty_value_sat
207 if to_holder_value_sat > 0 {
209 script_pubkey: to_holder_script,
210 value: to_holder_value_sat
214 transaction_utils::sort_outputs(&mut txouts, |_, _| { cmp::Ordering::Equal }); // Ordering doesnt matter if they used our pubkey...
216 let mut outputs: Vec<TxOut> = Vec::new();
217 for out in txouts.drain(..) {
223 lock_time: LockTime::ZERO,
229 /// Implements the per-commitment secret storage scheme from
230 /// [BOLT 3](https://github.com/lightning/bolts/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
232 /// Allows us to keep track of all of the revocation secrets of our counterparty in just 50*32 bytes
235 pub struct CounterpartyCommitmentSecrets {
236 old_secrets: [([u8; 32], u64); 49],
239 impl Eq for CounterpartyCommitmentSecrets {}
240 impl PartialEq for CounterpartyCommitmentSecrets {
241 fn eq(&self, other: &Self) -> bool {
242 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
243 if secret != o_secret || idx != o_idx {
251 impl CounterpartyCommitmentSecrets {
252 /// Creates a new empty `CounterpartyCommitmentSecrets` structure.
253 pub fn new() -> Self {
254 Self { old_secrets: [([0; 32], 1 << 48); 49], }
258 fn place_secret(idx: u64) -> u8 {
260 if idx & (1 << i) == (1 << i) {
267 /// Returns the minimum index of all stored secrets. Note that indexes start
268 /// at 1 << 48 and get decremented by one for each new secret.
269 pub fn get_min_seen_secret(&self) -> u64 {
270 //TODO This can be optimized?
271 let mut min = 1 << 48;
272 for &(_, idx) in self.old_secrets.iter() {
281 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
282 let mut res: [u8; 32] = secret;
284 let bitpos = bits - 1 - i;
285 if idx & (1 << bitpos) == (1 << bitpos) {
286 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
287 res = Sha256::hash(&res).to_byte_array();
293 /// Inserts the `secret` at `idx`. Returns `Ok(())` if the secret
294 /// was generated in accordance with BOLT 3 and is consistent with previous secrets.
295 pub fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
296 let pos = Self::place_secret(idx);
298 let (old_secret, old_idx) = self.old_secrets[i as usize];
299 if Self::derive_secret(secret, pos, old_idx) != old_secret {
303 if self.get_min_seen_secret() <= idx {
306 self.old_secrets[pos as usize] = (secret, idx);
310 /// Returns the secret at `idx`.
311 /// Returns `None` if `idx` is < [`CounterpartyCommitmentSecrets::get_min_seen_secret`].
312 pub fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
313 for i in 0..self.old_secrets.len() {
314 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
315 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
318 assert!(idx < self.get_min_seen_secret());
323 impl Writeable for CounterpartyCommitmentSecrets {
324 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
325 for &(ref secret, ref idx) in self.old_secrets.iter() {
326 writer.write_all(secret)?;
327 writer.write_all(&idx.to_be_bytes())?;
329 write_tlv_fields!(writer, {});
333 impl Readable for CounterpartyCommitmentSecrets {
334 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
335 let mut old_secrets = [([0; 32], 1 << 48); 49];
336 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
337 *secret = Readable::read(reader)?;
338 *idx = Readable::read(reader)?;
340 read_tlv_fields!(reader, {});
341 Ok(Self { old_secrets })
345 /// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
346 /// from the base secret and the per_commitment_point.
347 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> SecretKey {
348 let mut sha = Sha256::engine();
349 sha.input(&per_commitment_point.serialize());
350 sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
351 let res = Sha256::from_engine(sha).to_byte_array();
353 base_secret.clone().add_tweak(&Scalar::from_be_bytes(res).unwrap())
354 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak contains the hash of the key.")
357 /// Derives a per-commitment-transaction public key (eg an htlc key or a delayed_payment key)
358 /// from the base point and the per_commitment_key. This is the public equivalent of
359 /// derive_private_key - using only public keys to derive a public key instead of private keys.
360 pub fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> PublicKey {
361 let mut sha = Sha256::engine();
362 sha.input(&per_commitment_point.serialize());
363 sha.input(&base_point.serialize());
364 let res = Sha256::from_engine(sha).to_byte_array();
366 let hashkey = PublicKey::from_secret_key(&secp_ctx,
367 &SecretKey::from_slice(&res).expect("Hashes should always be valid keys unless SHA-256 is broken"));
368 base_point.combine(&hashkey)
369 .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.")
372 /// Derives a per-commitment-transaction revocation key from its constituent parts.
374 /// Only the cheating participant owns a valid witness to propagate a revoked
375 /// commitment transaction, thus per_commitment_secret always come from cheater
376 /// and revocation_base_secret always come from punisher, which is the broadcaster
377 /// of the transaction spending with this key knowledge.
378 pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>,
379 per_commitment_secret: &SecretKey, countersignatory_revocation_base_secret: &SecretKey)
381 let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
382 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
384 let rev_append_commit_hash_key = {
385 let mut sha = Sha256::engine();
386 sha.input(&countersignatory_revocation_base_point.serialize());
387 sha.input(&per_commitment_point.serialize());
389 Sha256::from_engine(sha).to_byte_array()
391 let commit_append_rev_hash_key = {
392 let mut sha = Sha256::engine();
393 sha.input(&per_commitment_point.serialize());
394 sha.input(&countersignatory_revocation_base_point.serialize());
396 Sha256::from_engine(sha).to_byte_array()
399 let countersignatory_contrib = countersignatory_revocation_base_secret.clone().mul_tweak(&Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
400 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
401 let broadcaster_contrib = per_commitment_secret.clone().mul_tweak(&Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
402 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
403 countersignatory_contrib.add_tweak(&Scalar::from_be_bytes(broadcaster_contrib.secret_bytes()).unwrap())
404 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
407 /// Derives a per-commitment-transaction revocation public key from its constituent parts. This is
408 /// the public equivalend of derive_private_revocation_key - using only public keys to derive a
409 /// public key instead of private keys.
411 /// Only the cheating participant owns a valid witness to propagate a revoked
412 /// commitment transaction, thus per_commitment_point always come from cheater
413 /// and revocation_base_point always come from punisher, which is the broadcaster
414 /// of the transaction spending with this key knowledge.
416 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
417 /// generated (ie our own).
418 pub fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp256k1<T>,
419 per_commitment_point: &PublicKey, countersignatory_revocation_base_point: &PublicKey)
421 let rev_append_commit_hash_key = {
422 let mut sha = Sha256::engine();
423 sha.input(&countersignatory_revocation_base_point.serialize());
424 sha.input(&per_commitment_point.serialize());
426 Sha256::from_engine(sha).to_byte_array()
428 let commit_append_rev_hash_key = {
429 let mut sha = Sha256::engine();
430 sha.input(&per_commitment_point.serialize());
431 sha.input(&countersignatory_revocation_base_point.serialize());
433 Sha256::from_engine(sha).to_byte_array()
436 let countersignatory_contrib = countersignatory_revocation_base_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
437 .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
438 let broadcaster_contrib = per_commitment_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
439 .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
440 countersignatory_contrib.combine(&broadcaster_contrib)
441 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
444 /// The set of public keys which are used in the creation of one commitment transaction.
445 /// These are derived from the channel base keys and per-commitment data.
447 /// A broadcaster key is provided from potential broadcaster of the computed transaction.
448 /// A countersignatory key is coming from a protocol participant unable to broadcast the
451 /// These keys are assumed to be good, either because the code derived them from
452 /// channel basepoints via the new function, or they were obtained via
453 /// CommitmentTransaction.trust().keys() because we trusted the source of the
454 /// pre-calculated keys.
455 #[derive(PartialEq, Eq, Clone, Debug)]
456 pub struct TxCreationKeys {
457 /// The broadcaster's per-commitment public key which was used to derive the other keys.
458 pub per_commitment_point: PublicKey,
459 /// The revocation key which is used to allow the broadcaster of the commitment
460 /// transaction to provide their counterparty the ability to punish them if they broadcast
462 pub revocation_key: PublicKey,
463 /// Broadcaster's HTLC Key
464 pub broadcaster_htlc_key: PublicKey,
465 /// Countersignatory's HTLC Key
466 pub countersignatory_htlc_key: PublicKey,
467 /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
468 pub broadcaster_delayed_payment_key: PublicKey,
471 impl_writeable_tlv_based!(TxCreationKeys, {
472 (0, per_commitment_point, required),
473 (2, revocation_key, required),
474 (4, broadcaster_htlc_key, required),
475 (6, countersignatory_htlc_key, required),
476 (8, broadcaster_delayed_payment_key, required),
479 /// One counterparty's public keys which do not change over the life of a channel.
480 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
481 pub struct ChannelPublicKeys {
482 /// The public key which is used to sign all commitment transactions, as it appears in the
483 /// on-chain channel lock-in 2-of-2 multisig output.
484 pub funding_pubkey: PublicKey,
485 /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
486 /// revocation keys. This is combined with the per-commitment-secret generated by the
487 /// counterparty to create a secret which the counterparty can reveal to revoke previous
489 pub revocation_basepoint: PublicKey,
490 /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
491 /// spendable primary channel balance on the broadcaster's commitment transaction. This key is
492 /// static across every commitment transaction.
493 pub payment_point: PublicKey,
494 /// The base point which is used (with derive_public_key) to derive a per-commitment payment
495 /// public key which receives non-HTLC-encumbered funds which are only available for spending
496 /// after some delay (or can be claimed via the revocation path).
497 pub delayed_payment_basepoint: PublicKey,
498 /// The base point which is used (with derive_public_key) to derive a per-commitment public key
499 /// which is used to encumber HTLC-in-flight outputs.
500 pub htlc_basepoint: PublicKey,
503 impl_writeable_tlv_based!(ChannelPublicKeys, {
504 (0, funding_pubkey, required),
505 (2, revocation_basepoint, required),
506 (4, payment_point, required),
507 (6, delayed_payment_basepoint, required),
508 (8, htlc_basepoint, required),
511 impl TxCreationKeys {
512 /// Create per-state keys from channel base points and the per-commitment point.
513 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
514 pub fn derive_new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, broadcaster_delayed_payment_base: &PublicKey, broadcaster_htlc_base: &PublicKey, countersignatory_revocation_base: &PublicKey, countersignatory_htlc_base: &PublicKey) -> TxCreationKeys {
516 per_commitment_point: per_commitment_point.clone(),
517 revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &countersignatory_revocation_base),
518 broadcaster_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_htlc_base),
519 countersignatory_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &countersignatory_htlc_base),
520 broadcaster_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_delayed_payment_base),
524 /// Generate per-state keys from channel static keys.
525 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
526 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 {
527 TxCreationKeys::derive_new(
529 &per_commitment_point,
530 &broadcaster_keys.delayed_payment_basepoint,
531 &broadcaster_keys.htlc_basepoint,
532 &countersignatory_keys.revocation_basepoint,
533 &countersignatory_keys.htlc_basepoint,
538 /// The maximum length of a script returned by get_revokeable_redeemscript.
539 // Calculated as 6 bytes of opcodes, 1 byte push plus 2 bytes for contest_delay, and two public
540 // keys of 33 bytes (+ 1 push).
541 pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 3 + 34*2;
543 /// A script either spendable by the revocation
544 /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
545 /// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
546 pub fn get_revokeable_redeemscript(revocation_key: &PublicKey, contest_delay: u16, broadcaster_delayed_payment_key: &PublicKey) -> ScriptBuf {
547 let res = Builder::new().push_opcode(opcodes::all::OP_IF)
548 .push_slice(&revocation_key.serialize())
549 .push_opcode(opcodes::all::OP_ELSE)
550 .push_int(contest_delay as i64)
551 .push_opcode(opcodes::all::OP_CSV)
552 .push_opcode(opcodes::all::OP_DROP)
553 .push_slice(&broadcaster_delayed_payment_key.serialize())
554 .push_opcode(opcodes::all::OP_ENDIF)
555 .push_opcode(opcodes::all::OP_CHECKSIG)
557 debug_assert!(res.len() <= REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH);
561 /// Returns the script for the counterparty's output on a holder's commitment transaction based on
562 /// the channel type.
563 pub fn get_counterparty_payment_script(channel_type_features: &ChannelTypeFeatures, payment_key: &PublicKey) -> ScriptBuf {
564 if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
565 get_to_countersignatory_with_anchors_redeemscript(payment_key).to_v0_p2wsh()
567 ScriptBuf::new_v0_p2wpkh(&WPubkeyHash::hash(&payment_key.serialize()))
571 /// Information about an HTLC as it appears in a commitment transaction
572 #[derive(Clone, Debug, PartialEq, Eq)]
573 pub struct HTLCOutputInCommitment {
574 /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
575 /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
576 /// need to compare this value to whether the commitment transaction in question is that of
577 /// the counterparty or our own.
579 /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
580 /// this divided by 1000.
581 pub amount_msat: u64,
582 /// The CLTV lock-time at which this HTLC expires.
583 pub cltv_expiry: u32,
584 /// The hash of the preimage which unlocks this HTLC.
585 pub payment_hash: PaymentHash,
586 /// The position within the commitment transactions' outputs. This may be None if the value is
587 /// below the dust limit (in which case no output appears in the commitment transaction and the
588 /// value is spent to additional transaction fees).
589 pub transaction_output_index: Option<u32>,
592 impl_writeable_tlv_based!(HTLCOutputInCommitment, {
593 (0, offered, required),
594 (2, amount_msat, required),
595 (4, cltv_expiry, required),
596 (6, payment_hash, required),
597 (8, transaction_output_index, option),
601 pub(crate) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, broadcaster_htlc_key: &PublicKey, countersignatory_htlc_key: &PublicKey, revocation_key: &PublicKey) -> ScriptBuf {
602 let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).to_byte_array();
604 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
605 .push_opcode(opcodes::all::OP_HASH160)
606 .push_slice(PubkeyHash::hash(&revocation_key.serialize()))
607 .push_opcode(opcodes::all::OP_EQUAL)
608 .push_opcode(opcodes::all::OP_IF)
609 .push_opcode(opcodes::all::OP_CHECKSIG)
610 .push_opcode(opcodes::all::OP_ELSE)
611 .push_slice(countersignatory_htlc_key.serialize())
612 .push_opcode(opcodes::all::OP_SWAP)
613 .push_opcode(opcodes::all::OP_SIZE)
615 .push_opcode(opcodes::all::OP_EQUAL)
616 .push_opcode(opcodes::all::OP_NOTIF)
617 .push_opcode(opcodes::all::OP_DROP)
619 .push_opcode(opcodes::all::OP_SWAP)
620 .push_slice(broadcaster_htlc_key.serialize())
622 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
623 .push_opcode(opcodes::all::OP_ELSE)
624 .push_opcode(opcodes::all::OP_HASH160)
625 .push_slice(&payment_hash160)
626 .push_opcode(opcodes::all::OP_EQUALVERIFY)
627 .push_opcode(opcodes::all::OP_CHECKSIG)
628 .push_opcode(opcodes::all::OP_ENDIF);
629 if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
630 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
631 .push_opcode(opcodes::all::OP_CSV)
632 .push_opcode(opcodes::all::OP_DROP);
634 bldr.push_opcode(opcodes::all::OP_ENDIF)
637 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
638 .push_opcode(opcodes::all::OP_HASH160)
639 .push_slice(PubkeyHash::hash(&revocation_key.serialize()))
640 .push_opcode(opcodes::all::OP_EQUAL)
641 .push_opcode(opcodes::all::OP_IF)
642 .push_opcode(opcodes::all::OP_CHECKSIG)
643 .push_opcode(opcodes::all::OP_ELSE)
644 .push_slice(countersignatory_htlc_key.serialize())
645 .push_opcode(opcodes::all::OP_SWAP)
646 .push_opcode(opcodes::all::OP_SIZE)
648 .push_opcode(opcodes::all::OP_EQUAL)
649 .push_opcode(opcodes::all::OP_IF)
650 .push_opcode(opcodes::all::OP_HASH160)
651 .push_slice(&payment_hash160)
652 .push_opcode(opcodes::all::OP_EQUALVERIFY)
654 .push_opcode(opcodes::all::OP_SWAP)
655 .push_slice(broadcaster_htlc_key.serialize())
657 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
658 .push_opcode(opcodes::all::OP_ELSE)
659 .push_opcode(opcodes::all::OP_DROP)
660 .push_int(htlc.cltv_expiry as i64)
661 .push_opcode(opcodes::all::OP_CLTV)
662 .push_opcode(opcodes::all::OP_DROP)
663 .push_opcode(opcodes::all::OP_CHECKSIG)
664 .push_opcode(opcodes::all::OP_ENDIF);
665 if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
666 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
667 .push_opcode(opcodes::all::OP_CSV)
668 .push_opcode(opcodes::all::OP_DROP);
670 bldr.push_opcode(opcodes::all::OP_ENDIF)
675 /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
676 /// does not need to have its previous_output_index filled.
678 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, keys: &TxCreationKeys) -> ScriptBuf {
679 get_htlc_redeemscript_with_explicit_keys(htlc, channel_type_features, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
682 /// Gets the redeemscript for a funding output from the two funding public keys.
683 /// Note that the order of funding public keys does not matter.
684 pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> ScriptBuf {
685 let broadcaster_funding_key = broadcaster.serialize();
686 let countersignatory_funding_key = countersignatory.serialize();
688 make_funding_redeemscript_from_slices(&broadcaster_funding_key, &countersignatory_funding_key)
691 pub(crate) fn make_funding_redeemscript_from_slices(broadcaster_funding_key: &[u8; 33], countersignatory_funding_key: &[u8; 33]) -> ScriptBuf {
692 let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
693 if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
694 builder.push_slice(broadcaster_funding_key)
695 .push_slice(countersignatory_funding_key)
697 builder.push_slice(countersignatory_funding_key)
698 .push_slice(broadcaster_funding_key)
699 }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
702 /// Builds an unsigned HTLC-Success or HTLC-Timeout transaction from the given channel and HTLC
703 /// parameters. This is used by [`TrustedCommitmentTransaction::get_htlc_sigs`] to fetch the
704 /// transaction which needs signing, and can be used to construct an HTLC transaction which is
705 /// broadcastable given a counterparty HTLC signature.
707 /// Panics if htlc.transaction_output_index.is_none() (as such HTLCs do not appear in the
708 /// commitment transaction).
709 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: &PublicKey, revocation_key: &PublicKey) -> Transaction {
710 let mut txins: Vec<TxIn> = Vec::new();
711 txins.push(build_htlc_input(commitment_txid, htlc, channel_type_features));
713 let mut txouts: Vec<TxOut> = Vec::new();
714 txouts.push(build_htlc_output(
715 feerate_per_kw, contest_delay, htlc, channel_type_features,
716 broadcaster_delayed_payment_key, revocation_key
721 lock_time: LockTime::from_consensus(if htlc.offered { htlc.cltv_expiry } else { 0 }),
727 pub(crate) fn build_htlc_input(commitment_txid: &Txid, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures) -> TxIn {
729 previous_output: OutPoint {
730 txid: commitment_txid.clone(),
731 vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
733 script_sig: ScriptBuf::new(),
734 sequence: Sequence(if channel_type_features.supports_anchors_zero_fee_htlc_tx() { 1 } else { 0 }),
735 witness: Witness::new(),
739 pub(crate) fn build_htlc_output(
740 feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, broadcaster_delayed_payment_key: &PublicKey, revocation_key: &PublicKey
742 let weight = if htlc.offered {
743 htlc_timeout_tx_weight(channel_type_features)
745 htlc_success_tx_weight(channel_type_features)
747 let output_value = if channel_type_features.supports_anchors_zero_fee_htlc_tx() && !channel_type_features.supports_anchors_nonzero_fee_htlc_tx() {
748 htlc.amount_msat / 1000
750 let total_fee = feerate_per_kw as u64 * weight / 1000;
751 htlc.amount_msat / 1000 - total_fee
755 script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_v0_p2wsh(),
760 /// Returns the witness required to satisfy and spend a HTLC input.
761 pub fn build_htlc_input_witness(
762 local_sig: &Signature, remote_sig: &Signature, preimage: &Option<PaymentPreimage>,
763 redeem_script: &Script, channel_type_features: &ChannelTypeFeatures,
765 let remote_sighash_type = if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
766 EcdsaSighashType::SinglePlusAnyoneCanPay
768 EcdsaSighashType::All
771 let mut witness = Witness::new();
772 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
773 witness.push(vec![]);
774 witness.push_bitcoin_signature(&remote_sig.serialize_der(), remote_sighash_type);
775 witness.push_bitcoin_signature(&local_sig.serialize_der(), EcdsaSighashType::All);
776 if let Some(preimage) = preimage {
777 witness.push(preimage.0.to_vec());
779 // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
780 witness.push(vec![]);
782 witness.push(redeem_script.to_bytes());
786 /// Pre-anchors channel type features did not use to get serialized in the following six structs:
787 /// — [`ChannelTransactionParameters`]
788 /// — [`CommitmentTransaction`]
789 /// — [`CounterpartyOfferedHTLCOutput`]
790 /// — [`CounterpartyReceivedHTLCOutput`]
791 /// — [`HolderHTLCOutput`]
792 /// — [`HolderFundingOutput`]
794 /// To ensure a forwards-compatible serialization, we use odd TLV fields. However, if new features
795 /// are used that could break security, where old signers should be prevented from handling the
796 /// serialized data, an optional even-field TLV will be used as a stand-in to break compatibility.
798 /// This method determines whether or not that option needs to be set based on the chanenl type
799 /// features, and returns it.
801 /// [`CounterpartyOfferedHTLCOutput`]: crate::chain::package::CounterpartyOfferedHTLCOutput
802 /// [`CounterpartyReceivedHTLCOutput`]: crate::chain::package::CounterpartyReceivedHTLCOutput
803 /// [`HolderHTLCOutput`]: crate::chain::package::HolderHTLCOutput
804 /// [`HolderFundingOutput`]: crate::chain::package::HolderFundingOutput
805 pub(crate) fn legacy_deserialization_prevention_marker_for_channel_type_features(features: &ChannelTypeFeatures) -> Option<()> {
806 let mut legacy_version_bit_set = ChannelTypeFeatures::only_static_remote_key();
807 legacy_version_bit_set.set_scid_privacy_required();
808 legacy_version_bit_set.set_zero_conf_required();
810 if features.is_subset(&legacy_version_bit_set) {
817 /// Gets the witnessScript for the to_remote output when anchors are enabled.
819 pub fn get_to_countersignatory_with_anchors_redeemscript(payment_point: &PublicKey) -> ScriptBuf {
821 .push_slice(payment_point.serialize())
822 .push_opcode(opcodes::all::OP_CHECKSIGVERIFY)
824 .push_opcode(opcodes::all::OP_CSV)
828 /// Gets the witnessScript for an anchor output from the funding public key.
829 /// The witness in the spending input must be:
830 /// <BIP 143 funding_signature>
831 /// After 16 blocks of confirmation, an alternative satisfying witness could be:
833 /// (empty vector required to satisfy compliance with MINIMALIF-standard rule)
835 pub fn get_anchor_redeemscript(funding_pubkey: &PublicKey) -> ScriptBuf {
836 Builder::new().push_slice(funding_pubkey.serialize())
837 .push_opcode(opcodes::all::OP_CHECKSIG)
838 .push_opcode(opcodes::all::OP_IFDUP)
839 .push_opcode(opcodes::all::OP_NOTIF)
841 .push_opcode(opcodes::all::OP_CSV)
842 .push_opcode(opcodes::all::OP_ENDIF)
846 /// Locates the output with an anchor script paying to `funding_pubkey` within `commitment_tx`.
847 pub(crate) fn get_anchor_output<'a>(commitment_tx: &'a Transaction, funding_pubkey: &PublicKey) -> Option<(u32, &'a TxOut)> {
848 let anchor_script = chan_utils::get_anchor_redeemscript(funding_pubkey).to_v0_p2wsh();
849 commitment_tx.output.iter().enumerate()
850 .find(|(_, txout)| txout.script_pubkey == anchor_script)
851 .map(|(idx, txout)| (idx as u32, txout))
854 /// Returns the witness required to satisfy and spend an anchor input.
855 pub fn build_anchor_input_witness(funding_key: &PublicKey, funding_sig: &Signature) -> Witness {
856 let anchor_redeem_script = chan_utils::get_anchor_redeemscript(funding_key);
857 let mut ret = Witness::new();
858 ret.push_bitcoin_signature(&funding_sig.serialize_der(), EcdsaSighashType::All);
859 ret.push(anchor_redeem_script.as_bytes());
863 /// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
864 /// The fields are organized by holder/counterparty.
866 /// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
867 /// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
868 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
869 pub struct ChannelTransactionParameters {
870 /// Holder public keys
871 pub holder_pubkeys: ChannelPublicKeys,
872 /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
873 pub holder_selected_contest_delay: u16,
874 /// Whether the holder is the initiator of this channel.
875 /// This is an input to the commitment number obscure factor computation.
876 pub is_outbound_from_holder: bool,
877 /// The late-bound counterparty channel transaction parameters.
878 /// These parameters are populated at the point in the protocol where the counterparty provides them.
879 pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
880 /// The late-bound funding outpoint
881 pub funding_outpoint: Option<chain::transaction::OutPoint>,
882 /// This channel's type, as negotiated during channel open. For old objects where this field
883 /// wasn't serialized, it will default to static_remote_key at deserialization.
884 pub channel_type_features: ChannelTypeFeatures
887 /// Late-bound per-channel counterparty data used to build transactions.
888 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
889 pub struct CounterpartyChannelTransactionParameters {
890 /// Counter-party public keys
891 pub pubkeys: ChannelPublicKeys,
892 /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
893 pub selected_contest_delay: u16,
896 impl ChannelTransactionParameters {
897 /// Whether the late bound parameters are populated.
898 pub fn is_populated(&self) -> bool {
899 self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
902 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
903 /// given that the holder is the broadcaster.
905 /// self.is_populated() must be true before calling this function.
906 pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
907 assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
908 DirectedChannelTransactionParameters {
910 holder_is_broadcaster: true
914 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
915 /// given that the counterparty is the broadcaster.
917 /// self.is_populated() must be true before calling this function.
918 pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
919 assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
920 DirectedChannelTransactionParameters {
922 holder_is_broadcaster: false
927 impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, {
928 (0, pubkeys, required),
929 (2, selected_contest_delay, required),
932 impl Writeable for ChannelTransactionParameters {
933 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
934 let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
935 write_tlv_fields!(writer, {
936 (0, self.holder_pubkeys, required),
937 (2, self.holder_selected_contest_delay, required),
938 (4, self.is_outbound_from_holder, required),
939 (6, self.counterparty_parameters, option),
940 (8, self.funding_outpoint, option),
941 (10, legacy_deserialization_prevention_marker, option),
942 (11, self.channel_type_features, required),
948 impl Readable for ChannelTransactionParameters {
949 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
950 let mut holder_pubkeys = RequiredWrapper(None);
951 let mut holder_selected_contest_delay = RequiredWrapper(None);
952 let mut is_outbound_from_holder = RequiredWrapper(None);
953 let mut counterparty_parameters = None;
954 let mut funding_outpoint = None;
955 let mut _legacy_deserialization_prevention_marker: Option<()> = None;
956 let mut channel_type_features = None;
958 read_tlv_fields!(reader, {
959 (0, holder_pubkeys, required),
960 (2, holder_selected_contest_delay, required),
961 (4, is_outbound_from_holder, required),
962 (6, counterparty_parameters, option),
963 (8, funding_outpoint, option),
964 (10, _legacy_deserialization_prevention_marker, option),
965 (11, channel_type_features, option),
968 let mut additional_features = ChannelTypeFeatures::empty();
969 additional_features.set_anchors_nonzero_fee_htlc_tx_required();
970 chain::package::verify_channel_type_features(&channel_type_features, Some(&additional_features))?;
973 holder_pubkeys: holder_pubkeys.0.unwrap(),
974 holder_selected_contest_delay: holder_selected_contest_delay.0.unwrap(),
975 is_outbound_from_holder: is_outbound_from_holder.0.unwrap(),
976 counterparty_parameters,
978 channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
983 /// Static channel fields used to build transactions given per-commitment fields, organized by
984 /// broadcaster/countersignatory.
986 /// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
987 /// as_holder_broadcastable and as_counterparty_broadcastable functions.
988 pub struct DirectedChannelTransactionParameters<'a> {
989 /// The holder's channel static parameters
990 inner: &'a ChannelTransactionParameters,
991 /// Whether the holder is the broadcaster
992 holder_is_broadcaster: bool,
995 impl<'a> DirectedChannelTransactionParameters<'a> {
996 /// Get the channel pubkeys for the broadcaster
997 pub fn broadcaster_pubkeys(&self) -> &'a ChannelPublicKeys {
998 if self.holder_is_broadcaster {
999 &self.inner.holder_pubkeys
1001 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
1005 /// Get the channel pubkeys for the countersignatory
1006 pub fn countersignatory_pubkeys(&self) -> &'a ChannelPublicKeys {
1007 if self.holder_is_broadcaster {
1008 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
1010 &self.inner.holder_pubkeys
1014 /// Get the contest delay applicable to the transactions.
1015 /// Note that the contest delay was selected by the countersignatory.
1016 pub fn contest_delay(&self) -> u16 {
1017 let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
1018 if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
1021 /// Whether the channel is outbound from the broadcaster.
1023 /// The boolean representing the side that initiated the channel is
1024 /// an input to the commitment number obscure factor computation.
1025 pub fn is_outbound(&self) -> bool {
1026 if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
1029 /// The funding outpoint
1030 pub fn funding_outpoint(&self) -> OutPoint {
1031 self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
1034 /// Whether to use anchors for this channel
1035 pub fn channel_type_features(&self) -> &'a ChannelTypeFeatures {
1036 &self.inner.channel_type_features
1040 /// Information needed to build and sign a holder's commitment transaction.
1042 /// The transaction is only signed once we are ready to broadcast.
1043 #[derive(Clone, Debug)]
1044 pub struct HolderCommitmentTransaction {
1045 inner: CommitmentTransaction,
1046 /// Our counterparty's signature for the transaction
1047 pub counterparty_sig: Signature,
1048 /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
1049 pub counterparty_htlc_sigs: Vec<Signature>,
1050 // Which order the signatures should go in when constructing the final commitment tx witness.
1051 // The user should be able to reconstruct this themselves, so we don't bother to expose it.
1052 holder_sig_first: bool,
1055 impl Deref for HolderCommitmentTransaction {
1056 type Target = CommitmentTransaction;
1058 fn deref(&self) -> &Self::Target { &self.inner }
1061 impl Eq for HolderCommitmentTransaction {}
1062 impl PartialEq for HolderCommitmentTransaction {
1063 // We dont care whether we are signed in equality comparison
1064 fn eq(&self, o: &Self) -> bool {
1065 self.inner == o.inner
1069 impl_writeable_tlv_based!(HolderCommitmentTransaction, {
1070 (0, inner, required),
1071 (2, counterparty_sig, required),
1072 (4, holder_sig_first, required),
1073 (6, counterparty_htlc_sigs, required_vec),
1076 impl HolderCommitmentTransaction {
1078 pub fn dummy(htlcs: &mut Vec<(HTLCOutputInCommitment, ())>) -> Self {
1079 let secp_ctx = Secp256k1::new();
1080 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1081 let dummy_sig = sign(&secp_ctx, &secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
1083 let keys = TxCreationKeys {
1084 per_commitment_point: dummy_key.clone(),
1085 revocation_key: dummy_key.clone(),
1086 broadcaster_htlc_key: dummy_key.clone(),
1087 countersignatory_htlc_key: dummy_key.clone(),
1088 broadcaster_delayed_payment_key: dummy_key.clone(),
1090 let channel_pubkeys = ChannelPublicKeys {
1091 funding_pubkey: dummy_key.clone(),
1092 revocation_basepoint: dummy_key.clone(),
1093 payment_point: dummy_key.clone(),
1094 delayed_payment_basepoint: dummy_key.clone(),
1095 htlc_basepoint: dummy_key.clone()
1097 let channel_parameters = ChannelTransactionParameters {
1098 holder_pubkeys: channel_pubkeys.clone(),
1099 holder_selected_contest_delay: 0,
1100 is_outbound_from_holder: false,
1101 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
1102 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1103 channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
1105 let mut counterparty_htlc_sigs = Vec::new();
1106 for _ in 0..htlcs.len() {
1107 counterparty_htlc_sigs.push(dummy_sig);
1109 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());
1110 htlcs.sort_by_key(|htlc| htlc.0.transaction_output_index);
1111 HolderCommitmentTransaction {
1113 counterparty_sig: dummy_sig,
1114 counterparty_htlc_sigs,
1115 holder_sig_first: false
1119 /// Create a new holder transaction with the given counterparty signatures.
1120 /// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
1121 pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
1123 inner: commitment_tx,
1125 counterparty_htlc_sigs,
1126 holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
1130 pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
1131 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
1132 let mut tx = self.inner.built.transaction.clone();
1133 tx.input[0].witness.push(Vec::new());
1135 if self.holder_sig_first {
1136 tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1137 tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1139 tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1140 tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1143 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
1148 /// A pre-built Bitcoin commitment transaction and its txid.
1149 #[derive(Clone, Debug)]
1150 pub struct BuiltCommitmentTransaction {
1151 /// The commitment transaction
1152 pub transaction: Transaction,
1153 /// The txid for the commitment transaction.
1155 /// This is provided as a performance optimization, instead of calling transaction.txid()
1160 impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
1161 (0, transaction, required),
1162 (2, txid, required),
1165 impl BuiltCommitmentTransaction {
1166 /// Get the SIGHASH_ALL sighash value of the transaction.
1168 /// This can be used to verify a signature.
1169 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1170 let sighash = &sighash::SighashCache::new(&self.transaction).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1171 hash_to_message!(sighash)
1174 /// Signs the counterparty's commitment transaction.
1175 pub fn sign_counterparty_commitment<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1176 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1177 sign(secp_ctx, &sighash, funding_key)
1180 /// Signs the holder commitment transaction because we are about to broadcast it.
1181 pub fn sign_holder_commitment<T: secp256k1::Signing, ES: Deref>(
1182 &self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64,
1183 entropy_source: &ES, secp_ctx: &Secp256k1<T>
1184 ) -> Signature where ES::Target: EntropySource {
1185 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1186 sign_with_aux_rand(secp_ctx, &sighash, funding_key, entropy_source)
1190 /// This class tracks the per-transaction information needed to build a closing transaction and will
1191 /// actually build it and sign.
1193 /// This class can be used inside a signer implementation to generate a signature given the relevant
1195 #[derive(Clone, Hash, PartialEq, Eq)]
1196 pub struct ClosingTransaction {
1197 to_holder_value_sat: u64,
1198 to_counterparty_value_sat: u64,
1199 to_holder_script: ScriptBuf,
1200 to_counterparty_script: ScriptBuf,
1204 impl ClosingTransaction {
1205 /// Construct an object of the class
1207 to_holder_value_sat: u64,
1208 to_counterparty_value_sat: u64,
1209 to_holder_script: ScriptBuf,
1210 to_counterparty_script: ScriptBuf,
1211 funding_outpoint: OutPoint,
1213 let built = build_closing_transaction(
1214 to_holder_value_sat, to_counterparty_value_sat,
1215 to_holder_script.clone(), to_counterparty_script.clone(),
1218 ClosingTransaction {
1219 to_holder_value_sat,
1220 to_counterparty_value_sat,
1222 to_counterparty_script,
1227 /// Trust our pre-built transaction.
1229 /// Applies a wrapper which allows access to the transaction.
1231 /// This should only be used if you fully trust the builder of this object. It should not
1232 /// be used by an external signer - instead use the verify function.
1233 pub fn trust(&self) -> TrustedClosingTransaction {
1234 TrustedClosingTransaction { inner: self }
1237 /// Verify our pre-built transaction.
1239 /// Applies a wrapper which allows access to the transaction.
1241 /// An external validating signer must call this method before signing
1242 /// or using the built transaction.
1243 pub fn verify(&self, funding_outpoint: OutPoint) -> Result<TrustedClosingTransaction, ()> {
1244 let built = build_closing_transaction(
1245 self.to_holder_value_sat, self.to_counterparty_value_sat,
1246 self.to_holder_script.clone(), self.to_counterparty_script.clone(),
1249 if self.built != built {
1252 Ok(TrustedClosingTransaction { inner: self })
1255 /// The value to be sent to the holder, or zero if the output will be omitted
1256 pub fn to_holder_value_sat(&self) -> u64 {
1257 self.to_holder_value_sat
1260 /// The value to be sent to the counterparty, or zero if the output will be omitted
1261 pub fn to_counterparty_value_sat(&self) -> u64 {
1262 self.to_counterparty_value_sat
1265 /// The destination of the holder's output
1266 pub fn to_holder_script(&self) -> &Script {
1267 &self.to_holder_script
1270 /// The destination of the counterparty's output
1271 pub fn to_counterparty_script(&self) -> &Script {
1272 &self.to_counterparty_script
1276 /// A wrapper on ClosingTransaction indicating that the built bitcoin
1277 /// transaction is trusted.
1279 /// See trust() and verify() functions on CommitmentTransaction.
1281 /// This structure implements Deref.
1282 pub struct TrustedClosingTransaction<'a> {
1283 inner: &'a ClosingTransaction,
1286 impl<'a> Deref for TrustedClosingTransaction<'a> {
1287 type Target = ClosingTransaction;
1289 fn deref(&self) -> &Self::Target { self.inner }
1292 impl<'a> TrustedClosingTransaction<'a> {
1293 /// The pre-built Bitcoin commitment transaction
1294 pub fn built_transaction(&self) -> &'a Transaction {
1298 /// Get the SIGHASH_ALL sighash value of the transaction.
1300 /// This can be used to verify a signature.
1301 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1302 let sighash = &sighash::SighashCache::new(&self.inner.built).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1303 hash_to_message!(sighash)
1306 /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1307 /// because we are about to broadcast a holder transaction.
1308 pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1309 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1310 sign(secp_ctx, &sighash, funding_key)
1314 /// This class tracks the per-transaction information needed to build a commitment transaction and will
1315 /// actually build it and sign. It is used for holder transactions that we sign only when needed
1316 /// and for transactions we sign for the counterparty.
1318 /// This class can be used inside a signer implementation to generate a signature given the relevant
1320 #[derive(Clone, Debug)]
1321 pub struct CommitmentTransaction {
1322 commitment_number: u64,
1323 to_broadcaster_value_sat: u64,
1324 to_countersignatory_value_sat: u64,
1325 to_broadcaster_delay: Option<u16>, // Added in 0.0.117
1326 feerate_per_kw: u32,
1327 htlcs: Vec<HTLCOutputInCommitment>,
1328 // Note that on upgrades, some features of existing outputs may be missed.
1329 channel_type_features: ChannelTypeFeatures,
1330 // A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
1331 keys: TxCreationKeys,
1332 // For access to the pre-built transaction, see doc for trust()
1333 built: BuiltCommitmentTransaction,
1336 impl Eq for CommitmentTransaction {}
1337 impl PartialEq for CommitmentTransaction {
1338 fn eq(&self, o: &Self) -> bool {
1339 let eq = self.commitment_number == o.commitment_number &&
1340 self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
1341 self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
1342 self.feerate_per_kw == o.feerate_per_kw &&
1343 self.htlcs == o.htlcs &&
1344 self.channel_type_features == o.channel_type_features &&
1345 self.keys == o.keys;
1347 debug_assert_eq!(self.built.transaction, o.built.transaction);
1348 debug_assert_eq!(self.built.txid, o.built.txid);
1354 impl Writeable for CommitmentTransaction {
1355 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1356 let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
1357 write_tlv_fields!(writer, {
1358 (0, self.commitment_number, required),
1359 (1, self.to_broadcaster_delay, option),
1360 (2, self.to_broadcaster_value_sat, required),
1361 (4, self.to_countersignatory_value_sat, required),
1362 (6, self.feerate_per_kw, required),
1363 (8, self.keys, required),
1364 (10, self.built, required),
1365 (12, self.htlcs, required_vec),
1366 (14, legacy_deserialization_prevention_marker, option),
1367 (15, self.channel_type_features, required),
1373 impl Readable for CommitmentTransaction {
1374 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1375 _init_and_read_len_prefixed_tlv_fields!(reader, {
1376 (0, commitment_number, required),
1377 (1, to_broadcaster_delay, option),
1378 (2, to_broadcaster_value_sat, required),
1379 (4, to_countersignatory_value_sat, required),
1380 (6, feerate_per_kw, required),
1381 (8, keys, required),
1382 (10, built, required),
1383 (12, htlcs, required_vec),
1384 (14, _legacy_deserialization_prevention_marker, option),
1385 (15, channel_type_features, option),
1388 let mut additional_features = ChannelTypeFeatures::empty();
1389 additional_features.set_anchors_nonzero_fee_htlc_tx_required();
1390 chain::package::verify_channel_type_features(&channel_type_features, Some(&additional_features))?;
1393 commitment_number: commitment_number.0.unwrap(),
1394 to_broadcaster_value_sat: to_broadcaster_value_sat.0.unwrap(),
1395 to_countersignatory_value_sat: to_countersignatory_value_sat.0.unwrap(),
1396 to_broadcaster_delay,
1397 feerate_per_kw: feerate_per_kw.0.unwrap(),
1398 keys: keys.0.unwrap(),
1399 built: built.0.unwrap(),
1401 channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
1406 impl CommitmentTransaction {
1407 /// Construct an object of the class while assigning transaction output indices to HTLCs.
1409 /// Populates HTLCOutputInCommitment.transaction_output_index in htlcs_with_aux.
1411 /// The generic T allows the caller to match the HTLC output index with auxiliary data.
1412 /// This auxiliary data is not stored in this object.
1414 /// Only include HTLCs that are above the dust limit for the channel.
1416 /// This is not exported to bindings users due to the generic though we likely should expose a version without
1417 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 {
1418 // Sort outputs and populate output indices while keeping track of the auxiliary data
1419 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();
1421 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
1422 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1423 let txid = transaction.txid();
1424 CommitmentTransaction {
1426 to_broadcaster_value_sat,
1427 to_countersignatory_value_sat,
1428 to_broadcaster_delay: Some(channel_parameters.contest_delay()),
1431 channel_type_features: channel_parameters.channel_type_features().clone(),
1433 built: BuiltCommitmentTransaction {
1440 /// Use non-zero fee anchors
1442 /// This is not exported to bindings users due to move, and also not likely to be useful for binding users
1443 pub fn with_non_zero_fee_anchors(mut self) -> Self {
1444 self.channel_type_features.set_anchors_nonzero_fee_htlc_tx_required();
1448 fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<BuiltCommitmentTransaction, ()> {
1449 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
1451 let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
1452 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)?;
1454 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1455 let txid = transaction.txid();
1456 let built_transaction = BuiltCommitmentTransaction {
1460 Ok(built_transaction)
1463 fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
1466 lock_time: LockTime::from_consensus(((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32)),
1472 // This is used in two cases:
1473 // - initial sorting of outputs / HTLCs in the constructor, in which case T is auxiliary data the
1474 // caller needs to have sorted together with the HTLCs so it can keep track of the output index
1475 // - building of a bitcoin transaction during a verify() call, in which case T is just ()
1476 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>), ()> {
1477 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1478 let contest_delay = channel_parameters.contest_delay();
1480 let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
1482 if to_countersignatory_value_sat > 0 {
1483 let script = if channel_parameters.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
1484 get_to_countersignatory_with_anchors_redeemscript(&countersignatory_pubkeys.payment_point).to_v0_p2wsh()
1486 Payload::p2wpkh(&BitcoinPublicKey::new(countersignatory_pubkeys.payment_point)).unwrap().script_pubkey()
1490 script_pubkey: script.clone(),
1491 value: to_countersignatory_value_sat,
1497 if to_broadcaster_value_sat > 0 {
1498 let redeem_script = get_revokeable_redeemscript(
1499 &keys.revocation_key,
1501 &keys.broadcaster_delayed_payment_key,
1505 script_pubkey: redeem_script.to_v0_p2wsh(),
1506 value: to_broadcaster_value_sat,
1512 if channel_parameters.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
1513 if to_broadcaster_value_sat > 0 || !htlcs_with_aux.is_empty() {
1514 let anchor_script = get_anchor_redeemscript(broadcaster_funding_key);
1517 script_pubkey: anchor_script.to_v0_p2wsh(),
1518 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1524 if to_countersignatory_value_sat > 0 || !htlcs_with_aux.is_empty() {
1525 let anchor_script = get_anchor_redeemscript(countersignatory_funding_key);
1528 script_pubkey: anchor_script.to_v0_p2wsh(),
1529 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1536 let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
1537 for (htlc, _) in htlcs_with_aux {
1538 let script = chan_utils::get_htlc_redeemscript(&htlc, &channel_parameters.channel_type_features(), &keys);
1540 script_pubkey: script.to_v0_p2wsh(),
1541 value: htlc.amount_msat / 1000,
1543 txouts.push((txout, Some(htlc)));
1546 // Sort output in BIP-69 order (amount, scriptPubkey). Tie-breaks based on HTLC
1547 // CLTV expiration height.
1548 sort_outputs(&mut txouts, |a, b| {
1549 if let &Some(ref a_htlcout) = a {
1550 if let &Some(ref b_htlcout) = b {
1551 a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
1552 // Note that due to hash collisions, we have to have a fallback comparison
1553 // here for fuzzing mode (otherwise at least chanmon_fail_consistency
1555 .then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
1556 // For non-HTLC outputs, if they're copying our SPK we don't really care if we
1557 // close the channel due to mismatches - they're doing something dumb:
1558 } else { cmp::Ordering::Equal }
1559 } else { cmp::Ordering::Equal }
1562 let mut outputs = Vec::with_capacity(txouts.len());
1563 for (idx, out) in txouts.drain(..).enumerate() {
1564 if let Some(htlc) = out.1 {
1565 htlc.transaction_output_index = Some(idx as u32);
1566 htlcs.push(htlc.clone());
1568 outputs.push(out.0);
1570 Ok((outputs, htlcs))
1573 fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
1574 let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
1575 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1576 let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
1577 &broadcaster_pubkeys.payment_point,
1578 &countersignatory_pubkeys.payment_point,
1579 channel_parameters.is_outbound(),
1582 let obscured_commitment_transaction_number =
1583 commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
1586 let mut ins: Vec<TxIn> = Vec::new();
1588 previous_output: channel_parameters.funding_outpoint(),
1589 script_sig: ScriptBuf::new(),
1590 sequence: Sequence(((0x80 as u32) << 8 * 3)
1591 | ((obscured_commitment_transaction_number >> 3 * 8) as u32)),
1592 witness: Witness::new(),
1596 (obscured_commitment_transaction_number, txins)
1599 /// The backwards-counting commitment number
1600 pub fn commitment_number(&self) -> u64 {
1601 self.commitment_number
1604 /// The per commitment point used by the broadcaster.
1605 pub fn per_commitment_point(&self) -> PublicKey {
1606 self.keys.per_commitment_point
1609 /// The value to be sent to the broadcaster
1610 pub fn to_broadcaster_value_sat(&self) -> u64 {
1611 self.to_broadcaster_value_sat
1614 /// The value to be sent to the counterparty
1615 pub fn to_countersignatory_value_sat(&self) -> u64 {
1616 self.to_countersignatory_value_sat
1619 /// The feerate paid per 1000-weight-unit in this commitment transaction.
1620 pub fn feerate_per_kw(&self) -> u32 {
1624 /// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
1625 /// which were included in this commitment transaction in output order.
1626 /// The transaction index is always populated.
1628 /// This is not exported to bindings users as we cannot currently convert Vec references to/from C, though we should
1629 /// expose a less effecient version which creates a Vec of references in the future.
1630 pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
1634 /// Trust our pre-built transaction and derived transaction creation public keys.
1636 /// Applies a wrapper which allows access to these fields.
1638 /// This should only be used if you fully trust the builder of this object. It should not
1639 /// be used by an external signer - instead use the verify function.
1640 pub fn trust(&self) -> TrustedCommitmentTransaction {
1641 TrustedCommitmentTransaction { inner: self }
1644 /// Verify our pre-built transaction and derived transaction creation public keys.
1646 /// Applies a wrapper which allows access to these fields.
1648 /// An external validating signer must call this method before signing
1649 /// or using the built transaction.
1650 pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
1651 // This is the only field of the key cache that we trust
1652 let per_commitment_point = self.keys.per_commitment_point;
1653 let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx);
1654 if keys != self.keys {
1657 let tx = self.internal_rebuild_transaction(&keys, channel_parameters, &broadcaster_keys.funding_pubkey, &countersignatory_keys.funding_pubkey)?;
1658 if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
1661 Ok(TrustedCommitmentTransaction { inner: self })
1665 /// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
1666 /// transaction and the transaction creation keys) are trusted.
1668 /// See trust() and verify() functions on CommitmentTransaction.
1670 /// This structure implements Deref.
1671 pub struct TrustedCommitmentTransaction<'a> {
1672 inner: &'a CommitmentTransaction,
1675 impl<'a> Deref for TrustedCommitmentTransaction<'a> {
1676 type Target = CommitmentTransaction;
1678 fn deref(&self) -> &Self::Target { self.inner }
1681 impl<'a> TrustedCommitmentTransaction<'a> {
1682 /// The transaction ID of the built Bitcoin transaction
1683 pub fn txid(&self) -> Txid {
1684 self.inner.built.txid
1687 /// The pre-built Bitcoin commitment transaction
1688 pub fn built_transaction(&self) -> &'a BuiltCommitmentTransaction {
1692 /// The pre-calculated transaction creation public keys.
1693 pub fn keys(&self) -> &'a TxCreationKeys {
1697 /// Should anchors be used.
1698 pub fn channel_type_features(&self) -> &'a ChannelTypeFeatures {
1699 &self.inner.channel_type_features
1702 /// Get a signature for each HTLC which was included in the commitment transaction (ie for
1703 /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
1705 /// The returned Vec has one entry for each HTLC, and in the same order.
1707 /// This function is only valid in the holder commitment context, it always uses EcdsaSighashType::All.
1708 pub fn get_htlc_sigs<T: secp256k1::Signing, ES: Deref>(
1709 &self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters,
1710 entropy_source: &ES, secp_ctx: &Secp256k1<T>,
1711 ) -> Result<Vec<Signature>, ()> where ES::Target: EntropySource {
1712 let inner = self.inner;
1713 let keys = &inner.keys;
1714 let txid = inner.built.txid;
1715 let mut ret = Vec::with_capacity(inner.htlcs.len());
1716 let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key);
1718 for this_htlc in inner.htlcs.iter() {
1719 assert!(this_htlc.transaction_output_index.is_some());
1720 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);
1722 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);
1724 let sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, EcdsaSighashType::All).unwrap()[..]);
1725 ret.push(sign_with_aux_rand(secp_ctx, &sighash, &holder_htlc_key, entropy_source));
1730 /// Builds the second-level holder HTLC transaction for the HTLC with index `htlc_index`.
1731 pub(crate) fn build_unsigned_htlc_tx(
1732 &self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize,
1733 preimage: &Option<PaymentPreimage>,
1735 let keys = &self.inner.keys;
1736 let this_htlc = &self.inner.htlcs[htlc_index];
1737 assert!(this_htlc.transaction_output_index.is_some());
1738 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
1739 if !this_htlc.offered && preimage.is_none() { unreachable!(); }
1740 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
1741 if this_htlc.offered && preimage.is_some() { unreachable!(); }
1743 build_htlc_transaction(
1744 &self.inner.built.txid, self.inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc,
1745 &self.channel_type_features, &keys.broadcaster_delayed_payment_key, &keys.revocation_key
1750 /// Builds the witness required to spend the input for the HTLC with index `htlc_index` in a
1751 /// second-level holder HTLC transaction.
1752 pub(crate) fn build_htlc_input_witness(
1753 &self, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature,
1754 preimage: &Option<PaymentPreimage>
1756 let keys = &self.inner.keys;
1757 let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(
1758 &self.inner.htlcs[htlc_index], &self.channel_type_features, &keys.broadcaster_htlc_key,
1759 &keys.countersignatory_htlc_key, &keys.revocation_key
1761 chan_utils::build_htlc_input_witness(
1762 signature, counterparty_signature, preimage, &htlc_redeemscript, &self.channel_type_features,
1766 /// Returns the index of the revokeable output, i.e. the `to_local` output sending funds to
1767 /// the broadcaster, in the built transaction, if any exists.
1769 /// There are two cases where this may return `None`:
1770 /// - The balance of the revokeable output is below the dust limit (only found on commitments
1771 /// early in the channel's lifetime, i.e. before the channel reserve is met).
1772 /// - This commitment was created before LDK 0.0.117. In this case, the
1773 /// commitment transaction previously didn't contain enough information to locate the
1774 /// revokeable output.
1775 pub fn revokeable_output_index(&self) -> Option<usize> {
1776 let revokeable_redeemscript = get_revokeable_redeemscript(
1777 &self.keys.revocation_key,
1778 self.to_broadcaster_delay?,
1779 &self.keys.broadcaster_delayed_payment_key,
1781 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1782 let outputs = &self.inner.built.transaction.output;
1783 outputs.iter().enumerate()
1784 .find(|(_, out)| out.script_pubkey == revokeable_p2wsh)
1785 .map(|(idx, _)| idx)
1788 /// Helper method to build an unsigned justice transaction spending the revokeable
1789 /// `to_local` output to a destination script. Fee estimation accounts for the expected
1790 /// revocation witness data that will be added when signed.
1792 /// This method will error if the given fee rate results in a fee greater than the value
1793 /// of the output being spent, or if there exists no revokeable `to_local` output on this
1794 /// commitment transaction. See [`Self::revokeable_output_index`] for more details.
1796 /// The built transaction will allow fee bumping with RBF, and this method takes
1797 /// `feerate_per_kw` as an input such that multiple copies of a justice transaction at different
1798 /// fee rates may be built.
1799 pub fn build_to_local_justice_tx(&self, feerate_per_kw: u64, destination_script: ScriptBuf)
1800 -> Result<Transaction, ()> {
1801 let output_idx = self.revokeable_output_index().ok_or(())?;
1802 let input = vec![TxIn {
1803 previous_output: OutPoint {
1804 txid: self.trust().txid(),
1805 vout: output_idx as u32,
1807 script_sig: ScriptBuf::new(),
1808 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
1809 witness: Witness::new(),
1811 let value = self.inner.built.transaction.output[output_idx].value;
1812 let output = vec![TxOut {
1813 script_pubkey: destination_script,
1816 let mut justice_tx = Transaction {
1818 lock_time: LockTime::ZERO,
1822 let weight = justice_tx.weight().to_wu() + WEIGHT_REVOKED_OUTPUT;
1823 let fee = fee_for_weight(feerate_per_kw as u32, weight);
1824 justice_tx.output[0].value = value.checked_sub(fee).ok_or(())?;
1830 /// Commitment transaction numbers which appear in the transactions themselves are XOR'd with a
1831 /// shared secret first. This prevents on-chain observers from discovering how many commitment
1832 /// transactions occurred in a channel before it was closed.
1834 /// This function gets the shared secret from relevant channel public keys and can be used to
1835 /// "decrypt" the commitment transaction number given a commitment transaction on-chain.
1836 pub fn get_commitment_transaction_number_obscure_factor(
1837 broadcaster_payment_basepoint: &PublicKey,
1838 countersignatory_payment_basepoint: &PublicKey,
1839 outbound_from_broadcaster: bool,
1841 let mut sha = Sha256::engine();
1843 if outbound_from_broadcaster {
1844 sha.input(&broadcaster_payment_basepoint.serialize());
1845 sha.input(&countersignatory_payment_basepoint.serialize());
1847 sha.input(&countersignatory_payment_basepoint.serialize());
1848 sha.input(&broadcaster_payment_basepoint.serialize());
1850 let res = Sha256::from_engine(sha).to_byte_array();
1852 ((res[26] as u64) << 5 * 8)
1853 | ((res[27] as u64) << 4 * 8)
1854 | ((res[28] as u64) << 3 * 8)
1855 | ((res[29] as u64) << 2 * 8)
1856 | ((res[30] as u64) << 1 * 8)
1857 | ((res[31] as u64) << 0 * 8)
1862 use super::{CounterpartyCommitmentSecrets, ChannelPublicKeys};
1864 use crate::prelude::*;
1865 use crate::ln::chan_utils::{get_htlc_redeemscript, get_to_countersignatory_with_anchors_redeemscript, CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
1866 use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
1867 use crate::util::test_utils;
1868 use crate::sign::{ChannelSigner, SignerProvider};
1869 use bitcoin::{Network, Txid, ScriptBuf};
1870 use bitcoin::hashes::Hash;
1871 use bitcoin::hashes::hex::FromHex;
1872 use crate::ln::PaymentHash;
1873 use bitcoin::address::Payload;
1874 use bitcoin::PublicKey as BitcoinPublicKey;
1875 use crate::ln::features::ChannelTypeFeatures;
1877 struct TestCommitmentTxBuilder {
1878 commitment_number: u64,
1879 holder_funding_pubkey: PublicKey,
1880 counterparty_funding_pubkey: PublicKey,
1881 keys: TxCreationKeys,
1882 feerate_per_kw: u32,
1883 htlcs_with_aux: Vec<(HTLCOutputInCommitment, ())>,
1884 channel_parameters: ChannelTransactionParameters,
1885 counterparty_pubkeys: ChannelPublicKeys,
1888 impl TestCommitmentTxBuilder {
1890 let secp_ctx = Secp256k1::new();
1891 let seed = [42; 32];
1892 let network = Network::Testnet;
1893 let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
1894 let signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(false, 1_000_000, 0));
1895 let counterparty_signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(true, 1_000_000, 1));
1896 let delayed_payment_base = &signer.pubkeys().delayed_payment_basepoint;
1897 let per_commitment_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
1898 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
1899 let htlc_basepoint = &signer.pubkeys().htlc_basepoint;
1900 let holder_pubkeys = signer.pubkeys();
1901 let counterparty_pubkeys = counterparty_signer.pubkeys().clone();
1902 let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint);
1903 let channel_parameters = ChannelTransactionParameters {
1904 holder_pubkeys: holder_pubkeys.clone(),
1905 holder_selected_contest_delay: 0,
1906 is_outbound_from_holder: false,
1907 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: counterparty_pubkeys.clone(), selected_contest_delay: 0 }),
1908 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1909 channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
1911 let htlcs_with_aux = Vec::new();
1914 commitment_number: 0,
1915 holder_funding_pubkey: holder_pubkeys.funding_pubkey,
1916 counterparty_funding_pubkey: counterparty_pubkeys.funding_pubkey,
1921 counterparty_pubkeys,
1925 fn build(&mut self, to_broadcaster_sats: u64, to_countersignatory_sats: u64) -> CommitmentTransaction {
1926 CommitmentTransaction::new_with_auxiliary_htlc_data(
1927 self.commitment_number, to_broadcaster_sats, to_countersignatory_sats,
1928 self.holder_funding_pubkey.clone(),
1929 self.counterparty_funding_pubkey.clone(),
1930 self.keys.clone(), self.feerate_per_kw,
1931 &mut self.htlcs_with_aux, &self.channel_parameters.as_holder_broadcastable()
1938 let mut builder = TestCommitmentTxBuilder::new();
1940 // Generate broadcaster and counterparty outputs
1941 let tx = builder.build(1000, 2000);
1942 assert_eq!(tx.built.transaction.output.len(), 2);
1943 assert_eq!(tx.built.transaction.output[1].script_pubkey, Payload::p2wpkh(&BitcoinPublicKey::new(builder.counterparty_pubkeys.payment_point)).unwrap().script_pubkey());
1945 // Generate broadcaster and counterparty outputs as well as two anchors
1946 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
1947 let tx = builder.build(1000, 2000);
1948 assert_eq!(tx.built.transaction.output.len(), 4);
1949 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_to_countersignatory_with_anchors_redeemscript(&builder.counterparty_pubkeys.payment_point).to_v0_p2wsh());
1951 // Generate broadcaster output and anchor
1952 let tx = builder.build(3000, 0);
1953 assert_eq!(tx.built.transaction.output.len(), 2);
1955 // Generate counterparty output and anchor
1956 let tx = builder.build(0, 3000);
1957 assert_eq!(tx.built.transaction.output.len(), 2);
1959 let received_htlc = HTLCOutputInCommitment {
1961 amount_msat: 400000,
1963 payment_hash: PaymentHash([42; 32]),
1964 transaction_output_index: None,
1967 let offered_htlc = HTLCOutputInCommitment {
1969 amount_msat: 600000,
1971 payment_hash: PaymentHash([43; 32]),
1972 transaction_output_index: None,
1975 // Generate broadcaster output and received and offered HTLC outputs, w/o anchors
1976 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1977 builder.htlcs_with_aux = vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())];
1978 let tx = builder.build(3000, 0);
1979 let keys = &builder.keys.clone();
1980 assert_eq!(tx.built.transaction.output.len(), 3);
1981 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh());
1982 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh());
1983 assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh().to_hex_string(),
1984 "0020e43a7c068553003fe68fcae424fb7b28ec5ce48cd8b6744b3945631389bad2fb");
1985 assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh().to_hex_string(),
1986 "0020215d61bba56b19e9eadb6107f5a85d7f99c40f65992443f69229c290165bc00d");
1988 // Generate broadcaster output and received and offered HTLC outputs, with anchors
1989 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
1990 builder.htlcs_with_aux = vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())];
1991 let tx = builder.build(3000, 0);
1992 assert_eq!(tx.built.transaction.output.len(), 5);
1993 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());
1994 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());
1995 assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_v0_p2wsh().to_hex_string(),
1996 "0020b70d0649c72b38756885c7a30908d912a7898dd5d79457a7280b8e9a20f3f2bc");
1997 assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_v0_p2wsh().to_hex_string(),
1998 "002087a3faeb1950a469c0e2db4a79b093a41b9526e5a6fc6ef5cb949bde3be379c7");
2002 fn test_finding_revokeable_output_index() {
2003 let mut builder = TestCommitmentTxBuilder::new();
2005 // Revokeable output present
2006 let tx = builder.build(1000, 2000);
2007 assert_eq!(tx.built.transaction.output.len(), 2);
2008 assert_eq!(tx.trust().revokeable_output_index(), Some(0));
2010 // Revokeable output present (but to_broadcaster_delay missing)
2011 let tx = CommitmentTransaction { to_broadcaster_delay: None, ..tx };
2012 assert_eq!(tx.built.transaction.output.len(), 2);
2013 assert_eq!(tx.trust().revokeable_output_index(), None);
2015 // Revokeable output not present (our balance is dust)
2016 let tx = builder.build(0, 2000);
2017 assert_eq!(tx.built.transaction.output.len(), 1);
2018 assert_eq!(tx.trust().revokeable_output_index(), None);
2022 fn test_building_to_local_justice_tx() {
2023 let mut builder = TestCommitmentTxBuilder::new();
2025 // Revokeable output not present (our balance is dust)
2026 let tx = builder.build(0, 2000);
2027 assert_eq!(tx.built.transaction.output.len(), 1);
2028 assert!(tx.trust().build_to_local_justice_tx(253, ScriptBuf::new()).is_err());
2030 // Revokeable output present
2031 let tx = builder.build(1000, 2000);
2032 assert_eq!(tx.built.transaction.output.len(), 2);
2035 assert!(tx.trust().build_to_local_justice_tx(100_000, ScriptBuf::new()).is_err());
2037 // Generate a random public key for destination script
2038 let secret_key = SecretKey::from_slice(
2039 &<Vec<u8>>::from_hex("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100")
2040 .unwrap()[..]).unwrap();
2041 let pubkey_hash = BitcoinPublicKey::new(
2042 PublicKey::from_secret_key(&Secp256k1::new(), &secret_key)).wpubkey_hash().unwrap();
2043 let destination_script = ScriptBuf::new_v0_p2wpkh(&pubkey_hash);
2045 let justice_tx = tx.trust().build_to_local_justice_tx(253, destination_script.clone()).unwrap();
2046 assert_eq!(justice_tx.input.len(), 1);
2047 assert_eq!(justice_tx.input[0].previous_output.txid, tx.built.transaction.txid());
2048 assert_eq!(justice_tx.input[0].previous_output.vout, tx.trust().revokeable_output_index().unwrap() as u32);
2049 assert!(justice_tx.input[0].sequence.is_rbf());
2051 assert_eq!(justice_tx.output.len(), 1);
2052 assert!(justice_tx.output[0].value < 1000);
2053 assert_eq!(justice_tx.output[0].script_pubkey, destination_script);
2057 fn test_per_commitment_storage() {
2058 // Test vectors from BOLT 3:
2059 let mut secrets: Vec<[u8; 32]> = Vec::new();
2062 macro_rules! test_secrets {
2064 let mut idx = 281474976710655;
2065 for secret in secrets.iter() {
2066 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
2069 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
2070 assert!(monitor.get_secret(idx).is_none());
2075 // insert_secret correct sequence
2076 monitor = CounterpartyCommitmentSecrets::new();
2079 secrets.push([0; 32]);
2080 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2081 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2084 secrets.push([0; 32]);
2085 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2086 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2089 secrets.push([0; 32]);
2090 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2091 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2094 secrets.push([0; 32]);
2095 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2096 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2099 secrets.push([0; 32]);
2100 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2101 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2104 secrets.push([0; 32]);
2105 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2106 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2109 secrets.push([0; 32]);
2110 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2111 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2114 secrets.push([0; 32]);
2115 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2116 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
2121 // insert_secret #1 incorrect
2122 monitor = CounterpartyCommitmentSecrets::new();
2125 secrets.push([0; 32]);
2126 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2127 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2130 secrets.push([0; 32]);
2131 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2132 assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
2136 // insert_secret #2 incorrect (#1 derived from incorrect)
2137 monitor = CounterpartyCommitmentSecrets::new();
2140 secrets.push([0; 32]);
2141 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2142 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2145 secrets.push([0; 32]);
2146 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2147 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2150 secrets.push([0; 32]);
2151 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2152 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2155 secrets.push([0; 32]);
2156 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2157 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
2161 // insert_secret #3 incorrect
2162 monitor = CounterpartyCommitmentSecrets::new();
2165 secrets.push([0; 32]);
2166 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2167 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2170 secrets.push([0; 32]);
2171 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2172 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2175 secrets.push([0; 32]);
2176 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2177 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2180 secrets.push([0; 32]);
2181 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2182 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
2186 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
2187 monitor = CounterpartyCommitmentSecrets::new();
2190 secrets.push([0; 32]);
2191 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2192 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2195 secrets.push([0; 32]);
2196 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2197 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2200 secrets.push([0; 32]);
2201 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2202 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2205 secrets.push([0; 32]);
2206 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
2207 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2210 secrets.push([0; 32]);
2211 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2212 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2215 secrets.push([0; 32]);
2216 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2217 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2220 secrets.push([0; 32]);
2221 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2222 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2225 secrets.push([0; 32]);
2226 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2227 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2231 // insert_secret #5 incorrect
2232 monitor = CounterpartyCommitmentSecrets::new();
2235 secrets.push([0; 32]);
2236 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2237 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2240 secrets.push([0; 32]);
2241 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2242 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2245 secrets.push([0; 32]);
2246 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2247 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2250 secrets.push([0; 32]);
2251 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2252 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2255 secrets.push([0; 32]);
2256 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2257 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2260 secrets.push([0; 32]);
2261 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2262 assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
2266 // insert_secret #6 incorrect (5 derived from incorrect)
2267 monitor = CounterpartyCommitmentSecrets::new();
2270 secrets.push([0; 32]);
2271 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2272 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2275 secrets.push([0; 32]);
2276 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2277 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2280 secrets.push([0; 32]);
2281 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2282 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2285 secrets.push([0; 32]);
2286 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2287 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2290 secrets.push([0; 32]);
2291 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2292 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2295 secrets.push([0; 32]);
2296 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
2297 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2300 secrets.push([0; 32]);
2301 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2302 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2305 secrets.push([0; 32]);
2306 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2307 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2311 // insert_secret #7 incorrect
2312 monitor = CounterpartyCommitmentSecrets::new();
2315 secrets.push([0; 32]);
2316 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2317 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2320 secrets.push([0; 32]);
2321 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2322 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2325 secrets.push([0; 32]);
2326 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2327 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2330 secrets.push([0; 32]);
2331 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2332 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2335 secrets.push([0; 32]);
2336 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2337 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2340 secrets.push([0; 32]);
2341 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2342 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2345 secrets.push([0; 32]);
2346 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2347 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2350 secrets.push([0; 32]);
2351 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2352 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2356 // insert_secret #8 incorrect
2357 monitor = CounterpartyCommitmentSecrets::new();
2360 secrets.push([0; 32]);
2361 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2362 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2365 secrets.push([0; 32]);
2366 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2367 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2370 secrets.push([0; 32]);
2371 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2372 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2375 secrets.push([0; 32]);
2376 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2377 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2380 secrets.push([0; 32]);
2381 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2382 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2385 secrets.push([0; 32]);
2386 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2387 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2390 secrets.push([0; 32]);
2391 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2392 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2395 secrets.push([0; 32]);
2396 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2397 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());