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::sign::EntropySource;
25 use crate::ln::{PaymentHash, PaymentPreimage};
26 use crate::ln::msgs::DecodeError;
27 use crate::util::ser::{Readable, RequiredWrapper, Writeable, Writer};
28 use crate::util::transaction_utils;
30 use bitcoin::secp256k1::{SecretKey, PublicKey, Scalar};
31 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature, Message};
32 use bitcoin::{PackedLockTime, secp256k1, Sequence, Witness};
33 use bitcoin::PublicKey as BitcoinPublicKey;
36 use crate::prelude::*;
38 use crate::ln::chan_utils;
39 use crate::util::transaction_utils::sort_outputs;
40 use crate::ln::channel::{INITIAL_COMMITMENT_NUMBER, ANCHOR_OUTPUT_VALUE_SATOSHI};
43 use crate::ln::features::ChannelTypeFeatures;
44 use crate::util::crypto::{sign, sign_with_aux_rand};
46 /// Maximum number of one-way in-flight HTLC (protocol-level value).
47 pub const MAX_HTLCS: u16 = 483;
48 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, non-anchor variant.
49 pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
50 /// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, anchor variant.
51 pub const OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS: usize = 136;
53 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
54 /// We define a range that encompasses both its non-anchors and anchors variants.
55 pub(crate) const MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 136;
56 /// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
57 /// We define a range that encompasses both its non-anchors and anchors variants.
58 /// This is the maximum post-anchor value.
59 pub const MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 143;
61 /// The upper bound weight of an anchor input.
62 pub const ANCHOR_INPUT_WITNESS_WEIGHT: u64 = 116;
63 /// The upper bound weight of an HTLC timeout input from a commitment transaction with anchor
65 pub const HTLC_TIMEOUT_INPUT_ANCHOR_WITNESS_WEIGHT: u64 = 288;
66 /// The upper bound weight of an HTLC success input from a commitment transaction with anchor
68 pub const HTLC_SUCCESS_INPUT_ANCHOR_WITNESS_WEIGHT: u64 = 327;
70 /// Gets the weight for an HTLC-Success transaction.
72 pub fn htlc_success_tx_weight(channel_type_features: &ChannelTypeFeatures) -> u64 {
73 const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
74 const HTLC_SUCCESS_ANCHOR_TX_WEIGHT: u64 = 706;
75 if channel_type_features.supports_anchors_zero_fee_htlc_tx() { HTLC_SUCCESS_ANCHOR_TX_WEIGHT } else { HTLC_SUCCESS_TX_WEIGHT }
78 /// Gets the weight for an HTLC-Timeout transaction.
80 pub fn htlc_timeout_tx_weight(channel_type_features: &ChannelTypeFeatures) -> u64 {
81 const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
82 const HTLC_TIMEOUT_ANCHOR_TX_WEIGHT: u64 = 666;
83 if channel_type_features.supports_anchors_zero_fee_htlc_tx() { HTLC_TIMEOUT_ANCHOR_TX_WEIGHT } else { HTLC_TIMEOUT_TX_WEIGHT }
86 /// Describes the type of HTLC claim as determined by analyzing the witness.
87 #[derive(PartialEq, Eq)]
89 /// Claims an offered output on a commitment transaction through the timeout path.
91 /// Claims an offered output on a commitment transaction through the success path.
93 /// Claims an accepted output on a commitment transaction through the timeout path.
95 /// Claims an accepted output on a commitment transaction through the success path.
97 /// Claims an offered/accepted output on a commitment transaction through the revocation path.
102 /// Check if a given input witness attempts to claim a HTLC.
103 pub fn from_witness(witness: &Witness) -> Option<Self> {
104 debug_assert_eq!(OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS, MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT);
105 if witness.len() < 2 {
108 let witness_script = witness.last().unwrap();
109 let second_to_last = witness.second_to_last().unwrap();
110 if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT {
111 if witness.len() == 3 && second_to_last.len() == 33 {
112 // <revocation sig> <revocationpubkey> <witness_script>
113 Some(Self::Revocation)
114 } else if witness.len() == 3 && second_to_last.len() == 32 {
115 // <remotehtlcsig> <payment_preimage> <witness_script>
116 Some(Self::OfferedPreimage)
117 } else if witness.len() == 5 && second_to_last.len() == 0 {
118 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
119 Some(Self::OfferedTimeout)
123 } else if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS {
124 // It's possible for the weight of `offered_htlc_script` and `accepted_htlc_script` to
125 // match so we check for both here.
126 if witness.len() == 3 && second_to_last.len() == 33 {
127 // <revocation sig> <revocationpubkey> <witness_script>
128 Some(Self::Revocation)
129 } else if witness.len() == 3 && second_to_last.len() == 32 {
130 // <remotehtlcsig> <payment_preimage> <witness_script>
131 Some(Self::OfferedPreimage)
132 } else if witness.len() == 5 && second_to_last.len() == 0 {
133 // 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
134 Some(Self::OfferedTimeout)
135 } else if witness.len() == 3 && second_to_last.len() == 0 {
136 // <remotehtlcsig> <> <witness_script>
137 Some(Self::AcceptedTimeout)
138 } else if witness.len() == 5 && second_to_last.len() == 32 {
139 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
140 Some(Self::AcceptedPreimage)
144 } else if witness_script.len() > MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT &&
145 witness_script.len() <= MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT {
146 // Handle remaining range of ACCEPTED_HTLC_SCRIPT_WEIGHT.
147 if witness.len() == 3 && second_to_last.len() == 33 {
148 // <revocation sig> <revocationpubkey> <witness_script>
149 Some(Self::Revocation)
150 } else if witness.len() == 3 && second_to_last.len() == 0 {
151 // <remotehtlcsig> <> <witness_script>
152 Some(Self::AcceptedTimeout)
153 } else if witness.len() == 5 && second_to_last.len() == 32 {
154 // 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
155 Some(Self::AcceptedPreimage)
165 // Various functions for key derivation and transaction creation for use within channels. Primarily
166 // used in Channel and ChannelMonitor.
168 /// Build the commitment secret from the seed and the commitment number
169 pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
170 let mut res: [u8; 32] = commitment_seed.clone();
173 if idx & (1 << bitpos) == (1 << bitpos) {
174 res[bitpos / 8] ^= 1 << (bitpos & 7);
175 res = Sha256::hash(&res).into_inner();
181 /// Build a closing transaction
182 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 {
184 let mut ins: Vec<TxIn> = Vec::new();
186 previous_output: funding_outpoint,
187 script_sig: Script::new(),
188 sequence: Sequence::MAX,
189 witness: Witness::new(),
194 let mut txouts: Vec<(TxOut, ())> = Vec::new();
196 if to_counterparty_value_sat > 0 {
198 script_pubkey: to_counterparty_script,
199 value: to_counterparty_value_sat
203 if to_holder_value_sat > 0 {
205 script_pubkey: to_holder_script,
206 value: to_holder_value_sat
210 transaction_utils::sort_outputs(&mut txouts, |_, _| { cmp::Ordering::Equal }); // Ordering doesnt matter if they used our pubkey...
212 let mut outputs: Vec<TxOut> = Vec::new();
213 for out in txouts.drain(..) {
219 lock_time: PackedLockTime::ZERO,
225 /// Implements the per-commitment secret storage scheme from
226 /// [BOLT 3](https://github.com/lightning/bolts/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
228 /// Allows us to keep track of all of the revocation secrets of our counterparty in just 50*32 bytes
231 pub struct CounterpartyCommitmentSecrets {
232 old_secrets: [([u8; 32], u64); 49],
235 impl Eq for CounterpartyCommitmentSecrets {}
236 impl PartialEq for CounterpartyCommitmentSecrets {
237 fn eq(&self, other: &Self) -> bool {
238 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
239 if secret != o_secret || idx != o_idx {
247 impl CounterpartyCommitmentSecrets {
248 /// Creates a new empty `CounterpartyCommitmentSecrets` structure.
249 pub fn new() -> Self {
250 Self { old_secrets: [([0; 32], 1 << 48); 49], }
254 fn place_secret(idx: u64) -> u8 {
256 if idx & (1 << i) == (1 << i) {
263 /// Returns the minimum index of all stored secrets. Note that indexes start
264 /// at 1 << 48 and get decremented by one for each new secret.
265 pub fn get_min_seen_secret(&self) -> u64 {
266 //TODO This can be optimized?
267 let mut min = 1 << 48;
268 for &(_, idx) in self.old_secrets.iter() {
277 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
278 let mut res: [u8; 32] = secret;
280 let bitpos = bits - 1 - i;
281 if idx & (1 << bitpos) == (1 << bitpos) {
282 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
283 res = Sha256::hash(&res).into_inner();
289 /// Inserts the `secret` at `idx`. Returns `Ok(())` if the secret
290 /// was generated in accordance with BOLT 3 and is consistent with previous secrets.
291 pub fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
292 let pos = Self::place_secret(idx);
294 let (old_secret, old_idx) = self.old_secrets[i as usize];
295 if Self::derive_secret(secret, pos, old_idx) != old_secret {
299 if self.get_min_seen_secret() <= idx {
302 self.old_secrets[pos as usize] = (secret, idx);
306 /// Returns the secret at `idx`.
307 /// Returns `None` if `idx` is < [`CounterpartyCommitmentSecrets::get_min_seen_secret`].
308 pub fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
309 for i in 0..self.old_secrets.len() {
310 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
311 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
314 assert!(idx < self.get_min_seen_secret());
319 impl Writeable for CounterpartyCommitmentSecrets {
320 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
321 for &(ref secret, ref idx) in self.old_secrets.iter() {
322 writer.write_all(secret)?;
323 writer.write_all(&idx.to_be_bytes())?;
325 write_tlv_fields!(writer, {});
329 impl Readable for CounterpartyCommitmentSecrets {
330 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
331 let mut old_secrets = [([0; 32], 1 << 48); 49];
332 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
333 *secret = Readable::read(reader)?;
334 *idx = Readable::read(reader)?;
336 read_tlv_fields!(reader, {});
337 Ok(Self { old_secrets })
341 /// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
342 /// from the base secret and the per_commitment_point.
343 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> SecretKey {
344 let mut sha = Sha256::engine();
345 sha.input(&per_commitment_point.serialize());
346 sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
347 let res = Sha256::from_engine(sha).into_inner();
349 base_secret.clone().add_tweak(&Scalar::from_be_bytes(res).unwrap())
350 .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.")
353 /// Derives a per-commitment-transaction public key (eg an htlc key or a delayed_payment key)
354 /// from the base point and the per_commitment_key. This is the public equivalent of
355 /// derive_private_key - using only public keys to derive a public key instead of private keys.
356 pub fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> PublicKey {
357 let mut sha = Sha256::engine();
358 sha.input(&per_commitment_point.serialize());
359 sha.input(&base_point.serialize());
360 let res = Sha256::from_engine(sha).into_inner();
362 let hashkey = PublicKey::from_secret_key(&secp_ctx,
363 &SecretKey::from_slice(&res).expect("Hashes should always be valid keys unless SHA-256 is broken"));
364 base_point.combine(&hashkey)
365 .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.")
368 /// Derives a per-commitment-transaction revocation key from its constituent parts.
370 /// Only the cheating participant owns a valid witness to propagate a revoked
371 /// commitment transaction, thus per_commitment_secret always come from cheater
372 /// and revocation_base_secret always come from punisher, which is the broadcaster
373 /// of the transaction spending with this key knowledge.
374 pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>,
375 per_commitment_secret: &SecretKey, countersignatory_revocation_base_secret: &SecretKey)
377 let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
378 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
380 let rev_append_commit_hash_key = {
381 let mut sha = Sha256::engine();
382 sha.input(&countersignatory_revocation_base_point.serialize());
383 sha.input(&per_commitment_point.serialize());
385 Sha256::from_engine(sha).into_inner()
387 let commit_append_rev_hash_key = {
388 let mut sha = Sha256::engine();
389 sha.input(&per_commitment_point.serialize());
390 sha.input(&countersignatory_revocation_base_point.serialize());
392 Sha256::from_engine(sha).into_inner()
395 let countersignatory_contrib = countersignatory_revocation_base_secret.clone().mul_tweak(&Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
396 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
397 let broadcaster_contrib = per_commitment_secret.clone().mul_tweak(&Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
398 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
399 countersignatory_contrib.add_tweak(&Scalar::from_be_bytes(broadcaster_contrib.secret_bytes()).unwrap())
400 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
403 /// Derives a per-commitment-transaction revocation public key from its constituent parts. This is
404 /// the public equivalend of derive_private_revocation_key - using only public keys to derive a
405 /// public key instead of private keys.
407 /// Only the cheating participant owns a valid witness to propagate a revoked
408 /// commitment transaction, thus per_commitment_point always come from cheater
409 /// and revocation_base_point always come from punisher, which is the broadcaster
410 /// of the transaction spending with this key knowledge.
412 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
413 /// generated (ie our own).
414 pub fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp256k1<T>,
415 per_commitment_point: &PublicKey, countersignatory_revocation_base_point: &PublicKey)
417 let rev_append_commit_hash_key = {
418 let mut sha = Sha256::engine();
419 sha.input(&countersignatory_revocation_base_point.serialize());
420 sha.input(&per_commitment_point.serialize());
422 Sha256::from_engine(sha).into_inner()
424 let commit_append_rev_hash_key = {
425 let mut sha = Sha256::engine();
426 sha.input(&per_commitment_point.serialize());
427 sha.input(&countersignatory_revocation_base_point.serialize());
429 Sha256::from_engine(sha).into_inner()
432 let countersignatory_contrib = countersignatory_revocation_base_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
433 .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
434 let broadcaster_contrib = per_commitment_point.clone().mul_tweak(&secp_ctx, &Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
435 .expect("Multiplying a valid public key by a hash is expected to never fail per secp256k1 docs");
436 countersignatory_contrib.combine(&broadcaster_contrib)
437 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
440 /// The set of public keys which are used in the creation of one commitment transaction.
441 /// These are derived from the channel base keys and per-commitment data.
443 /// A broadcaster key is provided from potential broadcaster of the computed transaction.
444 /// A countersignatory key is coming from a protocol participant unable to broadcast the
447 /// These keys are assumed to be good, either because the code derived them from
448 /// channel basepoints via the new function, or they were obtained via
449 /// CommitmentTransaction.trust().keys() because we trusted the source of the
450 /// pre-calculated keys.
451 #[derive(PartialEq, Eq, Clone)]
452 pub struct TxCreationKeys {
453 /// The broadcaster's per-commitment public key which was used to derive the other keys.
454 pub per_commitment_point: PublicKey,
455 /// The revocation key which is used to allow the broadcaster of the commitment
456 /// transaction to provide their counterparty the ability to punish them if they broadcast
458 pub revocation_key: PublicKey,
459 /// Broadcaster's HTLC Key
460 pub broadcaster_htlc_key: PublicKey,
461 /// Countersignatory's HTLC Key
462 pub countersignatory_htlc_key: PublicKey,
463 /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
464 pub broadcaster_delayed_payment_key: PublicKey,
467 impl_writeable_tlv_based!(TxCreationKeys, {
468 (0, per_commitment_point, required),
469 (2, revocation_key, required),
470 (4, broadcaster_htlc_key, required),
471 (6, countersignatory_htlc_key, required),
472 (8, broadcaster_delayed_payment_key, required),
475 /// One counterparty's public keys which do not change over the life of a channel.
476 #[derive(Clone, Debug, PartialEq, Eq)]
477 pub struct ChannelPublicKeys {
478 /// The public key which is used to sign all commitment transactions, as it appears in the
479 /// on-chain channel lock-in 2-of-2 multisig output.
480 pub funding_pubkey: PublicKey,
481 /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
482 /// revocation keys. This is combined with the per-commitment-secret generated by the
483 /// counterparty to create a secret which the counterparty can reveal to revoke previous
485 pub revocation_basepoint: PublicKey,
486 /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
487 /// spendable primary channel balance on the broadcaster's commitment transaction. This key is
488 /// static across every commitment transaction.
489 pub payment_point: PublicKey,
490 /// The base point which is used (with derive_public_key) to derive a per-commitment payment
491 /// public key which receives non-HTLC-encumbered funds which are only available for spending
492 /// after some delay (or can be claimed via the revocation path).
493 pub delayed_payment_basepoint: PublicKey,
494 /// The base point which is used (with derive_public_key) to derive a per-commitment public key
495 /// which is used to encumber HTLC-in-flight outputs.
496 pub htlc_basepoint: PublicKey,
499 impl_writeable_tlv_based!(ChannelPublicKeys, {
500 (0, funding_pubkey, required),
501 (2, revocation_basepoint, required),
502 (4, payment_point, required),
503 (6, delayed_payment_basepoint, required),
504 (8, htlc_basepoint, required),
507 impl TxCreationKeys {
508 /// Create per-state keys from channel base points and the per-commitment point.
509 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
510 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 {
512 per_commitment_point: per_commitment_point.clone(),
513 revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &countersignatory_revocation_base),
514 broadcaster_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_htlc_base),
515 countersignatory_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &countersignatory_htlc_base),
516 broadcaster_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &broadcaster_delayed_payment_base),
520 /// Generate per-state keys from channel static keys.
521 /// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
522 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 {
523 TxCreationKeys::derive_new(
525 &per_commitment_point,
526 &broadcaster_keys.delayed_payment_basepoint,
527 &broadcaster_keys.htlc_basepoint,
528 &countersignatory_keys.revocation_basepoint,
529 &countersignatory_keys.htlc_basepoint,
534 /// The maximum length of a script returned by get_revokeable_redeemscript.
535 // Calculated as 6 bytes of opcodes, 1 byte push plus 2 bytes for contest_delay, and two public
536 // keys of 33 bytes (+ 1 push).
537 pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 3 + 34*2;
539 /// A script either spendable by the revocation
540 /// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
541 /// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
542 pub fn get_revokeable_redeemscript(revocation_key: &PublicKey, contest_delay: u16, broadcaster_delayed_payment_key: &PublicKey) -> Script {
543 let res = Builder::new().push_opcode(opcodes::all::OP_IF)
544 .push_slice(&revocation_key.serialize())
545 .push_opcode(opcodes::all::OP_ELSE)
546 .push_int(contest_delay as i64)
547 .push_opcode(opcodes::all::OP_CSV)
548 .push_opcode(opcodes::all::OP_DROP)
549 .push_slice(&broadcaster_delayed_payment_key.serialize())
550 .push_opcode(opcodes::all::OP_ENDIF)
551 .push_opcode(opcodes::all::OP_CHECKSIG)
553 debug_assert!(res.len() <= REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH);
557 /// Information about an HTLC as it appears in a commitment transaction
558 #[derive(Clone, Debug, PartialEq, Eq)]
559 pub struct HTLCOutputInCommitment {
560 /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
561 /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
562 /// need to compare this value to whether the commitment transaction in question is that of
563 /// the counterparty or our own.
565 /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
566 /// this divided by 1000.
567 pub amount_msat: u64,
568 /// The CLTV lock-time at which this HTLC expires.
569 pub cltv_expiry: u32,
570 /// The hash of the preimage which unlocks this HTLC.
571 pub payment_hash: PaymentHash,
572 /// The position within the commitment transactions' outputs. This may be None if the value is
573 /// below the dust limit (in which case no output appears in the commitment transaction and the
574 /// value is spent to additional transaction fees).
575 pub transaction_output_index: Option<u32>,
578 impl_writeable_tlv_based!(HTLCOutputInCommitment, {
579 (0, offered, required),
580 (2, amount_msat, required),
581 (4, cltv_expiry, required),
582 (6, payment_hash, required),
583 (8, transaction_output_index, option),
587 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 {
588 let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
590 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
591 .push_opcode(opcodes::all::OP_HASH160)
592 .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
593 .push_opcode(opcodes::all::OP_EQUAL)
594 .push_opcode(opcodes::all::OP_IF)
595 .push_opcode(opcodes::all::OP_CHECKSIG)
596 .push_opcode(opcodes::all::OP_ELSE)
597 .push_slice(&countersignatory_htlc_key.serialize()[..])
598 .push_opcode(opcodes::all::OP_SWAP)
599 .push_opcode(opcodes::all::OP_SIZE)
601 .push_opcode(opcodes::all::OP_EQUAL)
602 .push_opcode(opcodes::all::OP_NOTIF)
603 .push_opcode(opcodes::all::OP_DROP)
605 .push_opcode(opcodes::all::OP_SWAP)
606 .push_slice(&broadcaster_htlc_key.serialize()[..])
608 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
609 .push_opcode(opcodes::all::OP_ELSE)
610 .push_opcode(opcodes::all::OP_HASH160)
611 .push_slice(&payment_hash160)
612 .push_opcode(opcodes::all::OP_EQUALVERIFY)
613 .push_opcode(opcodes::all::OP_CHECKSIG)
614 .push_opcode(opcodes::all::OP_ENDIF);
615 if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
616 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
617 .push_opcode(opcodes::all::OP_CSV)
618 .push_opcode(opcodes::all::OP_DROP);
620 bldr.push_opcode(opcodes::all::OP_ENDIF)
623 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
624 .push_opcode(opcodes::all::OP_HASH160)
625 .push_slice(&PubkeyHash::hash(&revocation_key.serialize())[..])
626 .push_opcode(opcodes::all::OP_EQUAL)
627 .push_opcode(opcodes::all::OP_IF)
628 .push_opcode(opcodes::all::OP_CHECKSIG)
629 .push_opcode(opcodes::all::OP_ELSE)
630 .push_slice(&countersignatory_htlc_key.serialize()[..])
631 .push_opcode(opcodes::all::OP_SWAP)
632 .push_opcode(opcodes::all::OP_SIZE)
634 .push_opcode(opcodes::all::OP_EQUAL)
635 .push_opcode(opcodes::all::OP_IF)
636 .push_opcode(opcodes::all::OP_HASH160)
637 .push_slice(&payment_hash160)
638 .push_opcode(opcodes::all::OP_EQUALVERIFY)
640 .push_opcode(opcodes::all::OP_SWAP)
641 .push_slice(&broadcaster_htlc_key.serialize()[..])
643 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
644 .push_opcode(opcodes::all::OP_ELSE)
645 .push_opcode(opcodes::all::OP_DROP)
646 .push_int(htlc.cltv_expiry as i64)
647 .push_opcode(opcodes::all::OP_CLTV)
648 .push_opcode(opcodes::all::OP_DROP)
649 .push_opcode(opcodes::all::OP_CHECKSIG)
650 .push_opcode(opcodes::all::OP_ENDIF);
651 if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
652 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
653 .push_opcode(opcodes::all::OP_CSV)
654 .push_opcode(opcodes::all::OP_DROP);
656 bldr.push_opcode(opcodes::all::OP_ENDIF)
661 /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
662 /// does not need to have its previous_output_index filled.
664 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, keys: &TxCreationKeys) -> Script {
665 get_htlc_redeemscript_with_explicit_keys(htlc, channel_type_features, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
668 /// Gets the redeemscript for a funding output from the two funding public keys.
669 /// Note that the order of funding public keys does not matter.
670 pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> Script {
671 let broadcaster_funding_key = broadcaster.serialize();
672 let countersignatory_funding_key = countersignatory.serialize();
674 make_funding_redeemscript_from_slices(&broadcaster_funding_key, &countersignatory_funding_key)
677 pub(crate) fn make_funding_redeemscript_from_slices(broadcaster_funding_key: &[u8], countersignatory_funding_key: &[u8]) -> Script {
678 let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
679 if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
680 builder.push_slice(broadcaster_funding_key)
681 .push_slice(countersignatory_funding_key)
683 builder.push_slice(countersignatory_funding_key)
684 .push_slice(broadcaster_funding_key)
685 }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
688 /// Builds an unsigned HTLC-Success or HTLC-Timeout transaction from the given channel and HTLC
689 /// parameters. This is used by [`TrustedCommitmentTransaction::get_htlc_sigs`] to fetch the
690 /// transaction which needs signing, and can be used to construct an HTLC transaction which is
691 /// broadcastable given a counterparty HTLC signature.
693 /// Panics if htlc.transaction_output_index.is_none() (as such HTLCs do not appear in the
694 /// commitment transaction).
695 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 {
696 let mut txins: Vec<TxIn> = Vec::new();
697 txins.push(build_htlc_input(commitment_txid, htlc, channel_type_features));
699 let mut txouts: Vec<TxOut> = Vec::new();
700 txouts.push(build_htlc_output(
701 feerate_per_kw, contest_delay, htlc, channel_type_features,
702 broadcaster_delayed_payment_key, revocation_key
707 lock_time: PackedLockTime(if htlc.offered { htlc.cltv_expiry } else { 0 }),
713 pub(crate) fn build_htlc_input(commitment_txid: &Txid, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures) -> TxIn {
715 previous_output: OutPoint {
716 txid: commitment_txid.clone(),
717 vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
719 script_sig: Script::new(),
720 sequence: Sequence(if channel_type_features.supports_anchors_zero_fee_htlc_tx() { 1 } else { 0 }),
721 witness: Witness::new(),
725 pub(crate) fn build_htlc_output(
726 feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, broadcaster_delayed_payment_key: &PublicKey, revocation_key: &PublicKey
728 let weight = if htlc.offered {
729 htlc_timeout_tx_weight(channel_type_features)
731 htlc_success_tx_weight(channel_type_features)
733 let output_value = if channel_type_features.supports_anchors_zero_fee_htlc_tx() && !channel_type_features.supports_anchors_nonzero_fee_htlc_tx() {
734 htlc.amount_msat / 1000
736 let total_fee = feerate_per_kw as u64 * weight / 1000;
737 htlc.amount_msat / 1000 - total_fee
741 script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_v0_p2wsh(),
746 /// Returns the witness required to satisfy and spend a HTLC input.
747 pub fn build_htlc_input_witness(
748 local_sig: &Signature, remote_sig: &Signature, preimage: &Option<PaymentPreimage>,
749 redeem_script: &Script, channel_type_features: &ChannelTypeFeatures,
751 let remote_sighash_type = if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
752 EcdsaSighashType::SinglePlusAnyoneCanPay
754 EcdsaSighashType::All
757 let mut witness = Witness::new();
758 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
759 witness.push(vec![]);
760 witness.push_bitcoin_signature(&remote_sig.serialize_der(), remote_sighash_type);
761 witness.push_bitcoin_signature(&local_sig.serialize_der(), EcdsaSighashType::All);
762 if let Some(preimage) = preimage {
763 witness.push(preimage.0.to_vec());
765 // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
766 witness.push(vec![]);
768 witness.push(redeem_script.to_bytes());
772 /// Pre-anchors channel type features did not use to get serialized in the following six structs:
773 /// — [`ChannelTransactionParameters`]
774 /// — [`CommitmentTransaction`]
775 /// — [`CounterpartyOfferedHTLCOutput`]
776 /// — [`CounterpartyReceivedHTLCOutput`]
777 /// — [`HolderHTLCOutput`]
778 /// — [`HolderFundingOutput`]
780 /// To ensure a forwards-compatible serialization, we use odd TLV fields. However, if new features
781 /// are used that could break security, where old signers should be prevented from handling the
782 /// serialized data, an optional even-field TLV will be used as a stand-in to break compatibility.
784 /// This method determines whether or not that option needs to be set based on the chanenl type
785 /// features, and returns it.
787 /// [`CounterpartyOfferedHTLCOutput`]: crate::chain::package::CounterpartyOfferedHTLCOutput
788 /// [`CounterpartyReceivedHTLCOutput`]: crate::chain::package::CounterpartyReceivedHTLCOutput
789 /// [`HolderHTLCOutput`]: crate::chain::package::HolderHTLCOutput
790 /// [`HolderFundingOutput`]: crate::chain::package::HolderFundingOutput
791 pub(crate) fn legacy_deserialization_prevention_marker_for_channel_type_features(features: &ChannelTypeFeatures) -> Option<()> {
792 let mut legacy_version_bit_set = ChannelTypeFeatures::only_static_remote_key();
793 legacy_version_bit_set.set_scid_privacy_required();
794 legacy_version_bit_set.set_zero_conf_required();
796 if features.is_subset(&legacy_version_bit_set) {
803 /// Gets the witnessScript for the to_remote output when anchors are enabled.
805 pub fn get_to_countersignatory_with_anchors_redeemscript(payment_point: &PublicKey) -> Script {
807 .push_slice(&payment_point.serialize()[..])
808 .push_opcode(opcodes::all::OP_CHECKSIGVERIFY)
810 .push_opcode(opcodes::all::OP_CSV)
814 /// Gets the witnessScript for an anchor output from the funding public key.
815 /// The witness in the spending input must be:
816 /// <BIP 143 funding_signature>
817 /// After 16 blocks of confirmation, an alternative satisfying witness could be:
819 /// (empty vector required to satisfy compliance with MINIMALIF-standard rule)
821 pub fn get_anchor_redeemscript(funding_pubkey: &PublicKey) -> Script {
822 Builder::new().push_slice(&funding_pubkey.serialize()[..])
823 .push_opcode(opcodes::all::OP_CHECKSIG)
824 .push_opcode(opcodes::all::OP_IFDUP)
825 .push_opcode(opcodes::all::OP_NOTIF)
827 .push_opcode(opcodes::all::OP_CSV)
828 .push_opcode(opcodes::all::OP_ENDIF)
833 /// Locates the output with an anchor script paying to `funding_pubkey` within `commitment_tx`.
834 pub(crate) fn get_anchor_output<'a>(commitment_tx: &'a Transaction, funding_pubkey: &PublicKey) -> Option<(u32, &'a TxOut)> {
835 let anchor_script = chan_utils::get_anchor_redeemscript(funding_pubkey).to_v0_p2wsh();
836 commitment_tx.output.iter().enumerate()
837 .find(|(_, txout)| txout.script_pubkey == anchor_script)
838 .map(|(idx, txout)| (idx as u32, txout))
841 /// Returns the witness required to satisfy and spend an anchor input.
842 pub fn build_anchor_input_witness(funding_key: &PublicKey, funding_sig: &Signature) -> Witness {
843 let anchor_redeem_script = chan_utils::get_anchor_redeemscript(funding_key);
844 let mut ret = Witness::new();
845 ret.push_bitcoin_signature(&funding_sig.serialize_der(), EcdsaSighashType::All);
846 ret.push(anchor_redeem_script.as_bytes());
850 /// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
851 /// The fields are organized by holder/counterparty.
853 /// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
854 /// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
855 #[derive(Clone, Debug, PartialEq, Eq)]
856 pub struct ChannelTransactionParameters {
857 /// Holder public keys
858 pub holder_pubkeys: ChannelPublicKeys,
859 /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
860 pub holder_selected_contest_delay: u16,
861 /// Whether the holder is the initiator of this channel.
862 /// This is an input to the commitment number obscure factor computation.
863 pub is_outbound_from_holder: bool,
864 /// The late-bound counterparty channel transaction parameters.
865 /// These parameters are populated at the point in the protocol where the counterparty provides them.
866 pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
867 /// The late-bound funding outpoint
868 pub funding_outpoint: Option<chain::transaction::OutPoint>,
869 /// This channel's type, as negotiated during channel open. For old objects where this field
870 /// wasn't serialized, it will default to static_remote_key at deserialization.
871 pub channel_type_features: ChannelTypeFeatures
874 /// Late-bound per-channel counterparty data used to build transactions.
875 #[derive(Clone, Debug, PartialEq, Eq)]
876 pub struct CounterpartyChannelTransactionParameters {
877 /// Counter-party public keys
878 pub pubkeys: ChannelPublicKeys,
879 /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
880 pub selected_contest_delay: u16,
883 impl ChannelTransactionParameters {
884 /// Whether the late bound parameters are populated.
885 pub fn is_populated(&self) -> bool {
886 self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
889 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
890 /// given that the holder is the broadcaster.
892 /// self.is_populated() must be true before calling this function.
893 pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
894 assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
895 DirectedChannelTransactionParameters {
897 holder_is_broadcaster: true
901 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
902 /// given that the counterparty is the broadcaster.
904 /// self.is_populated() must be true before calling this function.
905 pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
906 assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
907 DirectedChannelTransactionParameters {
909 holder_is_broadcaster: false
914 impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, {
915 (0, pubkeys, required),
916 (2, selected_contest_delay, required),
919 impl Writeable for ChannelTransactionParameters {
920 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
921 let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
922 write_tlv_fields!(writer, {
923 (0, self.holder_pubkeys, required),
924 (2, self.holder_selected_contest_delay, required),
925 (4, self.is_outbound_from_holder, required),
926 (6, self.counterparty_parameters, option),
927 (8, self.funding_outpoint, option),
928 (10, legacy_deserialization_prevention_marker, option),
929 (11, self.channel_type_features, required),
935 impl Readable for ChannelTransactionParameters {
936 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
937 let mut holder_pubkeys = RequiredWrapper(None);
938 let mut holder_selected_contest_delay = RequiredWrapper(None);
939 let mut is_outbound_from_holder = RequiredWrapper(None);
940 let mut counterparty_parameters = None;
941 let mut funding_outpoint = None;
942 let mut legacy_deserialization_prevention_marker: Option<()> = None;
943 let mut channel_type_features = None;
945 read_tlv_fields!(reader, {
946 (0, holder_pubkeys, required),
947 (2, holder_selected_contest_delay, required),
948 (4, is_outbound_from_holder, required),
949 (6, counterparty_parameters, option),
950 (8, funding_outpoint, option),
951 (10, legacy_deserialization_prevention_marker, option),
952 (11, channel_type_features, option),
956 holder_pubkeys: holder_pubkeys.0.unwrap(),
957 holder_selected_contest_delay: holder_selected_contest_delay.0.unwrap(),
958 is_outbound_from_holder: is_outbound_from_holder.0.unwrap(),
959 counterparty_parameters,
961 channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
966 /// Static channel fields used to build transactions given per-commitment fields, organized by
967 /// broadcaster/countersignatory.
969 /// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
970 /// as_holder_broadcastable and as_counterparty_broadcastable functions.
971 pub struct DirectedChannelTransactionParameters<'a> {
972 /// The holder's channel static parameters
973 inner: &'a ChannelTransactionParameters,
974 /// Whether the holder is the broadcaster
975 holder_is_broadcaster: bool,
978 impl<'a> DirectedChannelTransactionParameters<'a> {
979 /// Get the channel pubkeys for the broadcaster
980 pub fn broadcaster_pubkeys(&self) -> &ChannelPublicKeys {
981 if self.holder_is_broadcaster {
982 &self.inner.holder_pubkeys
984 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
988 /// Get the channel pubkeys for the countersignatory
989 pub fn countersignatory_pubkeys(&self) -> &ChannelPublicKeys {
990 if self.holder_is_broadcaster {
991 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
993 &self.inner.holder_pubkeys
997 /// Get the contest delay applicable to the transactions.
998 /// Note that the contest delay was selected by the countersignatory.
999 pub fn contest_delay(&self) -> u16 {
1000 let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
1001 if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
1004 /// Whether the channel is outbound from the broadcaster.
1006 /// The boolean representing the side that initiated the channel is
1007 /// an input to the commitment number obscure factor computation.
1008 pub fn is_outbound(&self) -> bool {
1009 if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
1012 /// The funding outpoint
1013 pub fn funding_outpoint(&self) -> OutPoint {
1014 self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
1017 /// Whether to use anchors for this channel
1018 pub fn channel_type_features(&self) -> &ChannelTypeFeatures {
1019 &self.inner.channel_type_features
1023 /// Information needed to build and sign a holder's commitment transaction.
1025 /// The transaction is only signed once we are ready to broadcast.
1027 pub struct HolderCommitmentTransaction {
1028 inner: CommitmentTransaction,
1029 /// Our counterparty's signature for the transaction
1030 pub counterparty_sig: Signature,
1031 /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
1032 pub counterparty_htlc_sigs: Vec<Signature>,
1033 // Which order the signatures should go in when constructing the final commitment tx witness.
1034 // The user should be able to reconstruct this themselves, so we don't bother to expose it.
1035 holder_sig_first: bool,
1038 impl Deref for HolderCommitmentTransaction {
1039 type Target = CommitmentTransaction;
1041 fn deref(&self) -> &Self::Target { &self.inner }
1044 impl Eq for HolderCommitmentTransaction {}
1045 impl PartialEq for HolderCommitmentTransaction {
1046 // We dont care whether we are signed in equality comparison
1047 fn eq(&self, o: &Self) -> bool {
1048 self.inner == o.inner
1052 impl_writeable_tlv_based!(HolderCommitmentTransaction, {
1053 (0, inner, required),
1054 (2, counterparty_sig, required),
1055 (4, holder_sig_first, required),
1056 (6, counterparty_htlc_sigs, vec_type),
1059 impl HolderCommitmentTransaction {
1061 pub fn dummy(htlcs: &mut Vec<(HTLCOutputInCommitment, ())>) -> Self {
1062 let secp_ctx = Secp256k1::new();
1063 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1064 let dummy_sig = sign(&secp_ctx, &secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
1066 let keys = TxCreationKeys {
1067 per_commitment_point: dummy_key.clone(),
1068 revocation_key: dummy_key.clone(),
1069 broadcaster_htlc_key: dummy_key.clone(),
1070 countersignatory_htlc_key: dummy_key.clone(),
1071 broadcaster_delayed_payment_key: dummy_key.clone(),
1073 let channel_pubkeys = ChannelPublicKeys {
1074 funding_pubkey: dummy_key.clone(),
1075 revocation_basepoint: dummy_key.clone(),
1076 payment_point: dummy_key.clone(),
1077 delayed_payment_basepoint: dummy_key.clone(),
1078 htlc_basepoint: dummy_key.clone()
1080 let channel_parameters = ChannelTransactionParameters {
1081 holder_pubkeys: channel_pubkeys.clone(),
1082 holder_selected_contest_delay: 0,
1083 is_outbound_from_holder: false,
1084 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
1085 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1086 channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
1088 let mut counterparty_htlc_sigs = Vec::new();
1089 for _ in 0..htlcs.len() {
1090 counterparty_htlc_sigs.push(dummy_sig);
1092 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());
1093 htlcs.sort_by_key(|htlc| htlc.0.transaction_output_index);
1094 HolderCommitmentTransaction {
1096 counterparty_sig: dummy_sig,
1097 counterparty_htlc_sigs,
1098 holder_sig_first: false
1102 /// Create a new holder transaction with the given counterparty signatures.
1103 /// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
1104 pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
1106 inner: commitment_tx,
1108 counterparty_htlc_sigs,
1109 holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
1113 pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
1114 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
1115 let mut tx = self.inner.built.transaction.clone();
1116 tx.input[0].witness.push(Vec::new());
1118 if self.holder_sig_first {
1119 tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1120 tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1122 tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1123 tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1126 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
1131 /// A pre-built Bitcoin commitment transaction and its txid.
1133 pub struct BuiltCommitmentTransaction {
1134 /// The commitment transaction
1135 pub transaction: Transaction,
1136 /// The txid for the commitment transaction.
1138 /// This is provided as a performance optimization, instead of calling transaction.txid()
1143 impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
1144 (0, transaction, required),
1145 (2, txid, required),
1148 impl BuiltCommitmentTransaction {
1149 /// Get the SIGHASH_ALL sighash value of the transaction.
1151 /// This can be used to verify a signature.
1152 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1153 let sighash = &sighash::SighashCache::new(&self.transaction).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1154 hash_to_message!(sighash)
1157 /// Signs the counterparty's commitment transaction.
1158 pub fn sign_counterparty_commitment<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1159 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1160 sign(secp_ctx, &sighash, funding_key)
1163 /// Signs the holder commitment transaction because we are about to broadcast it.
1164 pub fn sign_holder_commitment<T: secp256k1::Signing, ES: Deref>(
1165 &self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64,
1166 entropy_source: &ES, secp_ctx: &Secp256k1<T>
1167 ) -> Signature where ES::Target: EntropySource {
1168 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1169 sign_with_aux_rand(secp_ctx, &sighash, funding_key, entropy_source)
1173 /// This class tracks the per-transaction information needed to build a closing transaction and will
1174 /// actually build it and sign.
1176 /// This class can be used inside a signer implementation to generate a signature given the relevant
1178 #[derive(Clone, Hash, PartialEq, Eq)]
1179 pub struct ClosingTransaction {
1180 to_holder_value_sat: u64,
1181 to_counterparty_value_sat: u64,
1182 to_holder_script: Script,
1183 to_counterparty_script: Script,
1187 impl ClosingTransaction {
1188 /// Construct an object of the class
1190 to_holder_value_sat: u64,
1191 to_counterparty_value_sat: u64,
1192 to_holder_script: Script,
1193 to_counterparty_script: Script,
1194 funding_outpoint: OutPoint,
1196 let built = build_closing_transaction(
1197 to_holder_value_sat, to_counterparty_value_sat,
1198 to_holder_script.clone(), to_counterparty_script.clone(),
1201 ClosingTransaction {
1202 to_holder_value_sat,
1203 to_counterparty_value_sat,
1205 to_counterparty_script,
1210 /// Trust our pre-built transaction.
1212 /// Applies a wrapper which allows access to the transaction.
1214 /// This should only be used if you fully trust the builder of this object. It should not
1215 /// be used by an external signer - instead use the verify function.
1216 pub fn trust(&self) -> TrustedClosingTransaction {
1217 TrustedClosingTransaction { inner: self }
1220 /// Verify our pre-built transaction.
1222 /// Applies a wrapper which allows access to the transaction.
1224 /// An external validating signer must call this method before signing
1225 /// or using the built transaction.
1226 pub fn verify(&self, funding_outpoint: OutPoint) -> Result<TrustedClosingTransaction, ()> {
1227 let built = build_closing_transaction(
1228 self.to_holder_value_sat, self.to_counterparty_value_sat,
1229 self.to_holder_script.clone(), self.to_counterparty_script.clone(),
1232 if self.built != built {
1235 Ok(TrustedClosingTransaction { inner: self })
1238 /// The value to be sent to the holder, or zero if the output will be omitted
1239 pub fn to_holder_value_sat(&self) -> u64 {
1240 self.to_holder_value_sat
1243 /// The value to be sent to the counterparty, or zero if the output will be omitted
1244 pub fn to_counterparty_value_sat(&self) -> u64 {
1245 self.to_counterparty_value_sat
1248 /// The destination of the holder's output
1249 pub fn to_holder_script(&self) -> &Script {
1250 &self.to_holder_script
1253 /// The destination of the counterparty's output
1254 pub fn to_counterparty_script(&self) -> &Script {
1255 &self.to_counterparty_script
1259 /// A wrapper on ClosingTransaction indicating that the built bitcoin
1260 /// transaction is trusted.
1262 /// See trust() and verify() functions on CommitmentTransaction.
1264 /// This structure implements Deref.
1265 pub struct TrustedClosingTransaction<'a> {
1266 inner: &'a ClosingTransaction,
1269 impl<'a> Deref for TrustedClosingTransaction<'a> {
1270 type Target = ClosingTransaction;
1272 fn deref(&self) -> &Self::Target { self.inner }
1275 impl<'a> TrustedClosingTransaction<'a> {
1276 /// The pre-built Bitcoin commitment transaction
1277 pub fn built_transaction(&self) -> &Transaction {
1281 /// Get the SIGHASH_ALL sighash value of the transaction.
1283 /// This can be used to verify a signature.
1284 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1285 let sighash = &sighash::SighashCache::new(&self.inner.built).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1286 hash_to_message!(sighash)
1289 /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1290 /// because we are about to broadcast a holder transaction.
1291 pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1292 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1293 sign(secp_ctx, &sighash, funding_key)
1297 /// This class tracks the per-transaction information needed to build a commitment transaction and will
1298 /// actually build it and sign. It is used for holder transactions that we sign only when needed
1299 /// and for transactions we sign for the counterparty.
1301 /// This class can be used inside a signer implementation to generate a signature given the relevant
1304 pub struct CommitmentTransaction {
1305 commitment_number: u64,
1306 to_broadcaster_value_sat: u64,
1307 to_countersignatory_value_sat: u64,
1308 feerate_per_kw: u32,
1309 htlcs: Vec<HTLCOutputInCommitment>,
1310 // Note that on upgrades, some features of existing outputs may be missed.
1311 channel_type_features: ChannelTypeFeatures,
1312 // A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
1313 keys: TxCreationKeys,
1314 // For access to the pre-built transaction, see doc for trust()
1315 built: BuiltCommitmentTransaction,
1318 impl Eq for CommitmentTransaction {}
1319 impl PartialEq for CommitmentTransaction {
1320 fn eq(&self, o: &Self) -> bool {
1321 let eq = self.commitment_number == o.commitment_number &&
1322 self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
1323 self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
1324 self.feerate_per_kw == o.feerate_per_kw &&
1325 self.htlcs == o.htlcs &&
1326 self.channel_type_features == o.channel_type_features &&
1327 self.keys == o.keys;
1329 debug_assert_eq!(self.built.transaction, o.built.transaction);
1330 debug_assert_eq!(self.built.txid, o.built.txid);
1336 impl Writeable for CommitmentTransaction {
1337 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1338 let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
1339 write_tlv_fields!(writer, {
1340 (0, self.commitment_number, required),
1341 (2, self.to_broadcaster_value_sat, required),
1342 (4, self.to_countersignatory_value_sat, required),
1343 (6, self.feerate_per_kw, required),
1344 (8, self.keys, required),
1345 (10, self.built, required),
1346 (12, self.htlcs, vec_type),
1347 (14, legacy_deserialization_prevention_marker, option),
1348 (15, self.channel_type_features, required),
1354 impl Readable for CommitmentTransaction {
1355 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1356 let mut commitment_number = RequiredWrapper(None);
1357 let mut to_broadcaster_value_sat = RequiredWrapper(None);
1358 let mut to_countersignatory_value_sat = RequiredWrapper(None);
1359 let mut feerate_per_kw = RequiredWrapper(None);
1360 let mut keys = RequiredWrapper(None);
1361 let mut built = RequiredWrapper(None);
1362 _init_tlv_field_var!(htlcs, vec_type);
1363 let mut legacy_deserialization_prevention_marker: Option<()> = None;
1364 let mut channel_type_features = None;
1366 read_tlv_fields!(reader, {
1367 (0, commitment_number, required),
1368 (2, to_broadcaster_value_sat, required),
1369 (4, to_countersignatory_value_sat, required),
1370 (6, feerate_per_kw, required),
1371 (8, keys, required),
1372 (10, built, required),
1373 (12, htlcs, vec_type),
1374 (14, legacy_deserialization_prevention_marker, option),
1375 (15, channel_type_features, option),
1379 commitment_number: commitment_number.0.unwrap(),
1380 to_broadcaster_value_sat: to_broadcaster_value_sat.0.unwrap(),
1381 to_countersignatory_value_sat: to_countersignatory_value_sat.0.unwrap(),
1382 feerate_per_kw: feerate_per_kw.0.unwrap(),
1383 keys: keys.0.unwrap(),
1384 built: built.0.unwrap(),
1385 htlcs: _init_tlv_based_struct_field!(htlcs, vec_type),
1386 channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
1391 impl CommitmentTransaction {
1392 /// Construct an object of the class while assigning transaction output indices to HTLCs.
1394 /// Populates HTLCOutputInCommitment.transaction_output_index in htlcs_with_aux.
1396 /// The generic T allows the caller to match the HTLC output index with auxiliary data.
1397 /// This auxiliary data is not stored in this object.
1399 /// Only include HTLCs that are above the dust limit for the channel.
1401 /// This is not exported to bindings users due to the generic though we likely should expose a version without
1402 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 {
1403 // Sort outputs and populate output indices while keeping track of the auxiliary data
1404 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();
1406 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
1407 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1408 let txid = transaction.txid();
1409 CommitmentTransaction {
1411 to_broadcaster_value_sat,
1412 to_countersignatory_value_sat,
1415 channel_type_features: channel_parameters.channel_type_features().clone(),
1417 built: BuiltCommitmentTransaction {
1424 /// Use non-zero fee anchors
1426 /// This is not exported to bindings users due to move, and also not likely to be useful for binding users
1427 pub fn with_non_zero_fee_anchors(mut self) -> Self {
1428 self.channel_type_features.set_anchors_nonzero_fee_htlc_tx_required();
1432 fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<BuiltCommitmentTransaction, ()> {
1433 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
1435 let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
1436 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)?;
1438 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1439 let txid = transaction.txid();
1440 let built_transaction = BuiltCommitmentTransaction {
1444 Ok(built_transaction)
1447 fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
1450 lock_time: PackedLockTime(((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32)),
1456 // This is used in two cases:
1457 // - initial sorting of outputs / HTLCs in the constructor, in which case T is auxiliary data the
1458 // caller needs to have sorted together with the HTLCs so it can keep track of the output index
1459 // - building of a bitcoin transaction during a verify() call, in which case T is just ()
1460 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>), ()> {
1461 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1462 let contest_delay = channel_parameters.contest_delay();
1464 let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
1466 if to_countersignatory_value_sat > 0 {
1467 let script = if channel_parameters.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
1468 get_to_countersignatory_with_anchors_redeemscript(&countersignatory_pubkeys.payment_point).to_v0_p2wsh()
1470 Payload::p2wpkh(&BitcoinPublicKey::new(countersignatory_pubkeys.payment_point)).unwrap().script_pubkey()
1474 script_pubkey: script.clone(),
1475 value: to_countersignatory_value_sat,
1481 if to_broadcaster_value_sat > 0 {
1482 let redeem_script = get_revokeable_redeemscript(
1483 &keys.revocation_key,
1485 &keys.broadcaster_delayed_payment_key,
1489 script_pubkey: redeem_script.to_v0_p2wsh(),
1490 value: to_broadcaster_value_sat,
1496 if channel_parameters.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
1497 if to_broadcaster_value_sat > 0 || !htlcs_with_aux.is_empty() {
1498 let anchor_script = get_anchor_redeemscript(broadcaster_funding_key);
1501 script_pubkey: anchor_script.to_v0_p2wsh(),
1502 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1508 if to_countersignatory_value_sat > 0 || !htlcs_with_aux.is_empty() {
1509 let anchor_script = get_anchor_redeemscript(countersignatory_funding_key);
1512 script_pubkey: anchor_script.to_v0_p2wsh(),
1513 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1520 let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
1521 for (htlc, _) in htlcs_with_aux {
1522 let script = chan_utils::get_htlc_redeemscript(&htlc, &channel_parameters.channel_type_features(), &keys);
1524 script_pubkey: script.to_v0_p2wsh(),
1525 value: htlc.amount_msat / 1000,
1527 txouts.push((txout, Some(htlc)));
1530 // Sort output in BIP-69 order (amount, scriptPubkey). Tie-breaks based on HTLC
1531 // CLTV expiration height.
1532 sort_outputs(&mut txouts, |a, b| {
1533 if let &Some(ref a_htlcout) = a {
1534 if let &Some(ref b_htlcout) = b {
1535 a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
1536 // Note that due to hash collisions, we have to have a fallback comparison
1537 // here for fuzzing mode (otherwise at least chanmon_fail_consistency
1539 .then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
1540 // For non-HTLC outputs, if they're copying our SPK we don't really care if we
1541 // close the channel due to mismatches - they're doing something dumb:
1542 } else { cmp::Ordering::Equal }
1543 } else { cmp::Ordering::Equal }
1546 let mut outputs = Vec::with_capacity(txouts.len());
1547 for (idx, out) in txouts.drain(..).enumerate() {
1548 if let Some(htlc) = out.1 {
1549 htlc.transaction_output_index = Some(idx as u32);
1550 htlcs.push(htlc.clone());
1552 outputs.push(out.0);
1554 Ok((outputs, htlcs))
1557 fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
1558 let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
1559 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1560 let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
1561 &broadcaster_pubkeys.payment_point,
1562 &countersignatory_pubkeys.payment_point,
1563 channel_parameters.is_outbound(),
1566 let obscured_commitment_transaction_number =
1567 commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
1570 let mut ins: Vec<TxIn> = Vec::new();
1572 previous_output: channel_parameters.funding_outpoint(),
1573 script_sig: Script::new(),
1574 sequence: Sequence(((0x80 as u32) << 8 * 3)
1575 | ((obscured_commitment_transaction_number >> 3 * 8) as u32)),
1576 witness: Witness::new(),
1580 (obscured_commitment_transaction_number, txins)
1583 /// The backwards-counting commitment number
1584 pub fn commitment_number(&self) -> u64 {
1585 self.commitment_number
1588 /// The value to be sent to the broadcaster
1589 pub fn to_broadcaster_value_sat(&self) -> u64 {
1590 self.to_broadcaster_value_sat
1593 /// The value to be sent to the counterparty
1594 pub fn to_countersignatory_value_sat(&self) -> u64 {
1595 self.to_countersignatory_value_sat
1598 /// The feerate paid per 1000-weight-unit in this commitment transaction.
1599 pub fn feerate_per_kw(&self) -> u32 {
1603 /// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
1604 /// which were included in this commitment transaction in output order.
1605 /// The transaction index is always populated.
1607 /// This is not exported to bindings users as we cannot currently convert Vec references to/from C, though we should
1608 /// expose a less effecient version which creates a Vec of references in the future.
1609 pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
1613 /// Trust our pre-built transaction and derived transaction creation public keys.
1615 /// Applies a wrapper which allows access to these fields.
1617 /// This should only be used if you fully trust the builder of this object. It should not
1618 /// be used by an external signer - instead use the verify function.
1619 pub fn trust(&self) -> TrustedCommitmentTransaction {
1620 TrustedCommitmentTransaction { inner: self }
1623 /// Verify our pre-built transaction and derived transaction creation public keys.
1625 /// Applies a wrapper which allows access to these fields.
1627 /// An external validating signer must call this method before signing
1628 /// or using the built transaction.
1629 pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
1630 // This is the only field of the key cache that we trust
1631 let per_commitment_point = self.keys.per_commitment_point;
1632 let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx);
1633 if keys != self.keys {
1636 let tx = self.internal_rebuild_transaction(&keys, channel_parameters, &broadcaster_keys.funding_pubkey, &countersignatory_keys.funding_pubkey)?;
1637 if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
1640 Ok(TrustedCommitmentTransaction { inner: self })
1644 /// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
1645 /// transaction and the transaction creation keys) are trusted.
1647 /// See trust() and verify() functions on CommitmentTransaction.
1649 /// This structure implements Deref.
1650 pub struct TrustedCommitmentTransaction<'a> {
1651 inner: &'a CommitmentTransaction,
1654 impl<'a> Deref for TrustedCommitmentTransaction<'a> {
1655 type Target = CommitmentTransaction;
1657 fn deref(&self) -> &Self::Target { self.inner }
1660 impl<'a> TrustedCommitmentTransaction<'a> {
1661 /// The transaction ID of the built Bitcoin transaction
1662 pub fn txid(&self) -> Txid {
1663 self.inner.built.txid
1666 /// The pre-built Bitcoin commitment transaction
1667 pub fn built_transaction(&self) -> &BuiltCommitmentTransaction {
1671 /// The pre-calculated transaction creation public keys.
1672 pub fn keys(&self) -> &TxCreationKeys {
1676 /// Should anchors be used.
1677 pub fn channel_type_features(&self) -> &ChannelTypeFeatures {
1678 &self.inner.channel_type_features
1681 /// Get a signature for each HTLC which was included in the commitment transaction (ie for
1682 /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
1684 /// The returned Vec has one entry for each HTLC, and in the same order.
1686 /// This function is only valid in the holder commitment context, it always uses EcdsaSighashType::All.
1687 pub fn get_htlc_sigs<T: secp256k1::Signing, ES: Deref>(
1688 &self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters,
1689 entropy_source: &ES, secp_ctx: &Secp256k1<T>,
1690 ) -> Result<Vec<Signature>, ()> where ES::Target: EntropySource {
1691 let inner = self.inner;
1692 let keys = &inner.keys;
1693 let txid = inner.built.txid;
1694 let mut ret = Vec::with_capacity(inner.htlcs.len());
1695 let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key);
1697 for this_htlc in inner.htlcs.iter() {
1698 assert!(this_htlc.transaction_output_index.is_some());
1699 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);
1701 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);
1703 let sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, EcdsaSighashType::All).unwrap()[..]);
1704 ret.push(sign_with_aux_rand(secp_ctx, &sighash, &holder_htlc_key, entropy_source));
1709 /// Gets a signed HTLC transaction given a preimage (for !htlc.offered) and the holder HTLC transaction signature.
1710 pub(crate) fn get_signed_htlc_tx(&self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature, preimage: &Option<PaymentPreimage>) -> Transaction {
1711 let inner = self.inner;
1712 let keys = &inner.keys;
1713 let txid = inner.built.txid;
1714 let this_htlc = &inner.htlcs[htlc_index];
1715 assert!(this_htlc.transaction_output_index.is_some());
1716 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
1717 if !this_htlc.offered && preimage.is_none() { unreachable!(); }
1718 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
1719 if this_htlc.offered && preimage.is_some() { unreachable!(); }
1721 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);
1723 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);
1725 htlc_tx.input[0].witness = chan_utils::build_htlc_input_witness(
1726 signature, counterparty_signature, preimage, &htlc_redeemscript, &self.channel_type_features,
1732 /// Commitment transaction numbers which appear in the transactions themselves are XOR'd with a
1733 /// shared secret first. This prevents on-chain observers from discovering how many commitment
1734 /// transactions occurred in a channel before it was closed.
1736 /// This function gets the shared secret from relevant channel public keys and can be used to
1737 /// "decrypt" the commitment transaction number given a commitment transaction on-chain.
1738 pub fn get_commitment_transaction_number_obscure_factor(
1739 broadcaster_payment_basepoint: &PublicKey,
1740 countersignatory_payment_basepoint: &PublicKey,
1741 outbound_from_broadcaster: bool,
1743 let mut sha = Sha256::engine();
1745 if outbound_from_broadcaster {
1746 sha.input(&broadcaster_payment_basepoint.serialize());
1747 sha.input(&countersignatory_payment_basepoint.serialize());
1749 sha.input(&countersignatory_payment_basepoint.serialize());
1750 sha.input(&broadcaster_payment_basepoint.serialize());
1752 let res = Sha256::from_engine(sha).into_inner();
1754 ((res[26] as u64) << 5 * 8)
1755 | ((res[27] as u64) << 4 * 8)
1756 | ((res[28] as u64) << 3 * 8)
1757 | ((res[29] as u64) << 2 * 8)
1758 | ((res[30] as u64) << 1 * 8)
1759 | ((res[31] as u64) << 0 * 8)
1764 use super::CounterpartyCommitmentSecrets;
1765 use crate::{hex, chain};
1766 use crate::prelude::*;
1767 use crate::ln::chan_utils::{get_htlc_redeemscript, get_to_countersignatory_with_anchors_redeemscript, CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
1768 use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
1769 use crate::util::test_utils;
1770 use crate::sign::{ChannelSigner, SignerProvider};
1771 use bitcoin::{Network, Txid};
1772 use bitcoin::hashes::Hash;
1773 use crate::ln::PaymentHash;
1774 use bitcoin::hashes::hex::ToHex;
1775 use bitcoin::util::address::Payload;
1776 use bitcoin::PublicKey as BitcoinPublicKey;
1777 use crate::ln::features::ChannelTypeFeatures;
1781 let secp_ctx = Secp256k1::new();
1783 let seed = [42; 32];
1784 let network = Network::Testnet;
1785 let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
1786 let signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(false, 1_000_000, 0));
1787 let counterparty_signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(true, 1_000_000, 1));
1788 let delayed_payment_base = &signer.pubkeys().delayed_payment_basepoint;
1789 let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
1790 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
1791 let htlc_basepoint = &signer.pubkeys().htlc_basepoint;
1792 let holder_pubkeys = signer.pubkeys();
1793 let counterparty_pubkeys = counterparty_signer.pubkeys();
1794 let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint);
1795 let mut channel_parameters = ChannelTransactionParameters {
1796 holder_pubkeys: holder_pubkeys.clone(),
1797 holder_selected_contest_delay: 0,
1798 is_outbound_from_holder: false,
1799 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: counterparty_pubkeys.clone(), selected_contest_delay: 0 }),
1800 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1801 channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
1804 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
1806 // Generate broadcaster and counterparty outputs
1807 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1809 holder_pubkeys.funding_pubkey,
1810 counterparty_pubkeys.funding_pubkey,
1812 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1814 assert_eq!(tx.built.transaction.output.len(), 2);
1815 assert_eq!(tx.built.transaction.output[1].script_pubkey, Payload::p2wpkh(&BitcoinPublicKey::new(counterparty_pubkeys.payment_point)).unwrap().script_pubkey());
1817 // Generate broadcaster and counterparty outputs as well as two anchors
1818 channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
1819 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1821 holder_pubkeys.funding_pubkey,
1822 counterparty_pubkeys.funding_pubkey,
1824 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1826 assert_eq!(tx.built.transaction.output.len(), 4);
1827 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_to_countersignatory_with_anchors_redeemscript(&counterparty_pubkeys.payment_point).to_v0_p2wsh());
1829 // Generate broadcaster output and anchor
1830 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1832 holder_pubkeys.funding_pubkey,
1833 counterparty_pubkeys.funding_pubkey,
1835 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1837 assert_eq!(tx.built.transaction.output.len(), 2);
1839 // Generate counterparty output and anchor
1840 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1842 holder_pubkeys.funding_pubkey,
1843 counterparty_pubkeys.funding_pubkey,
1845 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1847 assert_eq!(tx.built.transaction.output.len(), 2);
1849 let received_htlc = HTLCOutputInCommitment {
1851 amount_msat: 400000,
1853 payment_hash: PaymentHash([42; 32]),
1854 transaction_output_index: None,
1857 let offered_htlc = HTLCOutputInCommitment {
1859 amount_msat: 600000,
1861 payment_hash: PaymentHash([43; 32]),
1862 transaction_output_index: None,
1865 // Generate broadcaster output and received and offered HTLC outputs, w/o anchors
1866 channel_parameters.channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1867 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1869 holder_pubkeys.funding_pubkey,
1870 counterparty_pubkeys.funding_pubkey,
1872 &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1873 &channel_parameters.as_holder_broadcastable()
1875 assert_eq!(tx.built.transaction.output.len(), 3);
1876 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh());
1877 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh());
1878 assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh().to_hex(),
1879 "0020e43a7c068553003fe68fcae424fb7b28ec5ce48cd8b6744b3945631389bad2fb");
1880 assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh().to_hex(),
1881 "0020215d61bba56b19e9eadb6107f5a85d7f99c40f65992443f69229c290165bc00d");
1883 // Generate broadcaster output and received and offered HTLC outputs, with anchors
1884 channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
1885 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1887 holder_pubkeys.funding_pubkey,
1888 counterparty_pubkeys.funding_pubkey,
1890 &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1891 &channel_parameters.as_holder_broadcastable()
1893 assert_eq!(tx.built.transaction.output.len(), 5);
1894 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());
1895 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());
1896 assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_v0_p2wsh().to_hex(),
1897 "0020b70d0649c72b38756885c7a30908d912a7898dd5d79457a7280b8e9a20f3f2bc");
1898 assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_v0_p2wsh().to_hex(),
1899 "002087a3faeb1950a469c0e2db4a79b093a41b9526e5a6fc6ef5cb949bde3be379c7");
1903 fn test_per_commitment_storage() {
1904 // Test vectors from BOLT 3:
1905 let mut secrets: Vec<[u8; 32]> = Vec::new();
1908 macro_rules! test_secrets {
1910 let mut idx = 281474976710655;
1911 for secret in secrets.iter() {
1912 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1915 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1916 assert!(monitor.get_secret(idx).is_none());
1921 // insert_secret correct sequence
1922 monitor = CounterpartyCommitmentSecrets::new();
1925 secrets.push([0; 32]);
1926 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1927 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1930 secrets.push([0; 32]);
1931 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1932 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1935 secrets.push([0; 32]);
1936 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1937 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1940 secrets.push([0; 32]);
1941 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1942 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1945 secrets.push([0; 32]);
1946 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1947 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1950 secrets.push([0; 32]);
1951 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1952 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1955 secrets.push([0; 32]);
1956 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1957 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1960 secrets.push([0; 32]);
1961 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1962 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
1967 // insert_secret #1 incorrect
1968 monitor = CounterpartyCommitmentSecrets::new();
1971 secrets.push([0; 32]);
1972 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1973 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1976 secrets.push([0; 32]);
1977 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1978 assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
1982 // insert_secret #2 incorrect (#1 derived from incorrect)
1983 monitor = CounterpartyCommitmentSecrets::new();
1986 secrets.push([0; 32]);
1987 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1988 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1991 secrets.push([0; 32]);
1992 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1993 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1996 secrets.push([0; 32]);
1997 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1998 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2001 secrets.push([0; 32]);
2002 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2003 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
2007 // insert_secret #3 incorrect
2008 monitor = CounterpartyCommitmentSecrets::new();
2011 secrets.push([0; 32]);
2012 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2013 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2016 secrets.push([0; 32]);
2017 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2018 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2021 secrets.push([0; 32]);
2022 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2023 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2026 secrets.push([0; 32]);
2027 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2028 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
2032 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
2033 monitor = CounterpartyCommitmentSecrets::new();
2036 secrets.push([0; 32]);
2037 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2038 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2041 secrets.push([0; 32]);
2042 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2043 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2046 secrets.push([0; 32]);
2047 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2048 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2051 secrets.push([0; 32]);
2052 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
2053 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2056 secrets.push([0; 32]);
2057 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2058 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2061 secrets.push([0; 32]);
2062 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2063 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2066 secrets.push([0; 32]);
2067 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2068 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2071 secrets.push([0; 32]);
2072 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2073 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2077 // insert_secret #5 incorrect
2078 monitor = CounterpartyCommitmentSecrets::new();
2081 secrets.push([0; 32]);
2082 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2083 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2086 secrets.push([0; 32]);
2087 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2088 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2091 secrets.push([0; 32]);
2092 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2093 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2096 secrets.push([0; 32]);
2097 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2098 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2101 secrets.push([0; 32]);
2102 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2103 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2106 secrets.push([0; 32]);
2107 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2108 assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
2112 // insert_secret #6 incorrect (5 derived from incorrect)
2113 monitor = CounterpartyCommitmentSecrets::new();
2116 secrets.push([0; 32]);
2117 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2118 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2121 secrets.push([0; 32]);
2122 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2123 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2126 secrets.push([0; 32]);
2127 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2128 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2131 secrets.push([0; 32]);
2132 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2133 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2136 secrets.push([0; 32]);
2137 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2138 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2141 secrets.push([0; 32]);
2142 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
2143 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2146 secrets.push([0; 32]);
2147 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2148 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2151 secrets.push([0; 32]);
2152 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2153 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2157 // insert_secret #7 incorrect
2158 monitor = CounterpartyCommitmentSecrets::new();
2161 secrets.push([0; 32]);
2162 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2163 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2166 secrets.push([0; 32]);
2167 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2168 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2171 secrets.push([0; 32]);
2172 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2173 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2176 secrets.push([0; 32]);
2177 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2178 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2181 secrets.push([0; 32]);
2182 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2183 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2186 secrets.push([0; 32]);
2187 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2188 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2191 secrets.push([0; 32]);
2192 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2193 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2196 secrets.push([0; 32]);
2197 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2198 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2202 // insert_secret #8 incorrect
2203 monitor = CounterpartyCommitmentSecrets::new();
2206 secrets.push([0; 32]);
2207 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2208 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2211 secrets.push([0; 32]);
2212 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2213 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2216 secrets.push([0; 32]);
2217 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2218 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2221 secrets.push([0; 32]);
2222 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2223 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2226 secrets.push([0; 32]);
2227 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2228 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2231 secrets.push([0; 32]);
2232 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2233 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2236 secrets.push([0; 32]);
2237 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2238 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2241 secrets.push([0; 32]);
2242 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2243 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());