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,Builder};
14 use bitcoin::blockdata::opcodes;
15 use bitcoin::blockdata::transaction::{TxIn,TxOut,OutPoint,Transaction, EcdsaSighashType};
16 use bitcoin::util::sighash;
17 use bitcoin::util::address::Payload;
19 use bitcoin::hashes::{Hash, HashEngine};
20 use bitcoin::hashes::sha256::Hash as Sha256;
21 use bitcoin::hashes::ripemd160::Hash as Ripemd160;
22 use bitcoin::hash_types::{Txid, PubkeyHash};
24 use crate::chain::chaininterface::fee_for_weight;
25 use crate::chain::package::WEIGHT_REVOKED_OUTPUT;
26 use crate::sign::EntropySource;
27 use crate::ln::{PaymentHash, PaymentPreimage};
28 use crate::ln::msgs::DecodeError;
29 use crate::util::ser::{Readable, RequiredWrapper, Writeable, Writer};
30 use crate::util::transaction_utils;
32 use bitcoin::secp256k1::{SecretKey, PublicKey, Scalar};
33 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature, Message};
34 use bitcoin::{PackedLockTime, secp256k1, Sequence, Witness};
35 use bitcoin::PublicKey as BitcoinPublicKey;
38 use crate::prelude::*;
40 use crate::ln::chan_utils;
41 use crate::util::transaction_utils::sort_outputs;
42 use crate::ln::channel::{INITIAL_COMMITMENT_NUMBER, ANCHOR_OUTPUT_VALUE_SATOSHI};
45 use crate::ln::features::ChannelTypeFeatures;
46 use crate::util::crypto::{sign, sign_with_aux_rand};
48 /// Maximum number of one-way in-flight HTLC (protocol-level value).
49 pub const MAX_HTLCS: u16 = 483;
50 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, non-anchor variant.
51 pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
52 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, anchor variant.
53 pub const OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS: usize = 136;
55 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
56 /// We define a range that encompasses both its non-anchors and anchors variants.
57 pub(crate) const MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 136;
58 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
59 /// We define a range that encompasses both its non-anchors and anchors variants.
60 /// This is the maximum post-anchor value.
61 pub const MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 143;
63 /// The upper bound weight of an anchor input.
64 pub const ANCHOR_INPUT_WITNESS_WEIGHT: u64 = 116;
65 /// The upper bound weight of an HTLC timeout input from a commitment transaction with anchor
67 pub const HTLC_TIMEOUT_INPUT_ANCHOR_WITNESS_WEIGHT: u64 = 288;
68 /// The upper bound weight of an HTLC success input from a commitment transaction with anchor
70 pub const HTLC_SUCCESS_INPUT_ANCHOR_WITNESS_WEIGHT: u64 = 327;
72 /// Gets the weight for an HTLC-Success transaction.
74 pub fn htlc_success_tx_weight(channel_type_features: &ChannelTypeFeatures) -> u64 {
75 const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
76 const HTLC_SUCCESS_ANCHOR_TX_WEIGHT: u64 = 706;
77 if channel_type_features.supports_anchors_zero_fee_htlc_tx() { HTLC_SUCCESS_ANCHOR_TX_WEIGHT } else { HTLC_SUCCESS_TX_WEIGHT }
80 /// Gets the weight for an HTLC-Timeout transaction.
82 pub fn htlc_timeout_tx_weight(channel_type_features: &ChannelTypeFeatures) -> u64 {
83 const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
84 const HTLC_TIMEOUT_ANCHOR_TX_WEIGHT: u64 = 666;
85 if channel_type_features.supports_anchors_zero_fee_htlc_tx() { HTLC_TIMEOUT_ANCHOR_TX_WEIGHT } else { HTLC_TIMEOUT_TX_WEIGHT }
88 /// Describes the type of HTLC claim as determined by analyzing the witness.
89 #[derive(PartialEq, Eq)]
91 /// Claims an offered output on a commitment transaction through the timeout path.
93 /// Claims an offered output on a commitment transaction through the success path.
95 /// Claims an accepted output on a commitment transaction through the timeout path.
97 /// Claims an accepted output on a commitment transaction through the success path.
99 /// Claims an offered/accepted output on a commitment transaction through the revocation path.
104 /// Check if a given input witness attempts to claim a HTLC.
105 pub fn from_witness(witness: &Witness) -> Option<Self> {
106 debug_assert_eq!(OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS, MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT);
107 if witness.len() < 2 {
110 let witness_script = witness.last().unwrap();
111 let second_to_last = witness.second_to_last().unwrap();
112 if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT {
113 if witness.len() == 3 && second_to_last.len() == 33 {
114 // <revocation sig> <revocationpubkey> <witness_script>
115 Some(Self::Revocation)
116 } else if witness.len() == 3 && second_to_last.len() == 32 {
117 // <remotehtlcsig> <payment_preimage> <witness_script>
118 Some(Self::OfferedPreimage)
119 } else if witness.len() == 5 && second_to_last.len() == 0 {
120 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
121 Some(Self::OfferedTimeout)
125 } else if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS {
126 // It's possible for the weight of `offered_htlc_script` and `accepted_htlc_script` to
127 // match so we check for both here.
128 if witness.len() == 3 && second_to_last.len() == 33 {
129 // <revocation sig> <revocationpubkey> <witness_script>
130 Some(Self::Revocation)
131 } else if witness.len() == 3 && second_to_last.len() == 32 {
132 // <remotehtlcsig> <payment_preimage> <witness_script>
133 Some(Self::OfferedPreimage)
134 } else if witness.len() == 5 && second_to_last.len() == 0 {
135 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
136 Some(Self::OfferedTimeout)
137 } else if witness.len() == 3 && second_to_last.len() == 0 {
138 // <remotehtlcsig> <> <witness_script>
139 Some(Self::AcceptedTimeout)
140 } else if witness.len() == 5 && second_to_last.len() == 32 {
141 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
142 Some(Self::AcceptedPreimage)
146 } else if witness_script.len() > MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT &&
147 witness_script.len() <= MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT {
148 // Handle remaining range of ACCEPTED_HTLC_SCRIPT_WEIGHT.
149 if witness.len() == 3 && second_to_last.len() == 33 {
150 // <revocation sig> <revocationpubkey> <witness_script>
151 Some(Self::Revocation)
152 } else if witness.len() == 3 && second_to_last.len() == 0 {
153 // <remotehtlcsig> <> <witness_script>
154 Some(Self::AcceptedTimeout)
155 } else if witness.len() == 5 && second_to_last.len() == 32 {
156 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
157 Some(Self::AcceptedPreimage)
167 // Various functions for key derivation and transaction creation for use within channels. Primarily
168 // used in Channel and ChannelMonitor.
170 /// Build the commitment secret from the seed and the commitment number
171 pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
172 let mut res: [u8; 32] = commitment_seed.clone();
175 if idx & (1 << bitpos) == (1 << bitpos) {
176 res[bitpos / 8] ^= 1 << (bitpos & 7);
177 res = Sha256::hash(&res).into_inner();
183 /// Build a closing transaction
184 pub fn build_closing_transaction(to_holder_value_sat: u64, to_counterparty_value_sat: u64, to_holder_script: Script, to_counterparty_script: Script, funding_outpoint: OutPoint) -> Transaction {
186 let mut ins: Vec<TxIn> = Vec::new();
188 previous_output: funding_outpoint,
189 script_sig: Script::new(),
190 sequence: Sequence::MAX,
191 witness: Witness::new(),
196 let mut txouts: Vec<(TxOut, ())> = Vec::new();
198 if to_counterparty_value_sat > 0 {
200 script_pubkey: to_counterparty_script,
201 value: to_counterparty_value_sat
205 if to_holder_value_sat > 0 {
207 script_pubkey: to_holder_script,
208 value: to_holder_value_sat
212 transaction_utils::sort_outputs(&mut txouts, |_, _| { cmp::Ordering::Equal }); // Ordering doesnt matter if they used our pubkey...
214 let mut outputs: Vec<TxOut> = Vec::new();
215 for out in txouts.drain(..) {
221 lock_time: PackedLockTime::ZERO,
227 /// Implements the per-commitment secret storage scheme from
228 /// [BOLT 3](https://github.com/lightning/bolts/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
230 /// Allows us to keep track of all of the revocation secrets of our counterparty in just 50*32 bytes
233 pub struct CounterpartyCommitmentSecrets {
234 old_secrets: [([u8; 32], u64); 49],
237 impl Eq for CounterpartyCommitmentSecrets {}
238 impl PartialEq for CounterpartyCommitmentSecrets {
239 fn eq(&self, other: &Self) -> bool {
240 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
241 if secret != o_secret || idx != o_idx {
249 impl CounterpartyCommitmentSecrets {
250 /// Creates a new empty `CounterpartyCommitmentSecrets` structure.
251 pub fn new() -> Self {
252 Self { old_secrets: [([0; 32], 1 << 48); 49], }
256 fn place_secret(idx: u64) -> u8 {
258 if idx & (1 << i) == (1 << i) {
265 /// Returns the minimum index of all stored secrets. Note that indexes start
266 /// at 1 << 48 and get decremented by one for each new secret.
267 pub fn get_min_seen_secret(&self) -> u64 {
268 //TODO This can be optimized?
269 let mut min = 1 << 48;
270 for &(_, idx) in self.old_secrets.iter() {
279 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
280 let mut res: [u8; 32] = secret;
282 let bitpos = bits - 1 - i;
283 if idx & (1 << bitpos) == (1 << bitpos) {
284 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
285 res = Sha256::hash(&res).into_inner();
291 /// Inserts the `secret` at `idx`. Returns `Ok(())` if the secret
292 /// was generated in accordance with BOLT 3 and is consistent with previous secrets.
293 pub fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
294 let pos = Self::place_secret(idx);
296 let (old_secret, old_idx) = self.old_secrets[i as usize];
297 if Self::derive_secret(secret, pos, old_idx) != old_secret {
301 if self.get_min_seen_secret() <= idx {
304 self.old_secrets[pos as usize] = (secret, idx);
308 /// Returns the secret at `idx`.
309 /// Returns `None` if `idx` is < [`CounterpartyCommitmentSecrets::get_min_seen_secret`].
310 pub fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
311 for i in 0..self.old_secrets.len() {
312 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
313 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
316 assert!(idx < self.get_min_seen_secret());
321 impl Writeable for CounterpartyCommitmentSecrets {
322 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
323 for &(ref secret, ref idx) in self.old_secrets.iter() {
324 writer.write_all(secret)?;
325 writer.write_all(&idx.to_be_bytes())?;
327 write_tlv_fields!(writer, {});
331 impl Readable for CounterpartyCommitmentSecrets {
332 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
333 let mut old_secrets = [([0; 32], 1 << 48); 49];
334 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
335 *secret = Readable::read(reader)?;
336 *idx = Readable::read(reader)?;
338 read_tlv_fields!(reader, {});
339 Ok(Self { old_secrets })
343 /// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
344 /// from the base secret and the per_commitment_point.
345 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> SecretKey {
346 let mut sha = Sha256::engine();
347 sha.input(&per_commitment_point.serialize());
348 sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
349 let res = Sha256::from_engine(sha).into_inner();
351 base_secret.clone().add_tweak(&Scalar::from_be_bytes(res).unwrap())
352 .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.")
355 /// Derives a per-commitment-transaction public key (eg an htlc key or a delayed_payment key)
356 /// from the base point and the per_commitment_key. This is the public equivalent of
357 /// derive_private_key - using only public keys to derive a public key instead of private keys.
358 pub fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> PublicKey {
359 let mut sha = Sha256::engine();
360 sha.input(&per_commitment_point.serialize());
361 sha.input(&base_point.serialize());
362 let res = Sha256::from_engine(sha).into_inner();
364 let hashkey = PublicKey::from_secret_key(&secp_ctx,
365 &SecretKey::from_slice(&res).expect("Hashes should always be valid keys unless SHA-256 is broken"));
366 base_point.combine(&hashkey)
367 .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.")
370 /// Derives a per-commitment-transaction revocation key from its constituent parts.
372 /// Only the cheating participant owns a valid witness to propagate a revoked
373 /// commitment transaction, thus per_commitment_secret always come from cheater
374 /// and revocation_base_secret always come from punisher, which is the broadcaster
375 /// of the transaction spending with this key knowledge.
376 pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>,
377 per_commitment_secret: &SecretKey, countersignatory_revocation_base_secret: &SecretKey)
379 let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
380 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
382 let rev_append_commit_hash_key = {
383 let mut sha = Sha256::engine();
384 sha.input(&countersignatory_revocation_base_point.serialize());
385 sha.input(&per_commitment_point.serialize());
387 Sha256::from_engine(sha).into_inner()
389 let commit_append_rev_hash_key = {
390 let mut sha = Sha256::engine();
391 sha.input(&per_commitment_point.serialize());
392 sha.input(&countersignatory_revocation_base_point.serialize());
394 Sha256::from_engine(sha).into_inner()
397 let countersignatory_contrib = countersignatory_revocation_base_secret.clone().mul_tweak(&Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
398 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
399 let broadcaster_contrib = per_commitment_secret.clone().mul_tweak(&Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
400 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
401 countersignatory_contrib.add_tweak(&Scalar::from_be_bytes(broadcaster_contrib.secret_bytes()).unwrap())
402 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
405 /// Derives a per-commitment-transaction revocation public key from its constituent parts. This is
406 /// the public equivalend of derive_private_revocation_key - using only public keys to derive a
407 /// public key instead of private keys.
409 /// Only the cheating participant owns a valid witness to propagate a revoked
410 /// commitment transaction, thus per_commitment_point always come from cheater
411 /// and revocation_base_point always come from punisher, which is the broadcaster
412 /// of the transaction spending with this key knowledge.
414 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
415 /// generated (ie our own).
416 pub fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp256k1<T>,
417 per_commitment_point: &PublicKey, countersignatory_revocation_base_point: &PublicKey)
419 let rev_append_commit_hash_key = {
420 let mut sha = Sha256::engine();
421 sha.input(&countersignatory_revocation_base_point.serialize());
422 sha.input(&per_commitment_point.serialize());
424 Sha256::from_engine(sha).into_inner()
426 let commit_append_rev_hash_key = {
427 let mut sha = Sha256::engine();
428 sha.input(&per_commitment_point.serialize());
429 sha.input(&countersignatory_revocation_base_point.serialize());
431 Sha256::from_engine(sha).into_inner()
434 let countersignatory_contrib = countersignatory_revocation_base_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
435 .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
436 let broadcaster_contrib = per_commitment_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
437 .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
438 countersignatory_contrib.combine(&broadcaster_contrib)
439 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
442 /// The set of public keys which are used in the creation of one commitment transaction.
443 /// These are derived from the channel base keys and per-commitment data.
445 /// A broadcaster key is provided from potential broadcaster of the computed transaction.
446 /// A countersignatory key is coming from a protocol participant unable to broadcast the
449 /// These keys are assumed to be good, either because the code derived them from
450 /// channel basepoints via the new function, or they were obtained via
451 /// CommitmentTransaction.trust().keys() because we trusted the source of the
452 /// pre-calculated keys.
453 #[derive(PartialEq, Eq, Clone, Debug)]
454 pub struct TxCreationKeys {
455 /// The broadcaster's per-commitment public key which was used to derive the other keys.
456 pub per_commitment_point: PublicKey,
457 /// The revocation key which is used to allow the broadcaster of the commitment
458 /// transaction to provide their counterparty the ability to punish them if they broadcast
460 pub revocation_key: PublicKey,
461 /// Broadcaster's HTLC Key
462 pub broadcaster_htlc_key: PublicKey,
463 /// Countersignatory's HTLC Key
464 pub countersignatory_htlc_key: PublicKey,
465 /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
466 pub broadcaster_delayed_payment_key: PublicKey,
469 impl_writeable_tlv_based!(TxCreationKeys, {
470 (0, per_commitment_point, required),
471 (2, revocation_key, required),
472 (4, broadcaster_htlc_key, required),
473 (6, countersignatory_htlc_key, required),
474 (8, broadcaster_delayed_payment_key, required),
477 /// One counterparty's public keys which do not change over the life of a channel.
478 #[derive(Clone, Debug, PartialEq, Eq)]
479 pub struct ChannelPublicKeys {
480 /// The public key which is used to sign all commitment transactions, as it appears in the
481 /// on-chain channel lock-in 2-of-2 multisig output.
482 pub funding_pubkey: PublicKey,
483 /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
484 /// revocation keys. This is combined with the per-commitment-secret generated by the
485 /// counterparty to create a secret which the counterparty can reveal to revoke previous
487 pub revocation_basepoint: PublicKey,
488 /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
489 /// spendable primary channel balance on the broadcaster's commitment transaction. This key is
490 /// static across every commitment transaction.
491 pub payment_point: PublicKey,
492 /// The base point which is used (with derive_public_key) to derive a per-commitment payment
493 /// public key which receives non-HTLC-encumbered funds which are only available for spending
494 /// after some delay (or can be claimed via the revocation path).
495 pub delayed_payment_basepoint: PublicKey,
496 /// The base point which is used (with derive_public_key) to derive a per-commitment public key
497 /// which is used to encumber HTLC-in-flight outputs.
498 pub htlc_basepoint: PublicKey,
501 impl_writeable_tlv_based!(ChannelPublicKeys, {
502 (0, funding_pubkey, required),
503 (2, revocation_basepoint, required),
504 (4, payment_point, required),
505 (6, delayed_payment_basepoint, required),
506 (8, htlc_basepoint, required),
509 impl TxCreationKeys {
510 /// Create per-state keys from channel base points and the per-commitment point.
511 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
512 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 {
514 per_commitment_point: per_commitment_point.clone(),
515 revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &countersignatory_revocation_base),
516 broadcaster_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_htlc_base),
517 countersignatory_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &countersignatory_htlc_base),
518 broadcaster_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_delayed_payment_base),
522 /// Generate per-state keys from channel static keys.
523 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
524 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 {
525 TxCreationKeys::derive_new(
527 &per_commitment_point,
528 &broadcaster_keys.delayed_payment_basepoint,
529 &broadcaster_keys.htlc_basepoint,
530 &countersignatory_keys.revocation_basepoint,
531 &countersignatory_keys.htlc_basepoint,
536 /// The maximum length of a script returned by get_revokeable_redeemscript.
537 // Calculated as 6 bytes of opcodes, 1 byte push plus 2 bytes for contest_delay, and two public
538 // keys of 33 bytes (+ 1 push).
539 pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 3 + 34*2;
541 /// A script either spendable by the revocation
542 /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
543 /// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
544 pub fn get_revokeable_redeemscript(revocation_key: &PublicKey, contest_delay: u16, broadcaster_delayed_payment_key: &PublicKey) -> Script {
545 let res = Builder::new().push_opcode(opcodes::all::OP_IF)
546 .push_slice(&revocation_key.serialize())
547 .push_opcode(opcodes::all::OP_ELSE)
548 .push_int(contest_delay as i64)
549 .push_opcode(opcodes::all::OP_CSV)
550 .push_opcode(opcodes::all::OP_DROP)
551 .push_slice(&broadcaster_delayed_payment_key.serialize())
552 .push_opcode(opcodes::all::OP_ENDIF)
553 .push_opcode(opcodes::all::OP_CHECKSIG)
555 debug_assert!(res.len() <= REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH);
559 /// Information about an HTLC as it appears in a commitment transaction
560 #[derive(Clone, Debug, PartialEq, Eq)]
561 pub struct HTLCOutputInCommitment {
562 /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
563 /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
564 /// need to compare this value to whether the commitment transaction in question is that of
565 /// the counterparty or our own.
567 /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
568 /// this divided by 1000.
569 pub amount_msat: u64,
570 /// The CLTV lock-time at which this HTLC expires.
571 pub cltv_expiry: u32,
572 /// The hash of the preimage which unlocks this HTLC.
573 pub payment_hash: PaymentHash,
574 /// The position within the commitment transactions' outputs. This may be None if the value is
575 /// below the dust limit (in which case no output appears in the commitment transaction and the
576 /// value is spent to additional transaction fees).
577 pub transaction_output_index: Option<u32>,
580 impl_writeable_tlv_based!(HTLCOutputInCommitment, {
581 (0, offered, required),
582 (2, amount_msat, required),
583 (4, cltv_expiry, required),
584 (6, payment_hash, required),
585 (8, transaction_output_index, option),
589 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) -> Script {
590 let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
592 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
593 .push_opcode(opcodes::all::OP_HASH160)
594 .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
595 .push_opcode(opcodes::all::OP_EQUAL)
596 .push_opcode(opcodes::all::OP_IF)
597 .push_opcode(opcodes::all::OP_CHECKSIG)
598 .push_opcode(opcodes::all::OP_ELSE)
599 .push_slice(&countersignatory_htlc_key.serialize()[..])
600 .push_opcode(opcodes::all::OP_SWAP)
601 .push_opcode(opcodes::all::OP_SIZE)
603 .push_opcode(opcodes::all::OP_EQUAL)
604 .push_opcode(opcodes::all::OP_NOTIF)
605 .push_opcode(opcodes::all::OP_DROP)
607 .push_opcode(opcodes::all::OP_SWAP)
608 .push_slice(&broadcaster_htlc_key.serialize()[..])
610 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
611 .push_opcode(opcodes::all::OP_ELSE)
612 .push_opcode(opcodes::all::OP_HASH160)
613 .push_slice(&payment_hash160)
614 .push_opcode(opcodes::all::OP_EQUALVERIFY)
615 .push_opcode(opcodes::all::OP_CHECKSIG)
616 .push_opcode(opcodes::all::OP_ENDIF);
617 if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
618 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
619 .push_opcode(opcodes::all::OP_CSV)
620 .push_opcode(opcodes::all::OP_DROP);
622 bldr.push_opcode(opcodes::all::OP_ENDIF)
625 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
626 .push_opcode(opcodes::all::OP_HASH160)
627 .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
628 .push_opcode(opcodes::all::OP_EQUAL)
629 .push_opcode(opcodes::all::OP_IF)
630 .push_opcode(opcodes::all::OP_CHECKSIG)
631 .push_opcode(opcodes::all::OP_ELSE)
632 .push_slice(&countersignatory_htlc_key.serialize()[..])
633 .push_opcode(opcodes::all::OP_SWAP)
634 .push_opcode(opcodes::all::OP_SIZE)
636 .push_opcode(opcodes::all::OP_EQUAL)
637 .push_opcode(opcodes::all::OP_IF)
638 .push_opcode(opcodes::all::OP_HASH160)
639 .push_slice(&payment_hash160)
640 .push_opcode(opcodes::all::OP_EQUALVERIFY)
642 .push_opcode(opcodes::all::OP_SWAP)
643 .push_slice(&broadcaster_htlc_key.serialize()[..])
645 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
646 .push_opcode(opcodes::all::OP_ELSE)
647 .push_opcode(opcodes::all::OP_DROP)
648 .push_int(htlc.cltv_expiry as i64)
649 .push_opcode(opcodes::all::OP_CLTV)
650 .push_opcode(opcodes::all::OP_DROP)
651 .push_opcode(opcodes::all::OP_CHECKSIG)
652 .push_opcode(opcodes::all::OP_ENDIF);
653 if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
654 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
655 .push_opcode(opcodes::all::OP_CSV)
656 .push_opcode(opcodes::all::OP_DROP);
658 bldr.push_opcode(opcodes::all::OP_ENDIF)
663 /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
664 /// does not need to have its previous_output_index filled.
666 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, keys: &TxCreationKeys) -> Script {
667 get_htlc_redeemscript_with_explicit_keys(htlc, channel_type_features, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
670 /// Gets the redeemscript for a funding output from the two funding public keys.
671 /// Note that the order of funding public keys does not matter.
672 pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> Script {
673 let broadcaster_funding_key = broadcaster.serialize();
674 let countersignatory_funding_key = countersignatory.serialize();
676 make_funding_redeemscript_from_slices(&broadcaster_funding_key, &countersignatory_funding_key)
679 pub(crate) fn make_funding_redeemscript_from_slices(broadcaster_funding_key: &[u8], countersignatory_funding_key: &[u8]) -> Script {
680 let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
681 if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
682 builder.push_slice(broadcaster_funding_key)
683 .push_slice(countersignatory_funding_key)
685 builder.push_slice(countersignatory_funding_key)
686 .push_slice(broadcaster_funding_key)
687 }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
690 /// Builds an unsigned HTLC-Success or HTLC-Timeout transaction from the given channel and HTLC
691 /// parameters. This is used by [`TrustedCommitmentTransaction::get_htlc_sigs`] to fetch the
692 /// transaction which needs signing, and can be used to construct an HTLC transaction which is
693 /// broadcastable given a counterparty HTLC signature.
695 /// Panics if htlc.transaction_output_index.is_none() (as such HTLCs do not appear in the
696 /// commitment transaction).
697 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 {
698 let mut txins: Vec<TxIn> = Vec::new();
699 txins.push(build_htlc_input(commitment_txid, htlc, channel_type_features));
701 let mut txouts: Vec<TxOut> = Vec::new();
702 txouts.push(build_htlc_output(
703 feerate_per_kw, contest_delay, htlc, channel_type_features,
704 broadcaster_delayed_payment_key, revocation_key
709 lock_time: PackedLockTime(if htlc.offered { htlc.cltv_expiry } else { 0 }),
715 pub(crate) fn build_htlc_input(commitment_txid: &Txid, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures) -> TxIn {
717 previous_output: OutPoint {
718 txid: commitment_txid.clone(),
719 vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
721 script_sig: Script::new(),
722 sequence: Sequence(if channel_type_features.supports_anchors_zero_fee_htlc_tx() { 1 } else { 0 }),
723 witness: Witness::new(),
727 pub(crate) fn build_htlc_output(
728 feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, broadcaster_delayed_payment_key: &PublicKey, revocation_key: &PublicKey
730 let weight = if htlc.offered {
731 htlc_timeout_tx_weight(channel_type_features)
733 htlc_success_tx_weight(channel_type_features)
735 let output_value = if channel_type_features.supports_anchors_zero_fee_htlc_tx() && !channel_type_features.supports_anchors_nonzero_fee_htlc_tx() {
736 htlc.amount_msat / 1000
738 let total_fee = feerate_per_kw as u64 * weight / 1000;
739 htlc.amount_msat / 1000 - total_fee
743 script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_v0_p2wsh(),
748 /// Returns the witness required to satisfy and spend a HTLC input.
749 pub fn build_htlc_input_witness(
750 local_sig: &Signature, remote_sig: &Signature, preimage: &Option<PaymentPreimage>,
751 redeem_script: &Script, channel_type_features: &ChannelTypeFeatures,
753 let remote_sighash_type = if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
754 EcdsaSighashType::SinglePlusAnyoneCanPay
756 EcdsaSighashType::All
759 let mut witness = Witness::new();
760 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
761 witness.push(vec![]);
762 witness.push_bitcoin_signature(&remote_sig.serialize_der(), remote_sighash_type);
763 witness.push_bitcoin_signature(&local_sig.serialize_der(), EcdsaSighashType::All);
764 if let Some(preimage) = preimage {
765 witness.push(preimage.0.to_vec());
767 // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
768 witness.push(vec![]);
770 witness.push(redeem_script.to_bytes());
774 /// Pre-anchors channel type features did not use to get serialized in the following six structs:
775 /// — [`ChannelTransactionParameters`]
776 /// — [`CommitmentTransaction`]
777 /// — [`CounterpartyOfferedHTLCOutput`]
778 /// — [`CounterpartyReceivedHTLCOutput`]
779 /// — [`HolderHTLCOutput`]
780 /// — [`HolderFundingOutput`]
782 /// To ensure a forwards-compatible serialization, we use odd TLV fields. However, if new features
783 /// are used that could break security, where old signers should be prevented from handling the
784 /// serialized data, an optional even-field TLV will be used as a stand-in to break compatibility.
786 /// This method determines whether or not that option needs to be set based on the chanenl type
787 /// features, and returns it.
789 /// [`CounterpartyOfferedHTLCOutput`]: crate::chain::package::CounterpartyOfferedHTLCOutput
790 /// [`CounterpartyReceivedHTLCOutput`]: crate::chain::package::CounterpartyReceivedHTLCOutput
791 /// [`HolderHTLCOutput`]: crate::chain::package::HolderHTLCOutput
792 /// [`HolderFundingOutput`]: crate::chain::package::HolderFundingOutput
793 pub(crate) fn legacy_deserialization_prevention_marker_for_channel_type_features(features: &ChannelTypeFeatures) -> Option<()> {
794 let mut legacy_version_bit_set = ChannelTypeFeatures::only_static_remote_key();
795 legacy_version_bit_set.set_scid_privacy_required();
796 legacy_version_bit_set.set_zero_conf_required();
798 if features.is_subset(&legacy_version_bit_set) {
805 /// Gets the witnessScript for the to_remote output when anchors are enabled.
807 pub fn get_to_countersignatory_with_anchors_redeemscript(payment_point: &PublicKey) -> Script {
809 .push_slice(&payment_point.serialize()[..])
810 .push_opcode(opcodes::all::OP_CHECKSIGVERIFY)
812 .push_opcode(opcodes::all::OP_CSV)
816 /// Gets the witnessScript for an anchor output from the funding public key.
817 /// The witness in the spending input must be:
818 /// <BIP 143 funding_signature>
819 /// After 16 blocks of confirmation, an alternative satisfying witness could be:
821 /// (empty vector required to satisfy compliance with MINIMALIF-standard rule)
823 pub fn get_anchor_redeemscript(funding_pubkey: &PublicKey) -> Script {
824 Builder::new().push_slice(&funding_pubkey.serialize()[..])
825 .push_opcode(opcodes::all::OP_CHECKSIG)
826 .push_opcode(opcodes::all::OP_IFDUP)
827 .push_opcode(opcodes::all::OP_NOTIF)
829 .push_opcode(opcodes::all::OP_CSV)
830 .push_opcode(opcodes::all::OP_ENDIF)
834 /// Locates the output with an anchor script paying to `funding_pubkey` within `commitment_tx`.
835 pub(crate) fn get_anchor_output<'a>(commitment_tx: &'a Transaction, funding_pubkey: &PublicKey) -> Option<(u32, &'a TxOut)> {
836 let anchor_script = chan_utils::get_anchor_redeemscript(funding_pubkey).to_v0_p2wsh();
837 commitment_tx.output.iter().enumerate()
838 .find(|(_, txout)| txout.script_pubkey == anchor_script)
839 .map(|(idx, txout)| (idx as u32, txout))
842 /// Returns the witness required to satisfy and spend an anchor input.
843 pub fn build_anchor_input_witness(funding_key: &PublicKey, funding_sig: &Signature) -> Witness {
844 let anchor_redeem_script = chan_utils::get_anchor_redeemscript(funding_key);
845 let mut ret = Witness::new();
846 ret.push_bitcoin_signature(&funding_sig.serialize_der(), EcdsaSighashType::All);
847 ret.push(anchor_redeem_script.as_bytes());
851 /// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
852 /// The fields are organized by holder/counterparty.
854 /// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
855 /// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
856 #[derive(Clone, Debug, PartialEq, Eq)]
857 pub struct ChannelTransactionParameters {
858 /// Holder public keys
859 pub holder_pubkeys: ChannelPublicKeys,
860 /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
861 pub holder_selected_contest_delay: u16,
862 /// Whether the holder is the initiator of this channel.
863 /// This is an input to the commitment number obscure factor computation.
864 pub is_outbound_from_holder: bool,
865 /// The late-bound counterparty channel transaction parameters.
866 /// These parameters are populated at the point in the protocol where the counterparty provides them.
867 pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
868 /// The late-bound funding outpoint
869 pub funding_outpoint: Option<chain::transaction::OutPoint>,
870 /// This channel's type, as negotiated during channel open. For old objects where this field
871 /// wasn't serialized, it will default to static_remote_key at deserialization.
872 pub channel_type_features: ChannelTypeFeatures
875 /// Late-bound per-channel counterparty data used to build transactions.
876 #[derive(Clone, Debug, PartialEq, Eq)]
877 pub struct CounterpartyChannelTransactionParameters {
878 /// Counter-party public keys
879 pub pubkeys: ChannelPublicKeys,
880 /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
881 pub selected_contest_delay: u16,
884 impl ChannelTransactionParameters {
885 /// Whether the late bound parameters are populated.
886 pub fn is_populated(&self) -> bool {
887 self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
890 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
891 /// given that the holder is the broadcaster.
893 /// self.is_populated() must be true before calling this function.
894 pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
895 assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
896 DirectedChannelTransactionParameters {
898 holder_is_broadcaster: true
902 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
903 /// given that the counterparty is the broadcaster.
905 /// self.is_populated() must be true before calling this function.
906 pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
907 assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
908 DirectedChannelTransactionParameters {
910 holder_is_broadcaster: false
915 impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, {
916 (0, pubkeys, required),
917 (2, selected_contest_delay, required),
920 impl Writeable for ChannelTransactionParameters {
921 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
922 let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
923 write_tlv_fields!(writer, {
924 (0, self.holder_pubkeys, required),
925 (2, self.holder_selected_contest_delay, required),
926 (4, self.is_outbound_from_holder, required),
927 (6, self.counterparty_parameters, option),
928 (8, self.funding_outpoint, option),
929 (10, legacy_deserialization_prevention_marker, option),
930 (11, self.channel_type_features, required),
936 impl Readable for ChannelTransactionParameters {
937 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
938 let mut holder_pubkeys = RequiredWrapper(None);
939 let mut holder_selected_contest_delay = RequiredWrapper(None);
940 let mut is_outbound_from_holder = RequiredWrapper(None);
941 let mut counterparty_parameters = None;
942 let mut funding_outpoint = None;
943 let mut _legacy_deserialization_prevention_marker: Option<()> = None;
944 let mut channel_type_features = None;
946 read_tlv_fields!(reader, {
947 (0, holder_pubkeys, required),
948 (2, holder_selected_contest_delay, required),
949 (4, is_outbound_from_holder, required),
950 (6, counterparty_parameters, option),
951 (8, funding_outpoint, option),
952 (10, _legacy_deserialization_prevention_marker, option),
953 (11, channel_type_features, option),
956 let mut additional_features = ChannelTypeFeatures::empty();
957 additional_features.set_anchors_nonzero_fee_htlc_tx_required();
958 chain::package::verify_channel_type_features(&channel_type_features, Some(&additional_features))?;
961 holder_pubkeys: holder_pubkeys.0.unwrap(),
962 holder_selected_contest_delay: holder_selected_contest_delay.0.unwrap(),
963 is_outbound_from_holder: is_outbound_from_holder.0.unwrap(),
964 counterparty_parameters,
966 channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
971 /// Static channel fields used to build transactions given per-commitment fields, organized by
972 /// broadcaster/countersignatory.
974 /// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
975 /// as_holder_broadcastable and as_counterparty_broadcastable functions.
976 pub struct DirectedChannelTransactionParameters<'a> {
977 /// The holder's channel static parameters
978 inner: &'a ChannelTransactionParameters,
979 /// Whether the holder is the broadcaster
980 holder_is_broadcaster: bool,
983 impl<'a> DirectedChannelTransactionParameters<'a> {
984 /// Get the channel pubkeys for the broadcaster
985 pub fn broadcaster_pubkeys(&self) -> &'a ChannelPublicKeys {
986 if self.holder_is_broadcaster {
987 &self.inner.holder_pubkeys
989 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
993 /// Get the channel pubkeys for the countersignatory
994 pub fn countersignatory_pubkeys(&self) -> &'a ChannelPublicKeys {
995 if self.holder_is_broadcaster {
996 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
998 &self.inner.holder_pubkeys
1002 /// Get the contest delay applicable to the transactions.
1003 /// Note that the contest delay was selected by the countersignatory.
1004 pub fn contest_delay(&self) -> u16 {
1005 let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
1006 if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
1009 /// Whether the channel is outbound from the broadcaster.
1011 /// The boolean representing the side that initiated the channel is
1012 /// an input to the commitment number obscure factor computation.
1013 pub fn is_outbound(&self) -> bool {
1014 if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
1017 /// The funding outpoint
1018 pub fn funding_outpoint(&self) -> OutPoint {
1019 self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
1022 /// Whether to use anchors for this channel
1023 pub fn channel_type_features(&self) -> &'a ChannelTypeFeatures {
1024 &self.inner.channel_type_features
1028 /// Information needed to build and sign a holder's commitment transaction.
1030 /// The transaction is only signed once we are ready to broadcast.
1031 #[derive(Clone, Debug)]
1032 pub struct HolderCommitmentTransaction {
1033 inner: CommitmentTransaction,
1034 /// Our counterparty's signature for the transaction
1035 pub counterparty_sig: Signature,
1036 /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
1037 pub counterparty_htlc_sigs: Vec<Signature>,
1038 // Which order the signatures should go in when constructing the final commitment tx witness.
1039 // The user should be able to reconstruct this themselves, so we don't bother to expose it.
1040 holder_sig_first: bool,
1043 impl Deref for HolderCommitmentTransaction {
1044 type Target = CommitmentTransaction;
1046 fn deref(&self) -> &Self::Target { &self.inner }
1049 impl Eq for HolderCommitmentTransaction {}
1050 impl PartialEq for HolderCommitmentTransaction {
1051 // We dont care whether we are signed in equality comparison
1052 fn eq(&self, o: &Self) -> bool {
1053 self.inner == o.inner
1057 impl_writeable_tlv_based!(HolderCommitmentTransaction, {
1058 (0, inner, required),
1059 (2, counterparty_sig, required),
1060 (4, holder_sig_first, required),
1061 (6, counterparty_htlc_sigs, required_vec),
1064 impl HolderCommitmentTransaction {
1066 pub fn dummy(htlcs: &mut Vec<(HTLCOutputInCommitment, ())>) -> Self {
1067 let secp_ctx = Secp256k1::new();
1068 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1069 let dummy_sig = sign(&secp_ctx, &secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
1071 let keys = TxCreationKeys {
1072 per_commitment_point: dummy_key.clone(),
1073 revocation_key: dummy_key.clone(),
1074 broadcaster_htlc_key: dummy_key.clone(),
1075 countersignatory_htlc_key: dummy_key.clone(),
1076 broadcaster_delayed_payment_key: dummy_key.clone(),
1078 let channel_pubkeys = ChannelPublicKeys {
1079 funding_pubkey: dummy_key.clone(),
1080 revocation_basepoint: dummy_key.clone(),
1081 payment_point: dummy_key.clone(),
1082 delayed_payment_basepoint: dummy_key.clone(),
1083 htlc_basepoint: dummy_key.clone()
1085 let channel_parameters = ChannelTransactionParameters {
1086 holder_pubkeys: channel_pubkeys.clone(),
1087 holder_selected_contest_delay: 0,
1088 is_outbound_from_holder: false,
1089 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
1090 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1091 channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
1093 let mut counterparty_htlc_sigs = Vec::new();
1094 for _ in 0..htlcs.len() {
1095 counterparty_htlc_sigs.push(dummy_sig);
1097 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());
1098 htlcs.sort_by_key(|htlc| htlc.0.transaction_output_index);
1099 HolderCommitmentTransaction {
1101 counterparty_sig: dummy_sig,
1102 counterparty_htlc_sigs,
1103 holder_sig_first: false
1107 /// Create a new holder transaction with the given counterparty signatures.
1108 /// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
1109 pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
1111 inner: commitment_tx,
1113 counterparty_htlc_sigs,
1114 holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
1118 pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
1119 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
1120 let mut tx = self.inner.built.transaction.clone();
1121 tx.input[0].witness.push(Vec::new());
1123 if self.holder_sig_first {
1124 tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1125 tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1127 tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1128 tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1131 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
1136 /// A pre-built Bitcoin commitment transaction and its txid.
1137 #[derive(Clone, Debug)]
1138 pub struct BuiltCommitmentTransaction {
1139 /// The commitment transaction
1140 pub transaction: Transaction,
1141 /// The txid for the commitment transaction.
1143 /// This is provided as a performance optimization, instead of calling transaction.txid()
1148 impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
1149 (0, transaction, required),
1150 (2, txid, required),
1153 impl BuiltCommitmentTransaction {
1154 /// Get the SIGHASH_ALL sighash value of the transaction.
1156 /// This can be used to verify a signature.
1157 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1158 let sighash = &sighash::SighashCache::new(&self.transaction).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1159 hash_to_message!(sighash)
1162 /// Signs the counterparty's commitment transaction.
1163 pub fn sign_counterparty_commitment<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1164 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1165 sign(secp_ctx, &sighash, funding_key)
1168 /// Signs the holder commitment transaction because we are about to broadcast it.
1169 pub fn sign_holder_commitment<T: secp256k1::Signing, ES: Deref>(
1170 &self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64,
1171 entropy_source: &ES, secp_ctx: &Secp256k1<T>
1172 ) -> Signature where ES::Target: EntropySource {
1173 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1174 sign_with_aux_rand(secp_ctx, &sighash, funding_key, entropy_source)
1178 /// This class tracks the per-transaction information needed to build a closing transaction and will
1179 /// actually build it and sign.
1181 /// This class can be used inside a signer implementation to generate a signature given the relevant
1183 #[derive(Clone, Hash, PartialEq, Eq)]
1184 pub struct ClosingTransaction {
1185 to_holder_value_sat: u64,
1186 to_counterparty_value_sat: u64,
1187 to_holder_script: Script,
1188 to_counterparty_script: Script,
1192 impl ClosingTransaction {
1193 /// Construct an object of the class
1195 to_holder_value_sat: u64,
1196 to_counterparty_value_sat: u64,
1197 to_holder_script: Script,
1198 to_counterparty_script: Script,
1199 funding_outpoint: OutPoint,
1201 let built = build_closing_transaction(
1202 to_holder_value_sat, to_counterparty_value_sat,
1203 to_holder_script.clone(), to_counterparty_script.clone(),
1206 ClosingTransaction {
1207 to_holder_value_sat,
1208 to_counterparty_value_sat,
1210 to_counterparty_script,
1215 /// Trust our pre-built transaction.
1217 /// Applies a wrapper which allows access to the transaction.
1219 /// This should only be used if you fully trust the builder of this object. It should not
1220 /// be used by an external signer - instead use the verify function.
1221 pub fn trust(&self) -> TrustedClosingTransaction {
1222 TrustedClosingTransaction { inner: self }
1225 /// Verify our pre-built transaction.
1227 /// Applies a wrapper which allows access to the transaction.
1229 /// An external validating signer must call this method before signing
1230 /// or using the built transaction.
1231 pub fn verify(&self, funding_outpoint: OutPoint) -> Result<TrustedClosingTransaction, ()> {
1232 let built = build_closing_transaction(
1233 self.to_holder_value_sat, self.to_counterparty_value_sat,
1234 self.to_holder_script.clone(), self.to_counterparty_script.clone(),
1237 if self.built != built {
1240 Ok(TrustedClosingTransaction { inner: self })
1243 /// The value to be sent to the holder, or zero if the output will be omitted
1244 pub fn to_holder_value_sat(&self) -> u64 {
1245 self.to_holder_value_sat
1248 /// The value to be sent to the counterparty, or zero if the output will be omitted
1249 pub fn to_counterparty_value_sat(&self) -> u64 {
1250 self.to_counterparty_value_sat
1253 /// The destination of the holder's output
1254 pub fn to_holder_script(&self) -> &Script {
1255 &self.to_holder_script
1258 /// The destination of the counterparty's output
1259 pub fn to_counterparty_script(&self) -> &Script {
1260 &self.to_counterparty_script
1264 /// A wrapper on ClosingTransaction indicating that the built bitcoin
1265 /// transaction is trusted.
1267 /// See trust() and verify() functions on CommitmentTransaction.
1269 /// This structure implements Deref.
1270 pub struct TrustedClosingTransaction<'a> {
1271 inner: &'a ClosingTransaction,
1274 impl<'a> Deref for TrustedClosingTransaction<'a> {
1275 type Target = ClosingTransaction;
1277 fn deref(&self) -> &Self::Target { self.inner }
1280 impl<'a> TrustedClosingTransaction<'a> {
1281 /// The pre-built Bitcoin commitment transaction
1282 pub fn built_transaction(&self) -> &'a Transaction {
1286 /// Get the SIGHASH_ALL sighash value of the transaction.
1288 /// This can be used to verify a signature.
1289 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1290 let sighash = &sighash::SighashCache::new(&self.inner.built).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1291 hash_to_message!(sighash)
1294 /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1295 /// because we are about to broadcast a holder transaction.
1296 pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1297 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1298 sign(secp_ctx, &sighash, funding_key)
1302 /// This class tracks the per-transaction information needed to build a commitment transaction and will
1303 /// actually build it and sign. It is used for holder transactions that we sign only when needed
1304 /// and for transactions we sign for the counterparty.
1306 /// This class can be used inside a signer implementation to generate a signature given the relevant
1308 #[derive(Clone, Debug)]
1309 pub struct CommitmentTransaction {
1310 commitment_number: u64,
1311 to_broadcaster_value_sat: u64,
1312 to_countersignatory_value_sat: u64,
1313 to_broadcaster_delay: Option<u16>, // Added in 0.0.117
1314 feerate_per_kw: u32,
1315 htlcs: Vec<HTLCOutputInCommitment>,
1316 // Note that on upgrades, some features of existing outputs may be missed.
1317 channel_type_features: ChannelTypeFeatures,
1318 // A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
1319 keys: TxCreationKeys,
1320 // For access to the pre-built transaction, see doc for trust()
1321 built: BuiltCommitmentTransaction,
1324 impl Eq for CommitmentTransaction {}
1325 impl PartialEq for CommitmentTransaction {
1326 fn eq(&self, o: &Self) -> bool {
1327 let eq = self.commitment_number == o.commitment_number &&
1328 self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
1329 self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
1330 self.feerate_per_kw == o.feerate_per_kw &&
1331 self.htlcs == o.htlcs &&
1332 self.channel_type_features == o.channel_type_features &&
1333 self.keys == o.keys;
1335 debug_assert_eq!(self.built.transaction, o.built.transaction);
1336 debug_assert_eq!(self.built.txid, o.built.txid);
1342 impl Writeable for CommitmentTransaction {
1343 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1344 let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
1345 write_tlv_fields!(writer, {
1346 (0, self.commitment_number, required),
1347 (1, self.to_broadcaster_delay, option),
1348 (2, self.to_broadcaster_value_sat, required),
1349 (4, self.to_countersignatory_value_sat, required),
1350 (6, self.feerate_per_kw, required),
1351 (8, self.keys, required),
1352 (10, self.built, required),
1353 (12, self.htlcs, required_vec),
1354 (14, legacy_deserialization_prevention_marker, option),
1355 (15, self.channel_type_features, required),
1361 impl Readable for CommitmentTransaction {
1362 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1363 _init_and_read_len_prefixed_tlv_fields!(reader, {
1364 (0, commitment_number, required),
1365 (1, to_broadcaster_delay, option),
1366 (2, to_broadcaster_value_sat, required),
1367 (4, to_countersignatory_value_sat, required),
1368 (6, feerate_per_kw, required),
1369 (8, keys, required),
1370 (10, built, required),
1371 (12, htlcs, required_vec),
1372 (14, _legacy_deserialization_prevention_marker, option),
1373 (15, channel_type_features, option),
1376 let mut additional_features = ChannelTypeFeatures::empty();
1377 additional_features.set_anchors_nonzero_fee_htlc_tx_required();
1378 chain::package::verify_channel_type_features(&channel_type_features, Some(&additional_features))?;
1381 commitment_number: commitment_number.0.unwrap(),
1382 to_broadcaster_value_sat: to_broadcaster_value_sat.0.unwrap(),
1383 to_countersignatory_value_sat: to_countersignatory_value_sat.0.unwrap(),
1384 to_broadcaster_delay,
1385 feerate_per_kw: feerate_per_kw.0.unwrap(),
1386 keys: keys.0.unwrap(),
1387 built: built.0.unwrap(),
1389 channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
1394 impl CommitmentTransaction {
1395 /// Construct an object of the class while assigning transaction output indices to HTLCs.
1397 /// Populates HTLCOutputInCommitment.transaction_output_index in htlcs_with_aux.
1399 /// The generic T allows the caller to match the HTLC output index with auxiliary data.
1400 /// This auxiliary data is not stored in this object.
1402 /// Only include HTLCs that are above the dust limit for the channel.
1404 /// This is not exported to bindings users due to the generic though we likely should expose a version without
1405 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 {
1406 // Sort outputs and populate output indices while keeping track of the auxiliary data
1407 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();
1409 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
1410 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1411 let txid = transaction.txid();
1412 CommitmentTransaction {
1414 to_broadcaster_value_sat,
1415 to_countersignatory_value_sat,
1416 to_broadcaster_delay: Some(channel_parameters.contest_delay()),
1419 channel_type_features: channel_parameters.channel_type_features().clone(),
1421 built: BuiltCommitmentTransaction {
1428 /// Use non-zero fee anchors
1430 /// This is not exported to bindings users due to move, and also not likely to be useful for binding users
1431 pub fn with_non_zero_fee_anchors(mut self) -> Self {
1432 self.channel_type_features.set_anchors_nonzero_fee_htlc_tx_required();
1436 fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<BuiltCommitmentTransaction, ()> {
1437 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
1439 let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
1440 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)?;
1442 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1443 let txid = transaction.txid();
1444 let built_transaction = BuiltCommitmentTransaction {
1448 Ok(built_transaction)
1451 fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
1454 lock_time: PackedLockTime(((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32)),
1460 // This is used in two cases:
1461 // - initial sorting of outputs / HTLCs in the constructor, in which case T is auxiliary data the
1462 // caller needs to have sorted together with the HTLCs so it can keep track of the output index
1463 // - building of a bitcoin transaction during a verify() call, in which case T is just ()
1464 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>), ()> {
1465 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1466 let contest_delay = channel_parameters.contest_delay();
1468 let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
1470 if to_countersignatory_value_sat > 0 {
1471 let script = if channel_parameters.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
1472 get_to_countersignatory_with_anchors_redeemscript(&countersignatory_pubkeys.payment_point).to_v0_p2wsh()
1474 Payload::p2wpkh(&BitcoinPublicKey::new(countersignatory_pubkeys.payment_point)).unwrap().script_pubkey()
1478 script_pubkey: script.clone(),
1479 value: to_countersignatory_value_sat,
1485 if to_broadcaster_value_sat > 0 {
1486 let redeem_script = get_revokeable_redeemscript(
1487 &keys.revocation_key,
1489 &keys.broadcaster_delayed_payment_key,
1493 script_pubkey: redeem_script.to_v0_p2wsh(),
1494 value: to_broadcaster_value_sat,
1500 if channel_parameters.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
1501 if to_broadcaster_value_sat > 0 || !htlcs_with_aux.is_empty() {
1502 let anchor_script = get_anchor_redeemscript(broadcaster_funding_key);
1505 script_pubkey: anchor_script.to_v0_p2wsh(),
1506 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1512 if to_countersignatory_value_sat > 0 || !htlcs_with_aux.is_empty() {
1513 let anchor_script = get_anchor_redeemscript(countersignatory_funding_key);
1516 script_pubkey: anchor_script.to_v0_p2wsh(),
1517 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1524 let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
1525 for (htlc, _) in htlcs_with_aux {
1526 let script = chan_utils::get_htlc_redeemscript(&htlc, &channel_parameters.channel_type_features(), &keys);
1528 script_pubkey: script.to_v0_p2wsh(),
1529 value: htlc.amount_msat / 1000,
1531 txouts.push((txout, Some(htlc)));
1534 // Sort output in BIP-69 order (amount, scriptPubkey). Tie-breaks based on HTLC
1535 // CLTV expiration height.
1536 sort_outputs(&mut txouts, |a, b| {
1537 if let &Some(ref a_htlcout) = a {
1538 if let &Some(ref b_htlcout) = b {
1539 a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
1540 // Note that due to hash collisions, we have to have a fallback comparison
1541 // here for fuzzing mode (otherwise at least chanmon_fail_consistency
1543 .then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
1544 // For non-HTLC outputs, if they're copying our SPK we don't really care if we
1545 // close the channel due to mismatches - they're doing something dumb:
1546 } else { cmp::Ordering::Equal }
1547 } else { cmp::Ordering::Equal }
1550 let mut outputs = Vec::with_capacity(txouts.len());
1551 for (idx, out) in txouts.drain(..).enumerate() {
1552 if let Some(htlc) = out.1 {
1553 htlc.transaction_output_index = Some(idx as u32);
1554 htlcs.push(htlc.clone());
1556 outputs.push(out.0);
1558 Ok((outputs, htlcs))
1561 fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
1562 let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
1563 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1564 let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
1565 &broadcaster_pubkeys.payment_point,
1566 &countersignatory_pubkeys.payment_point,
1567 channel_parameters.is_outbound(),
1570 let obscured_commitment_transaction_number =
1571 commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
1574 let mut ins: Vec<TxIn> = Vec::new();
1576 previous_output: channel_parameters.funding_outpoint(),
1577 script_sig: Script::new(),
1578 sequence: Sequence(((0x80 as u32) << 8 * 3)
1579 | ((obscured_commitment_transaction_number >> 3 * 8) as u32)),
1580 witness: Witness::new(),
1584 (obscured_commitment_transaction_number, txins)
1587 /// The backwards-counting commitment number
1588 pub fn commitment_number(&self) -> u64 {
1589 self.commitment_number
1592 /// The value to be sent to the broadcaster
1593 pub fn to_broadcaster_value_sat(&self) -> u64 {
1594 self.to_broadcaster_value_sat
1597 /// The value to be sent to the counterparty
1598 pub fn to_countersignatory_value_sat(&self) -> u64 {
1599 self.to_countersignatory_value_sat
1602 /// The feerate paid per 1000-weight-unit in this commitment transaction.
1603 pub fn feerate_per_kw(&self) -> u32 {
1607 /// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
1608 /// which were included in this commitment transaction in output order.
1609 /// The transaction index is always populated.
1611 /// This is not exported to bindings users as we cannot currently convert Vec references to/from C, though we should
1612 /// expose a less effecient version which creates a Vec of references in the future.
1613 pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
1617 /// Trust our pre-built transaction and derived transaction creation public keys.
1619 /// Applies a wrapper which allows access to these fields.
1621 /// This should only be used if you fully trust the builder of this object. It should not
1622 /// be used by an external signer - instead use the verify function.
1623 pub fn trust(&self) -> TrustedCommitmentTransaction {
1624 TrustedCommitmentTransaction { inner: self }
1627 /// Verify our pre-built transaction and derived transaction creation public keys.
1629 /// Applies a wrapper which allows access to these fields.
1631 /// An external validating signer must call this method before signing
1632 /// or using the built transaction.
1633 pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
1634 // This is the only field of the key cache that we trust
1635 let per_commitment_point = self.keys.per_commitment_point;
1636 let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx);
1637 if keys != self.keys {
1640 let tx = self.internal_rebuild_transaction(&keys, channel_parameters, &broadcaster_keys.funding_pubkey, &countersignatory_keys.funding_pubkey)?;
1641 if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
1644 Ok(TrustedCommitmentTransaction { inner: self })
1648 /// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
1649 /// transaction and the transaction creation keys) are trusted.
1651 /// See trust() and verify() functions on CommitmentTransaction.
1653 /// This structure implements Deref.
1654 pub struct TrustedCommitmentTransaction<'a> {
1655 inner: &'a CommitmentTransaction,
1658 impl<'a> Deref for TrustedCommitmentTransaction<'a> {
1659 type Target = CommitmentTransaction;
1661 fn deref(&self) -> &Self::Target { self.inner }
1664 impl<'a> TrustedCommitmentTransaction<'a> {
1665 /// The transaction ID of the built Bitcoin transaction
1666 pub fn txid(&self) -> Txid {
1667 self.inner.built.txid
1670 /// The pre-built Bitcoin commitment transaction
1671 pub fn built_transaction(&self) -> &'a BuiltCommitmentTransaction {
1675 /// The pre-calculated transaction creation public keys.
1676 pub fn keys(&self) -> &'a TxCreationKeys {
1680 /// Should anchors be used.
1681 pub fn channel_type_features(&self) -> &'a ChannelTypeFeatures {
1682 &self.inner.channel_type_features
1685 /// Get a signature for each HTLC which was included in the commitment transaction (ie for
1686 /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
1688 /// The returned Vec has one entry for each HTLC, and in the same order.
1690 /// This function is only valid in the holder commitment context, it always uses EcdsaSighashType::All.
1691 pub fn get_htlc_sigs<T: secp256k1::Signing, ES: Deref>(
1692 &self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters,
1693 entropy_source: &ES, secp_ctx: &Secp256k1<T>,
1694 ) -> Result<Vec<Signature>, ()> where ES::Target: EntropySource {
1695 let inner = self.inner;
1696 let keys = &inner.keys;
1697 let txid = inner.built.txid;
1698 let mut ret = Vec::with_capacity(inner.htlcs.len());
1699 let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key);
1701 for this_htlc in inner.htlcs.iter() {
1702 assert!(this_htlc.transaction_output_index.is_some());
1703 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);
1705 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);
1707 let sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, EcdsaSighashType::All).unwrap()[..]);
1708 ret.push(sign_with_aux_rand(secp_ctx, &sighash, &holder_htlc_key, entropy_source));
1713 /// Gets a signed HTLC transaction given a preimage (for !htlc.offered) and the holder HTLC transaction signature.
1714 pub(crate) fn get_signed_htlc_tx(&self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature, preimage: &Option<PaymentPreimage>) -> Transaction {
1715 let inner = self.inner;
1716 let keys = &inner.keys;
1717 let txid = inner.built.txid;
1718 let this_htlc = &inner.htlcs[htlc_index];
1719 assert!(this_htlc.transaction_output_index.is_some());
1720 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
1721 if !this_htlc.offered && preimage.is_none() { unreachable!(); }
1722 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
1723 if this_htlc.offered && preimage.is_some() { unreachable!(); }
1725 let mut 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);
1727 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);
1729 htlc_tx.input[0].witness = chan_utils::build_htlc_input_witness(
1730 signature, counterparty_signature, preimage, &htlc_redeemscript, &self.channel_type_features,
1735 /// Returns the index of the revokeable output, i.e. the `to_local` output sending funds to
1736 /// the broadcaster, in the built transaction, if any exists.
1738 /// There are two cases where this may return `None`:
1739 /// - The balance of the revokeable output is below the dust limit (only found on commitments
1740 /// early in the channel's lifetime, i.e. before the channel reserve is met).
1741 /// - This commitment was created before LDK 0.0.117. In this case, the
1742 /// commitment transaction previously didn't contain enough information to locate the
1743 /// revokeable output.
1744 pub fn revokeable_output_index(&self) -> Option<usize> {
1745 let revokeable_redeemscript = get_revokeable_redeemscript(
1746 &self.keys.revocation_key,
1747 self.to_broadcaster_delay?,
1748 &self.keys.broadcaster_delayed_payment_key,
1750 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
1751 let outputs = &self.inner.built.transaction.output;
1752 outputs.iter().enumerate()
1753 .find(|(_, out)| out.script_pubkey == revokeable_p2wsh)
1754 .map(|(idx, _)| idx)
1757 /// Helper method to build an unsigned justice transaction spending the revokeable
1758 /// `to_local` output to a destination script. Fee estimation accounts for the expected
1759 /// revocation witness data that will be added when signed.
1761 /// This method will error if the given fee rate results in a fee greater than the value
1762 /// of the output being spent, or if there exists no revokeable `to_local` output on this
1763 /// commitment transaction. See [`Self::revokeable_output_index`] for more details.
1765 /// The built transaction will allow fee bumping with RBF, and this method takes
1766 /// `feerate_per_kw` as an input such that multiple copies of a justice transaction at different
1767 /// fee rates may be built.
1768 pub fn build_to_local_justice_tx(&self, feerate_per_kw: u64, destination_script: Script)
1769 -> Result<Transaction, ()> {
1770 let output_idx = self.revokeable_output_index().ok_or(())?;
1771 let input = vec![TxIn {
1772 previous_output: OutPoint {
1773 txid: self.trust().txid(),
1774 vout: output_idx as u32,
1776 script_sig: Script::new(),
1777 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
1778 witness: Witness::new(),
1780 let value = self.inner.built.transaction.output[output_idx].value;
1781 let output = vec![TxOut {
1782 script_pubkey: destination_script,
1785 let mut justice_tx = Transaction {
1787 lock_time: PackedLockTime::ZERO,
1791 let weight = justice_tx.weight() as u64 + WEIGHT_REVOKED_OUTPUT;
1792 let fee = fee_for_weight(feerate_per_kw as u32, weight);
1793 justice_tx.output[0].value = value.checked_sub(fee).ok_or(())?;
1799 /// Commitment transaction numbers which appear in the transactions themselves are XOR'd with a
1800 /// shared secret first. This prevents on-chain observers from discovering how many commitment
1801 /// transactions occurred in a channel before it was closed.
1803 /// This function gets the shared secret from relevant channel public keys and can be used to
1804 /// "decrypt" the commitment transaction number given a commitment transaction on-chain.
1805 pub fn get_commitment_transaction_number_obscure_factor(
1806 broadcaster_payment_basepoint: &PublicKey,
1807 countersignatory_payment_basepoint: &PublicKey,
1808 outbound_from_broadcaster: bool,
1810 let mut sha = Sha256::engine();
1812 if outbound_from_broadcaster {
1813 sha.input(&broadcaster_payment_basepoint.serialize());
1814 sha.input(&countersignatory_payment_basepoint.serialize());
1816 sha.input(&countersignatory_payment_basepoint.serialize());
1817 sha.input(&broadcaster_payment_basepoint.serialize());
1819 let res = Sha256::from_engine(sha).into_inner();
1821 ((res[26] as u64) << 5 * 8)
1822 | ((res[27] as u64) << 4 * 8)
1823 | ((res[28] as u64) << 3 * 8)
1824 | ((res[29] as u64) << 2 * 8)
1825 | ((res[30] as u64) << 1 * 8)
1826 | ((res[31] as u64) << 0 * 8)
1831 use super::{CounterpartyCommitmentSecrets, ChannelPublicKeys};
1832 use crate::{hex, chain};
1833 use crate::prelude::*;
1834 use crate::ln::chan_utils::{get_htlc_redeemscript, get_to_countersignatory_with_anchors_redeemscript, CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
1835 use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
1836 use crate::util::test_utils;
1837 use crate::sign::{ChannelSigner, SignerProvider};
1838 use bitcoin::{Network, Txid, Script};
1839 use bitcoin::hashes::Hash;
1840 use crate::ln::PaymentHash;
1841 use bitcoin::hashes::hex::ToHex;
1842 use bitcoin::util::address::Payload;
1843 use bitcoin::PublicKey as BitcoinPublicKey;
1844 use crate::ln::features::ChannelTypeFeatures;
1846 struct TestCommitmentTxBuilder {
1847 commitment_number: u64,
1848 holder_funding_pubkey: PublicKey,
1849 counterparty_funding_pubkey: PublicKey,
1850 keys: TxCreationKeys,
1851 feerate_per_kw: u32,
1852 htlcs_with_aux: Vec<(HTLCOutputInCommitment, ())>,
1853 channel_parameters: ChannelTransactionParameters,
1854 counterparty_pubkeys: ChannelPublicKeys,
1857 impl TestCommitmentTxBuilder {
1859 let secp_ctx = Secp256k1::new();
1860 let seed = [42; 32];
1861 let network = Network::Testnet;
1862 let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
1863 let signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(false, 1_000_000, 0));
1864 let counterparty_signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(true, 1_000_000, 1));
1865 let delayed_payment_base = &signer.pubkeys().delayed_payment_basepoint;
1866 let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
1867 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
1868 let htlc_basepoint = &signer.pubkeys().htlc_basepoint;
1869 let holder_pubkeys = signer.pubkeys();
1870 let counterparty_pubkeys = counterparty_signer.pubkeys().clone();
1871 let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint);
1872 let channel_parameters = ChannelTransactionParameters {
1873 holder_pubkeys: holder_pubkeys.clone(),
1874 holder_selected_contest_delay: 0,
1875 is_outbound_from_holder: false,
1876 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: counterparty_pubkeys.clone(), selected_contest_delay: 0 }),
1877 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1878 channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
1880 let htlcs_with_aux = Vec::new();
1883 commitment_number: 0,
1884 holder_funding_pubkey: holder_pubkeys.funding_pubkey,
1885 counterparty_funding_pubkey: counterparty_pubkeys.funding_pubkey,
1890 counterparty_pubkeys,
1894 fn build(&mut self, to_broadcaster_sats: u64, to_countersignatory_sats: u64) -> CommitmentTransaction {
1895 CommitmentTransaction::new_with_auxiliary_htlc_data(
1896 self.commitment_number, to_broadcaster_sats, to_countersignatory_sats,
1897 self.holder_funding_pubkey.clone(),
1898 self.counterparty_funding_pubkey.clone(),
1899 self.keys.clone(), self.feerate_per_kw,
1900 &mut self.htlcs_with_aux, &self.channel_parameters.as_holder_broadcastable()
1907 let mut builder = TestCommitmentTxBuilder::new();
1909 // Generate broadcaster and counterparty outputs
1910 let tx = builder.build(1000, 2000);
1911 assert_eq!(tx.built.transaction.output.len(), 2);
1912 assert_eq!(tx.built.transaction.output[1].script_pubkey, Payload::p2wpkh(&BitcoinPublicKey::new(builder.counterparty_pubkeys.payment_point)).unwrap().script_pubkey());
1914 // Generate broadcaster and counterparty outputs as well as two anchors
1915 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
1916 let tx = builder.build(1000, 2000);
1917 assert_eq!(tx.built.transaction.output.len(), 4);
1918 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_to_countersignatory_with_anchors_redeemscript(&builder.counterparty_pubkeys.payment_point).to_v0_p2wsh());
1920 // Generate broadcaster output and anchor
1921 let tx = builder.build(3000, 0);
1922 assert_eq!(tx.built.transaction.output.len(), 2);
1924 // Generate counterparty output and anchor
1925 let tx = builder.build(0, 3000);
1926 assert_eq!(tx.built.transaction.output.len(), 2);
1928 let received_htlc = HTLCOutputInCommitment {
1930 amount_msat: 400000,
1932 payment_hash: PaymentHash([42; 32]),
1933 transaction_output_index: None,
1936 let offered_htlc = HTLCOutputInCommitment {
1938 amount_msat: 600000,
1940 payment_hash: PaymentHash([43; 32]),
1941 transaction_output_index: None,
1944 // Generate broadcaster output and received and offered HTLC outputs, w/o anchors
1945 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1946 builder.htlcs_with_aux = vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())];
1947 let tx = builder.build(3000, 0);
1948 let keys = &builder.keys.clone();
1949 assert_eq!(tx.built.transaction.output.len(), 3);
1950 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh());
1951 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh());
1952 assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh().to_hex(),
1953 "0020e43a7c068553003fe68fcae424fb7b28ec5ce48cd8b6744b3945631389bad2fb");
1954 assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh().to_hex(),
1955 "0020215d61bba56b19e9eadb6107f5a85d7f99c40f65992443f69229c290165bc00d");
1957 // Generate broadcaster output and received and offered HTLC outputs, with anchors
1958 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
1959 builder.htlcs_with_aux = vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())];
1960 let tx = builder.build(3000, 0);
1961 assert_eq!(tx.built.transaction.output.len(), 5);
1962 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());
1963 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());
1964 assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_v0_p2wsh().to_hex(),
1965 "0020b70d0649c72b38756885c7a30908d912a7898dd5d79457a7280b8e9a20f3f2bc");
1966 assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_v0_p2wsh().to_hex(),
1967 "002087a3faeb1950a469c0e2db4a79b093a41b9526e5a6fc6ef5cb949bde3be379c7");
1971 fn test_finding_revokeable_output_index() {
1972 let mut builder = TestCommitmentTxBuilder::new();
1974 // Revokeable output present
1975 let tx = builder.build(1000, 2000);
1976 assert_eq!(tx.built.transaction.output.len(), 2);
1977 assert_eq!(tx.trust().revokeable_output_index(), Some(0));
1979 // Revokeable output present (but to_broadcaster_delay missing)
1980 let tx = CommitmentTransaction { to_broadcaster_delay: None, ..tx };
1981 assert_eq!(tx.built.transaction.output.len(), 2);
1982 assert_eq!(tx.trust().revokeable_output_index(), None);
1984 // Revokeable output not present (our balance is dust)
1985 let tx = builder.build(0, 2000);
1986 assert_eq!(tx.built.transaction.output.len(), 1);
1987 assert_eq!(tx.trust().revokeable_output_index(), None);
1991 fn test_building_to_local_justice_tx() {
1992 let mut builder = TestCommitmentTxBuilder::new();
1994 // Revokeable output not present (our balance is dust)
1995 let tx = builder.build(0, 2000);
1996 assert_eq!(tx.built.transaction.output.len(), 1);
1997 assert!(tx.trust().build_to_local_justice_tx(253, Script::new()).is_err());
1999 // Revokeable output present
2000 let tx = builder.build(1000, 2000);
2001 assert_eq!(tx.built.transaction.output.len(), 2);
2004 assert!(tx.trust().build_to_local_justice_tx(100_000, Script::new()).is_err());
2006 // Generate a random public key for destination script
2007 let secret_key = SecretKey::from_slice(
2008 &hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100")
2009 .unwrap()[..]).unwrap();
2010 let pubkey_hash = BitcoinPublicKey::new(
2011 PublicKey::from_secret_key(&Secp256k1::new(), &secret_key)).wpubkey_hash().unwrap();
2012 let destination_script = Script::new_v0_p2wpkh(&pubkey_hash);
2014 let justice_tx = tx.trust().build_to_local_justice_tx(253, destination_script.clone()).unwrap();
2015 assert_eq!(justice_tx.input.len(), 1);
2016 assert_eq!(justice_tx.input[0].previous_output.txid, tx.built.transaction.txid());
2017 assert_eq!(justice_tx.input[0].previous_output.vout, tx.trust().revokeable_output_index().unwrap() as u32);
2018 assert!(justice_tx.input[0].sequence.is_rbf());
2020 assert_eq!(justice_tx.output.len(), 1);
2021 assert!(justice_tx.output[0].value < 1000);
2022 assert_eq!(justice_tx.output[0].script_pubkey, destination_script);
2026 fn test_per_commitment_storage() {
2027 // Test vectors from BOLT 3:
2028 let mut secrets: Vec<[u8; 32]> = Vec::new();
2031 macro_rules! test_secrets {
2033 let mut idx = 281474976710655;
2034 for secret in secrets.iter() {
2035 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
2038 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
2039 assert!(monitor.get_secret(idx).is_none());
2044 // insert_secret correct sequence
2045 monitor = CounterpartyCommitmentSecrets::new();
2048 secrets.push([0; 32]);
2049 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2050 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2053 secrets.push([0; 32]);
2054 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2055 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2058 secrets.push([0; 32]);
2059 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2060 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2063 secrets.push([0; 32]);
2064 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2065 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2068 secrets.push([0; 32]);
2069 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2070 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2073 secrets.push([0; 32]);
2074 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2075 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2078 secrets.push([0; 32]);
2079 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2080 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2083 secrets.push([0; 32]);
2084 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2085 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
2090 // insert_secret #1 incorrect
2091 monitor = CounterpartyCommitmentSecrets::new();
2094 secrets.push([0; 32]);
2095 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2096 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2099 secrets.push([0; 32]);
2100 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2101 assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
2105 // insert_secret #2 incorrect (#1 derived from incorrect)
2106 monitor = CounterpartyCommitmentSecrets::new();
2109 secrets.push([0; 32]);
2110 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2111 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2114 secrets.push([0; 32]);
2115 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2116 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2119 secrets.push([0; 32]);
2120 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2121 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2124 secrets.push([0; 32]);
2125 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2126 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
2130 // insert_secret #3 incorrect
2131 monitor = CounterpartyCommitmentSecrets::new();
2134 secrets.push([0; 32]);
2135 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2136 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2139 secrets.push([0; 32]);
2140 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2141 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2144 secrets.push([0; 32]);
2145 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2146 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2149 secrets.push([0; 32]);
2150 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2151 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
2155 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
2156 monitor = CounterpartyCommitmentSecrets::new();
2159 secrets.push([0; 32]);
2160 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2161 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2164 secrets.push([0; 32]);
2165 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2166 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2169 secrets.push([0; 32]);
2170 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2171 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2174 secrets.push([0; 32]);
2175 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
2176 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2179 secrets.push([0; 32]);
2180 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2181 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2184 secrets.push([0; 32]);
2185 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2186 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2189 secrets.push([0; 32]);
2190 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2191 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2194 secrets.push([0; 32]);
2195 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2196 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2200 // insert_secret #5 incorrect
2201 monitor = CounterpartyCommitmentSecrets::new();
2204 secrets.push([0; 32]);
2205 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2206 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2209 secrets.push([0; 32]);
2210 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2211 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2214 secrets.push([0; 32]);
2215 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2216 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2219 secrets.push([0; 32]);
2220 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2221 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2224 secrets.push([0; 32]);
2225 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2226 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2229 secrets.push([0; 32]);
2230 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2231 assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
2235 // insert_secret #6 incorrect (5 derived from incorrect)
2236 monitor = CounterpartyCommitmentSecrets::new();
2239 secrets.push([0; 32]);
2240 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2241 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2244 secrets.push([0; 32]);
2245 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2246 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2249 secrets.push([0; 32]);
2250 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2251 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2254 secrets.push([0; 32]);
2255 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2256 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2259 secrets.push([0; 32]);
2260 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2261 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2264 secrets.push([0; 32]);
2265 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
2266 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2269 secrets.push([0; 32]);
2270 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2271 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2274 secrets.push([0; 32]);
2275 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2276 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2280 // insert_secret #7 incorrect
2281 monitor = CounterpartyCommitmentSecrets::new();
2284 secrets.push([0; 32]);
2285 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2286 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2289 secrets.push([0; 32]);
2290 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2291 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2294 secrets.push([0; 32]);
2295 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2296 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2299 secrets.push([0; 32]);
2300 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2301 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2304 secrets.push([0; 32]);
2305 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2306 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2309 secrets.push([0; 32]);
2310 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2311 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2314 secrets.push([0; 32]);
2315 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2316 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2319 secrets.push([0; 32]);
2320 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2321 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2325 // insert_secret #8 incorrect
2326 monitor = CounterpartyCommitmentSecrets::new();
2329 secrets.push([0; 32]);
2330 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2331 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2334 secrets.push([0; 32]);
2335 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2336 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2339 secrets.push([0; 32]);
2340 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2341 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2344 secrets.push([0; 32]);
2345 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2346 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2349 secrets.push([0; 32]);
2350 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2351 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2354 secrets.push([0; 32]);
2355 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2356 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2359 secrets.push([0; 32]);
2360 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2361 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2364 secrets.push([0; 32]);
2365 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2366 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());