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)
832 /// Locates the output with an anchor script paying to `funding_pubkey` within `commitment_tx`.
833 pub(crate) fn get_anchor_output<'a>(commitment_tx: &'a Transaction, funding_pubkey: &PublicKey) -> Option<(u32, &'a TxOut)> {
834 let anchor_script = chan_utils::get_anchor_redeemscript(funding_pubkey).to_v0_p2wsh();
835 commitment_tx.output.iter().enumerate()
836 .find(|(_, txout)| txout.script_pubkey == anchor_script)
837 .map(|(idx, txout)| (idx as u32, txout))
840 /// Returns the witness required to satisfy and spend an anchor input.
841 pub fn build_anchor_input_witness(funding_key: &PublicKey, funding_sig: &Signature) -> Witness {
842 let anchor_redeem_script = chan_utils::get_anchor_redeemscript(funding_key);
843 let mut ret = Witness::new();
844 ret.push_bitcoin_signature(&funding_sig.serialize_der(), EcdsaSighashType::All);
845 ret.push(anchor_redeem_script.as_bytes());
849 /// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
850 /// The fields are organized by holder/counterparty.
852 /// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
853 /// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
854 #[derive(Clone, Debug, PartialEq, Eq)]
855 pub struct ChannelTransactionParameters {
856 /// Holder public keys
857 pub holder_pubkeys: ChannelPublicKeys,
858 /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
859 pub holder_selected_contest_delay: u16,
860 /// Whether the holder is the initiator of this channel.
861 /// This is an input to the commitment number obscure factor computation.
862 pub is_outbound_from_holder: bool,
863 /// The late-bound counterparty channel transaction parameters.
864 /// These parameters are populated at the point in the protocol where the counterparty provides them.
865 pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
866 /// The late-bound funding outpoint
867 pub funding_outpoint: Option<chain::transaction::OutPoint>,
868 /// This channel's type, as negotiated during channel open. For old objects where this field
869 /// wasn't serialized, it will default to static_remote_key at deserialization.
870 pub channel_type_features: ChannelTypeFeatures
873 /// Late-bound per-channel counterparty data used to build transactions.
874 #[derive(Clone, Debug, PartialEq, Eq)]
875 pub struct CounterpartyChannelTransactionParameters {
876 /// Counter-party public keys
877 pub pubkeys: ChannelPublicKeys,
878 /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
879 pub selected_contest_delay: u16,
882 impl ChannelTransactionParameters {
883 /// Whether the late bound parameters are populated.
884 pub fn is_populated(&self) -> bool {
885 self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
888 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
889 /// given that the holder is the broadcaster.
891 /// self.is_populated() must be true before calling this function.
892 pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
893 assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
894 DirectedChannelTransactionParameters {
896 holder_is_broadcaster: true
900 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
901 /// given that the counterparty is the broadcaster.
903 /// self.is_populated() must be true before calling this function.
904 pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
905 assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
906 DirectedChannelTransactionParameters {
908 holder_is_broadcaster: false
913 impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, {
914 (0, pubkeys, required),
915 (2, selected_contest_delay, required),
918 impl Writeable for ChannelTransactionParameters {
919 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
920 let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
921 write_tlv_fields!(writer, {
922 (0, self.holder_pubkeys, required),
923 (2, self.holder_selected_contest_delay, required),
924 (4, self.is_outbound_from_holder, required),
925 (6, self.counterparty_parameters, option),
926 (8, self.funding_outpoint, option),
927 (10, legacy_deserialization_prevention_marker, option),
928 (11, self.channel_type_features, required),
934 impl Readable for ChannelTransactionParameters {
935 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
936 let mut holder_pubkeys = RequiredWrapper(None);
937 let mut holder_selected_contest_delay = RequiredWrapper(None);
938 let mut is_outbound_from_holder = RequiredWrapper(None);
939 let mut counterparty_parameters = None;
940 let mut funding_outpoint = None;
941 let mut _legacy_deserialization_prevention_marker: Option<()> = None;
942 let mut channel_type_features = None;
944 read_tlv_fields!(reader, {
945 (0, holder_pubkeys, required),
946 (2, holder_selected_contest_delay, required),
947 (4, is_outbound_from_holder, required),
948 (6, counterparty_parameters, option),
949 (8, funding_outpoint, option),
950 (10, _legacy_deserialization_prevention_marker, option),
951 (11, channel_type_features, option),
954 let mut additional_features = ChannelTypeFeatures::empty();
955 additional_features.set_anchors_nonzero_fee_htlc_tx_required();
956 chain::package::verify_channel_type_features(&channel_type_features, Some(&additional_features))?;
959 holder_pubkeys: holder_pubkeys.0.unwrap(),
960 holder_selected_contest_delay: holder_selected_contest_delay.0.unwrap(),
961 is_outbound_from_holder: is_outbound_from_holder.0.unwrap(),
962 counterparty_parameters,
964 channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
969 /// Static channel fields used to build transactions given per-commitment fields, organized by
970 /// broadcaster/countersignatory.
972 /// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
973 /// as_holder_broadcastable and as_counterparty_broadcastable functions.
974 pub struct DirectedChannelTransactionParameters<'a> {
975 /// The holder's channel static parameters
976 inner: &'a ChannelTransactionParameters,
977 /// Whether the holder is the broadcaster
978 holder_is_broadcaster: bool,
981 impl<'a> DirectedChannelTransactionParameters<'a> {
982 /// Get the channel pubkeys for the broadcaster
983 pub fn broadcaster_pubkeys(&self) -> &ChannelPublicKeys {
984 if self.holder_is_broadcaster {
985 &self.inner.holder_pubkeys
987 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
991 /// Get the channel pubkeys for the countersignatory
992 pub fn countersignatory_pubkeys(&self) -> &ChannelPublicKeys {
993 if self.holder_is_broadcaster {
994 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
996 &self.inner.holder_pubkeys
1000 /// Get the contest delay applicable to the transactions.
1001 /// Note that the contest delay was selected by the countersignatory.
1002 pub fn contest_delay(&self) -> u16 {
1003 let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
1004 if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
1007 /// Whether the channel is outbound from the broadcaster.
1009 /// The boolean representing the side that initiated the channel is
1010 /// an input to the commitment number obscure factor computation.
1011 pub fn is_outbound(&self) -> bool {
1012 if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
1015 /// The funding outpoint
1016 pub fn funding_outpoint(&self) -> OutPoint {
1017 self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
1020 /// Whether to use anchors for this channel
1021 pub fn channel_type_features(&self) -> &ChannelTypeFeatures {
1022 &self.inner.channel_type_features
1026 /// Information needed to build and sign a holder's commitment transaction.
1028 /// The transaction is only signed once we are ready to broadcast.
1030 pub struct HolderCommitmentTransaction {
1031 inner: CommitmentTransaction,
1032 /// Our counterparty's signature for the transaction
1033 pub counterparty_sig: Signature,
1034 /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
1035 pub counterparty_htlc_sigs: Vec<Signature>,
1036 // Which order the signatures should go in when constructing the final commitment tx witness.
1037 // The user should be able to reconstruct this themselves, so we don't bother to expose it.
1038 holder_sig_first: bool,
1041 impl Deref for HolderCommitmentTransaction {
1042 type Target = CommitmentTransaction;
1044 fn deref(&self) -> &Self::Target { &self.inner }
1047 impl Eq for HolderCommitmentTransaction {}
1048 impl PartialEq for HolderCommitmentTransaction {
1049 // We dont care whether we are signed in equality comparison
1050 fn eq(&self, o: &Self) -> bool {
1051 self.inner == o.inner
1055 impl_writeable_tlv_based!(HolderCommitmentTransaction, {
1056 (0, inner, required),
1057 (2, counterparty_sig, required),
1058 (4, holder_sig_first, required),
1059 (6, counterparty_htlc_sigs, required_vec),
1062 impl HolderCommitmentTransaction {
1064 pub fn dummy(htlcs: &mut Vec<(HTLCOutputInCommitment, ())>) -> Self {
1065 let secp_ctx = Secp256k1::new();
1066 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1067 let dummy_sig = sign(&secp_ctx, &secp256k1::Message::from_slice(&[42; 32]).unwrap(), &SecretKey::from_slice(&[42; 32]).unwrap());
1069 let keys = TxCreationKeys {
1070 per_commitment_point: dummy_key.clone(),
1071 revocation_key: dummy_key.clone(),
1072 broadcaster_htlc_key: dummy_key.clone(),
1073 countersignatory_htlc_key: dummy_key.clone(),
1074 broadcaster_delayed_payment_key: dummy_key.clone(),
1076 let channel_pubkeys = ChannelPublicKeys {
1077 funding_pubkey: dummy_key.clone(),
1078 revocation_basepoint: dummy_key.clone(),
1079 payment_point: dummy_key.clone(),
1080 delayed_payment_basepoint: dummy_key.clone(),
1081 htlc_basepoint: dummy_key.clone()
1083 let channel_parameters = ChannelTransactionParameters {
1084 holder_pubkeys: channel_pubkeys.clone(),
1085 holder_selected_contest_delay: 0,
1086 is_outbound_from_holder: false,
1087 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
1088 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1089 channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
1091 let mut counterparty_htlc_sigs = Vec::new();
1092 for _ in 0..htlcs.len() {
1093 counterparty_htlc_sigs.push(dummy_sig);
1095 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());
1096 htlcs.sort_by_key(|htlc| htlc.0.transaction_output_index);
1097 HolderCommitmentTransaction {
1099 counterparty_sig: dummy_sig,
1100 counterparty_htlc_sigs,
1101 holder_sig_first: false
1105 /// Create a new holder transaction with the given counterparty signatures.
1106 /// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
1107 pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
1109 inner: commitment_tx,
1111 counterparty_htlc_sigs,
1112 holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
1116 pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
1117 // First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
1118 let mut tx = self.inner.built.transaction.clone();
1119 tx.input[0].witness.push(Vec::new());
1121 if self.holder_sig_first {
1122 tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1123 tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1125 tx.input[0].witness.push_bitcoin_signature(&self.counterparty_sig.serialize_der(), EcdsaSighashType::All);
1126 tx.input[0].witness.push_bitcoin_signature(&holder_sig.serialize_der(), EcdsaSighashType::All);
1129 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
1134 /// A pre-built Bitcoin commitment transaction and its txid.
1136 pub struct BuiltCommitmentTransaction {
1137 /// The commitment transaction
1138 pub transaction: Transaction,
1139 /// The txid for the commitment transaction.
1141 /// This is provided as a performance optimization, instead of calling transaction.txid()
1146 impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
1147 (0, transaction, required),
1148 (2, txid, required),
1151 impl BuiltCommitmentTransaction {
1152 /// Get the SIGHASH_ALL sighash value of the transaction.
1154 /// This can be used to verify a signature.
1155 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1156 let sighash = &sighash::SighashCache::new(&self.transaction).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1157 hash_to_message!(sighash)
1160 /// Signs the counterparty's commitment transaction.
1161 pub fn sign_counterparty_commitment<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1162 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1163 sign(secp_ctx, &sighash, funding_key)
1166 /// Signs the holder commitment transaction because we are about to broadcast it.
1167 pub fn sign_holder_commitment<T: secp256k1::Signing, ES: Deref>(
1168 &self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64,
1169 entropy_source: &ES, secp_ctx: &Secp256k1<T>
1170 ) -> Signature where ES::Target: EntropySource {
1171 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1172 sign_with_aux_rand(secp_ctx, &sighash, funding_key, entropy_source)
1176 /// This class tracks the per-transaction information needed to build a closing transaction and will
1177 /// actually build it and sign.
1179 /// This class can be used inside a signer implementation to generate a signature given the relevant
1181 #[derive(Clone, Hash, PartialEq, Eq)]
1182 pub struct ClosingTransaction {
1183 to_holder_value_sat: u64,
1184 to_counterparty_value_sat: u64,
1185 to_holder_script: Script,
1186 to_counterparty_script: Script,
1190 impl ClosingTransaction {
1191 /// Construct an object of the class
1193 to_holder_value_sat: u64,
1194 to_counterparty_value_sat: u64,
1195 to_holder_script: Script,
1196 to_counterparty_script: Script,
1197 funding_outpoint: OutPoint,
1199 let built = build_closing_transaction(
1200 to_holder_value_sat, to_counterparty_value_sat,
1201 to_holder_script.clone(), to_counterparty_script.clone(),
1204 ClosingTransaction {
1205 to_holder_value_sat,
1206 to_counterparty_value_sat,
1208 to_counterparty_script,
1213 /// Trust our pre-built transaction.
1215 /// Applies a wrapper which allows access to the transaction.
1217 /// This should only be used if you fully trust the builder of this object. It should not
1218 /// be used by an external signer - instead use the verify function.
1219 pub fn trust(&self) -> TrustedClosingTransaction {
1220 TrustedClosingTransaction { inner: self }
1223 /// Verify our pre-built transaction.
1225 /// Applies a wrapper which allows access to the transaction.
1227 /// An external validating signer must call this method before signing
1228 /// or using the built transaction.
1229 pub fn verify(&self, funding_outpoint: OutPoint) -> Result<TrustedClosingTransaction, ()> {
1230 let built = build_closing_transaction(
1231 self.to_holder_value_sat, self.to_counterparty_value_sat,
1232 self.to_holder_script.clone(), self.to_counterparty_script.clone(),
1235 if self.built != built {
1238 Ok(TrustedClosingTransaction { inner: self })
1241 /// The value to be sent to the holder, or zero if the output will be omitted
1242 pub fn to_holder_value_sat(&self) -> u64 {
1243 self.to_holder_value_sat
1246 /// The value to be sent to the counterparty, or zero if the output will be omitted
1247 pub fn to_counterparty_value_sat(&self) -> u64 {
1248 self.to_counterparty_value_sat
1251 /// The destination of the holder's output
1252 pub fn to_holder_script(&self) -> &Script {
1253 &self.to_holder_script
1256 /// The destination of the counterparty's output
1257 pub fn to_counterparty_script(&self) -> &Script {
1258 &self.to_counterparty_script
1262 /// A wrapper on ClosingTransaction indicating that the built bitcoin
1263 /// transaction is trusted.
1265 /// See trust() and verify() functions on CommitmentTransaction.
1267 /// This structure implements Deref.
1268 pub struct TrustedClosingTransaction<'a> {
1269 inner: &'a ClosingTransaction,
1272 impl<'a> Deref for TrustedClosingTransaction<'a> {
1273 type Target = ClosingTransaction;
1275 fn deref(&self) -> &Self::Target { self.inner }
1278 impl<'a> TrustedClosingTransaction<'a> {
1279 /// The pre-built Bitcoin commitment transaction
1280 pub fn built_transaction(&self) -> &Transaction {
1284 /// Get the SIGHASH_ALL sighash value of the transaction.
1286 /// This can be used to verify a signature.
1287 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1288 let sighash = &sighash::SighashCache::new(&self.inner.built).segwit_signature_hash(0, funding_redeemscript, channel_value_satoshis, EcdsaSighashType::All).unwrap()[..];
1289 hash_to_message!(sighash)
1292 /// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1293 /// because we are about to broadcast a holder transaction.
1294 pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1295 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1296 sign(secp_ctx, &sighash, funding_key)
1300 /// This class tracks the per-transaction information needed to build a commitment transaction and will
1301 /// actually build it and sign. It is used for holder transactions that we sign only when needed
1302 /// and for transactions we sign for the counterparty.
1304 /// This class can be used inside a signer implementation to generate a signature given the relevant
1307 pub struct CommitmentTransaction {
1308 commitment_number: u64,
1309 to_broadcaster_value_sat: u64,
1310 to_countersignatory_value_sat: u64,
1311 feerate_per_kw: u32,
1312 htlcs: Vec<HTLCOutputInCommitment>,
1313 // Note that on upgrades, some features of existing outputs may be missed.
1314 channel_type_features: ChannelTypeFeatures,
1315 // A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
1316 keys: TxCreationKeys,
1317 // For access to the pre-built transaction, see doc for trust()
1318 built: BuiltCommitmentTransaction,
1321 impl Eq for CommitmentTransaction {}
1322 impl PartialEq for CommitmentTransaction {
1323 fn eq(&self, o: &Self) -> bool {
1324 let eq = self.commitment_number == o.commitment_number &&
1325 self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
1326 self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
1327 self.feerate_per_kw == o.feerate_per_kw &&
1328 self.htlcs == o.htlcs &&
1329 self.channel_type_features == o.channel_type_features &&
1330 self.keys == o.keys;
1332 debug_assert_eq!(self.built.transaction, o.built.transaction);
1333 debug_assert_eq!(self.built.txid, o.built.txid);
1339 impl Writeable for CommitmentTransaction {
1340 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1341 let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
1342 write_tlv_fields!(writer, {
1343 (0, self.commitment_number, required),
1344 (2, self.to_broadcaster_value_sat, required),
1345 (4, self.to_countersignatory_value_sat, required),
1346 (6, self.feerate_per_kw, required),
1347 (8, self.keys, required),
1348 (10, self.built, required),
1349 (12, self.htlcs, required_vec),
1350 (14, legacy_deserialization_prevention_marker, option),
1351 (15, self.channel_type_features, required),
1357 impl Readable for CommitmentTransaction {
1358 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1359 _init_and_read_len_prefixed_tlv_fields!(reader, {
1360 (0, commitment_number, required),
1361 (2, to_broadcaster_value_sat, required),
1362 (4, to_countersignatory_value_sat, required),
1363 (6, feerate_per_kw, required),
1364 (8, keys, required),
1365 (10, built, required),
1366 (12, htlcs, required_vec),
1367 (14, _legacy_deserialization_prevention_marker, option),
1368 (15, channel_type_features, option),
1371 let mut additional_features = ChannelTypeFeatures::empty();
1372 additional_features.set_anchors_nonzero_fee_htlc_tx_required();
1373 chain::package::verify_channel_type_features(&channel_type_features, Some(&additional_features))?;
1376 commitment_number: commitment_number.0.unwrap(),
1377 to_broadcaster_value_sat: to_broadcaster_value_sat.0.unwrap(),
1378 to_countersignatory_value_sat: to_countersignatory_value_sat.0.unwrap(),
1379 feerate_per_kw: feerate_per_kw.0.unwrap(),
1380 keys: keys.0.unwrap(),
1381 built: built.0.unwrap(),
1383 channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
1388 impl CommitmentTransaction {
1389 /// Construct an object of the class while assigning transaction output indices to HTLCs.
1391 /// Populates HTLCOutputInCommitment.transaction_output_index in htlcs_with_aux.
1393 /// The generic T allows the caller to match the HTLC output index with auxiliary data.
1394 /// This auxiliary data is not stored in this object.
1396 /// Only include HTLCs that are above the dust limit for the channel.
1398 /// This is not exported to bindings users due to the generic though we likely should expose a version without
1399 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 {
1400 // Sort outputs and populate output indices while keeping track of the auxiliary data
1401 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();
1403 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
1404 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1405 let txid = transaction.txid();
1406 CommitmentTransaction {
1408 to_broadcaster_value_sat,
1409 to_countersignatory_value_sat,
1412 channel_type_features: channel_parameters.channel_type_features().clone(),
1414 built: BuiltCommitmentTransaction {
1421 /// Use non-zero fee anchors
1423 /// This is not exported to bindings users due to move, and also not likely to be useful for binding users
1424 pub fn with_non_zero_fee_anchors(mut self) -> Self {
1425 self.channel_type_features.set_anchors_nonzero_fee_htlc_tx_required();
1429 fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<BuiltCommitmentTransaction, ()> {
1430 let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
1432 let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
1433 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)?;
1435 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1436 let txid = transaction.txid();
1437 let built_transaction = BuiltCommitmentTransaction {
1441 Ok(built_transaction)
1444 fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
1447 lock_time: PackedLockTime(((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32)),
1453 // This is used in two cases:
1454 // - initial sorting of outputs / HTLCs in the constructor, in which case T is auxiliary data the
1455 // caller needs to have sorted together with the HTLCs so it can keep track of the output index
1456 // - building of a bitcoin transaction during a verify() call, in which case T is just ()
1457 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>), ()> {
1458 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1459 let contest_delay = channel_parameters.contest_delay();
1461 let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
1463 if to_countersignatory_value_sat > 0 {
1464 let script = if channel_parameters.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
1465 get_to_countersignatory_with_anchors_redeemscript(&countersignatory_pubkeys.payment_point).to_v0_p2wsh()
1467 Payload::p2wpkh(&BitcoinPublicKey::new(countersignatory_pubkeys.payment_point)).unwrap().script_pubkey()
1471 script_pubkey: script.clone(),
1472 value: to_countersignatory_value_sat,
1478 if to_broadcaster_value_sat > 0 {
1479 let redeem_script = get_revokeable_redeemscript(
1480 &keys.revocation_key,
1482 &keys.broadcaster_delayed_payment_key,
1486 script_pubkey: redeem_script.to_v0_p2wsh(),
1487 value: to_broadcaster_value_sat,
1493 if channel_parameters.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
1494 if to_broadcaster_value_sat > 0 || !htlcs_with_aux.is_empty() {
1495 let anchor_script = get_anchor_redeemscript(broadcaster_funding_key);
1498 script_pubkey: anchor_script.to_v0_p2wsh(),
1499 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1505 if to_countersignatory_value_sat > 0 || !htlcs_with_aux.is_empty() {
1506 let anchor_script = get_anchor_redeemscript(countersignatory_funding_key);
1509 script_pubkey: anchor_script.to_v0_p2wsh(),
1510 value: ANCHOR_OUTPUT_VALUE_SATOSHI,
1517 let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
1518 for (htlc, _) in htlcs_with_aux {
1519 let script = chan_utils::get_htlc_redeemscript(&htlc, &channel_parameters.channel_type_features(), &keys);
1521 script_pubkey: script.to_v0_p2wsh(),
1522 value: htlc.amount_msat / 1000,
1524 txouts.push((txout, Some(htlc)));
1527 // Sort output in BIP-69 order (amount, scriptPubkey). Tie-breaks based on HTLC
1528 // CLTV expiration height.
1529 sort_outputs(&mut txouts, |a, b| {
1530 if let &Some(ref a_htlcout) = a {
1531 if let &Some(ref b_htlcout) = b {
1532 a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
1533 // Note that due to hash collisions, we have to have a fallback comparison
1534 // here for fuzzing mode (otherwise at least chanmon_fail_consistency
1536 .then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
1537 // For non-HTLC outputs, if they're copying our SPK we don't really care if we
1538 // close the channel due to mismatches - they're doing something dumb:
1539 } else { cmp::Ordering::Equal }
1540 } else { cmp::Ordering::Equal }
1543 let mut outputs = Vec::with_capacity(txouts.len());
1544 for (idx, out) in txouts.drain(..).enumerate() {
1545 if let Some(htlc) = out.1 {
1546 htlc.transaction_output_index = Some(idx as u32);
1547 htlcs.push(htlc.clone());
1549 outputs.push(out.0);
1551 Ok((outputs, htlcs))
1554 fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
1555 let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
1556 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1557 let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
1558 &broadcaster_pubkeys.payment_point,
1559 &countersignatory_pubkeys.payment_point,
1560 channel_parameters.is_outbound(),
1563 let obscured_commitment_transaction_number =
1564 commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
1567 let mut ins: Vec<TxIn> = Vec::new();
1569 previous_output: channel_parameters.funding_outpoint(),
1570 script_sig: Script::new(),
1571 sequence: Sequence(((0x80 as u32) << 8 * 3)
1572 | ((obscured_commitment_transaction_number >> 3 * 8) as u32)),
1573 witness: Witness::new(),
1577 (obscured_commitment_transaction_number, txins)
1580 /// The backwards-counting commitment number
1581 pub fn commitment_number(&self) -> u64 {
1582 self.commitment_number
1585 /// The value to be sent to the broadcaster
1586 pub fn to_broadcaster_value_sat(&self) -> u64 {
1587 self.to_broadcaster_value_sat
1590 /// The value to be sent to the counterparty
1591 pub fn to_countersignatory_value_sat(&self) -> u64 {
1592 self.to_countersignatory_value_sat
1595 /// The feerate paid per 1000-weight-unit in this commitment transaction.
1596 pub fn feerate_per_kw(&self) -> u32 {
1600 /// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
1601 /// which were included in this commitment transaction in output order.
1602 /// The transaction index is always populated.
1604 /// This is not exported to bindings users as we cannot currently convert Vec references to/from C, though we should
1605 /// expose a less effecient version which creates a Vec of references in the future.
1606 pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
1610 /// Trust our pre-built transaction and derived transaction creation public keys.
1612 /// Applies a wrapper which allows access to these fields.
1614 /// This should only be used if you fully trust the builder of this object. It should not
1615 /// be used by an external signer - instead use the verify function.
1616 pub fn trust(&self) -> TrustedCommitmentTransaction {
1617 TrustedCommitmentTransaction { inner: self }
1620 /// Verify our pre-built transaction and derived transaction creation public keys.
1622 /// Applies a wrapper which allows access to these fields.
1624 /// An external validating signer must call this method before signing
1625 /// or using the built transaction.
1626 pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
1627 // This is the only field of the key cache that we trust
1628 let per_commitment_point = self.keys.per_commitment_point;
1629 let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx);
1630 if keys != self.keys {
1633 let tx = self.internal_rebuild_transaction(&keys, channel_parameters, &broadcaster_keys.funding_pubkey, &countersignatory_keys.funding_pubkey)?;
1634 if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
1637 Ok(TrustedCommitmentTransaction { inner: self })
1641 /// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
1642 /// transaction and the transaction creation keys) are trusted.
1644 /// See trust() and verify() functions on CommitmentTransaction.
1646 /// This structure implements Deref.
1647 pub struct TrustedCommitmentTransaction<'a> {
1648 inner: &'a CommitmentTransaction,
1651 impl<'a> Deref for TrustedCommitmentTransaction<'a> {
1652 type Target = CommitmentTransaction;
1654 fn deref(&self) -> &Self::Target { self.inner }
1657 impl<'a> TrustedCommitmentTransaction<'a> {
1658 /// The transaction ID of the built Bitcoin transaction
1659 pub fn txid(&self) -> Txid {
1660 self.inner.built.txid
1663 /// The pre-built Bitcoin commitment transaction
1664 pub fn built_transaction(&self) -> &BuiltCommitmentTransaction {
1668 /// The pre-calculated transaction creation public keys.
1669 pub fn keys(&self) -> &TxCreationKeys {
1673 /// Should anchors be used.
1674 pub fn channel_type_features(&self) -> &ChannelTypeFeatures {
1675 &self.inner.channel_type_features
1678 /// Get a signature for each HTLC which was included in the commitment transaction (ie for
1679 /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
1681 /// The returned Vec has one entry for each HTLC, and in the same order.
1683 /// This function is only valid in the holder commitment context, it always uses EcdsaSighashType::All.
1684 pub fn get_htlc_sigs<T: secp256k1::Signing, ES: Deref>(
1685 &self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters,
1686 entropy_source: &ES, secp_ctx: &Secp256k1<T>,
1687 ) -> Result<Vec<Signature>, ()> where ES::Target: EntropySource {
1688 let inner = self.inner;
1689 let keys = &inner.keys;
1690 let txid = inner.built.txid;
1691 let mut ret = Vec::with_capacity(inner.htlcs.len());
1692 let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key);
1694 for this_htlc in inner.htlcs.iter() {
1695 assert!(this_htlc.transaction_output_index.is_some());
1696 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);
1698 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);
1700 let sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, this_htlc.amount_msat / 1000, EcdsaSighashType::All).unwrap()[..]);
1701 ret.push(sign_with_aux_rand(secp_ctx, &sighash, &holder_htlc_key, entropy_source));
1706 /// Gets a signed HTLC transaction given a preimage (for !htlc.offered) and the holder HTLC transaction signature.
1707 pub(crate) fn get_signed_htlc_tx(&self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature, preimage: &Option<PaymentPreimage>) -> Transaction {
1708 let inner = self.inner;
1709 let keys = &inner.keys;
1710 let txid = inner.built.txid;
1711 let this_htlc = &inner.htlcs[htlc_index];
1712 assert!(this_htlc.transaction_output_index.is_some());
1713 // if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
1714 if !this_htlc.offered && preimage.is_none() { unreachable!(); }
1715 // Further, we should never be provided the preimage for an HTLC-Timeout transaction.
1716 if this_htlc.offered && preimage.is_some() { unreachable!(); }
1718 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);
1720 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);
1722 htlc_tx.input[0].witness = chan_utils::build_htlc_input_witness(
1723 signature, counterparty_signature, preimage, &htlc_redeemscript, &self.channel_type_features,
1729 /// Commitment transaction numbers which appear in the transactions themselves are XOR'd with a
1730 /// shared secret first. This prevents on-chain observers from discovering how many commitment
1731 /// transactions occurred in a channel before it was closed.
1733 /// This function gets the shared secret from relevant channel public keys and can be used to
1734 /// "decrypt" the commitment transaction number given a commitment transaction on-chain.
1735 pub fn get_commitment_transaction_number_obscure_factor(
1736 broadcaster_payment_basepoint: &PublicKey,
1737 countersignatory_payment_basepoint: &PublicKey,
1738 outbound_from_broadcaster: bool,
1740 let mut sha = Sha256::engine();
1742 if outbound_from_broadcaster {
1743 sha.input(&broadcaster_payment_basepoint.serialize());
1744 sha.input(&countersignatory_payment_basepoint.serialize());
1746 sha.input(&countersignatory_payment_basepoint.serialize());
1747 sha.input(&broadcaster_payment_basepoint.serialize());
1749 let res = Sha256::from_engine(sha).into_inner();
1751 ((res[26] as u64) << 5 * 8)
1752 | ((res[27] as u64) << 4 * 8)
1753 | ((res[28] as u64) << 3 * 8)
1754 | ((res[29] as u64) << 2 * 8)
1755 | ((res[30] as u64) << 1 * 8)
1756 | ((res[31] as u64) << 0 * 8)
1761 use super::CounterpartyCommitmentSecrets;
1762 use crate::{hex, chain};
1763 use crate::prelude::*;
1764 use crate::ln::chan_utils::{get_htlc_redeemscript, get_to_countersignatory_with_anchors_redeemscript, CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
1765 use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
1766 use crate::util::test_utils;
1767 use crate::sign::{ChannelSigner, SignerProvider};
1768 use bitcoin::{Network, Txid};
1769 use bitcoin::hashes::Hash;
1770 use crate::ln::PaymentHash;
1771 use bitcoin::hashes::hex::ToHex;
1772 use bitcoin::util::address::Payload;
1773 use bitcoin::PublicKey as BitcoinPublicKey;
1774 use crate::ln::features::ChannelTypeFeatures;
1778 let secp_ctx = Secp256k1::new();
1780 let seed = [42; 32];
1781 let network = Network::Testnet;
1782 let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
1783 let signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(false, 1_000_000, 0));
1784 let counterparty_signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(true, 1_000_000, 1));
1785 let delayed_payment_base = &signer.pubkeys().delayed_payment_basepoint;
1786 let per_commitment_secret = SecretKey::from_slice(&hex::decode("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
1787 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
1788 let htlc_basepoint = &signer.pubkeys().htlc_basepoint;
1789 let holder_pubkeys = signer.pubkeys();
1790 let counterparty_pubkeys = counterparty_signer.pubkeys();
1791 let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint);
1792 let mut channel_parameters = ChannelTransactionParameters {
1793 holder_pubkeys: holder_pubkeys.clone(),
1794 holder_selected_contest_delay: 0,
1795 is_outbound_from_holder: false,
1796 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: counterparty_pubkeys.clone(), selected_contest_delay: 0 }),
1797 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1798 channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
1801 let mut htlcs_with_aux: Vec<(_, ())> = Vec::new();
1803 // Generate broadcaster and counterparty outputs
1804 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1806 holder_pubkeys.funding_pubkey,
1807 counterparty_pubkeys.funding_pubkey,
1809 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1811 assert_eq!(tx.built.transaction.output.len(), 2);
1812 assert_eq!(tx.built.transaction.output[1].script_pubkey, Payload::p2wpkh(&BitcoinPublicKey::new(counterparty_pubkeys.payment_point)).unwrap().script_pubkey());
1814 // Generate broadcaster and counterparty outputs as well as two anchors
1815 channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
1816 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1818 holder_pubkeys.funding_pubkey,
1819 counterparty_pubkeys.funding_pubkey,
1821 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1823 assert_eq!(tx.built.transaction.output.len(), 4);
1824 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_to_countersignatory_with_anchors_redeemscript(&counterparty_pubkeys.payment_point).to_v0_p2wsh());
1826 // Generate broadcaster output and anchor
1827 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1829 holder_pubkeys.funding_pubkey,
1830 counterparty_pubkeys.funding_pubkey,
1832 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1834 assert_eq!(tx.built.transaction.output.len(), 2);
1836 // Generate counterparty output and anchor
1837 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1839 holder_pubkeys.funding_pubkey,
1840 counterparty_pubkeys.funding_pubkey,
1842 &mut htlcs_with_aux, &channel_parameters.as_holder_broadcastable()
1844 assert_eq!(tx.built.transaction.output.len(), 2);
1846 let received_htlc = HTLCOutputInCommitment {
1848 amount_msat: 400000,
1850 payment_hash: PaymentHash([42; 32]),
1851 transaction_output_index: None,
1854 let offered_htlc = HTLCOutputInCommitment {
1856 amount_msat: 600000,
1858 payment_hash: PaymentHash([43; 32]),
1859 transaction_output_index: None,
1862 // Generate broadcaster output and received and offered HTLC outputs, w/o anchors
1863 channel_parameters.channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1864 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1866 holder_pubkeys.funding_pubkey,
1867 counterparty_pubkeys.funding_pubkey,
1869 &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1870 &channel_parameters.as_holder_broadcastable()
1872 assert_eq!(tx.built.transaction.output.len(), 3);
1873 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh());
1874 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh());
1875 assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh().to_hex(),
1876 "0020e43a7c068553003fe68fcae424fb7b28ec5ce48cd8b6744b3945631389bad2fb");
1877 assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_v0_p2wsh().to_hex(),
1878 "0020215d61bba56b19e9eadb6107f5a85d7f99c40f65992443f69229c290165bc00d");
1880 // Generate broadcaster output and received and offered HTLC outputs, with anchors
1881 channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
1882 let tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1884 holder_pubkeys.funding_pubkey,
1885 counterparty_pubkeys.funding_pubkey,
1887 &mut vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())],
1888 &channel_parameters.as_holder_broadcastable()
1890 assert_eq!(tx.built.transaction.output.len(), 5);
1891 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());
1892 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());
1893 assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_v0_p2wsh().to_hex(),
1894 "0020b70d0649c72b38756885c7a30908d912a7898dd5d79457a7280b8e9a20f3f2bc");
1895 assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_v0_p2wsh().to_hex(),
1896 "002087a3faeb1950a469c0e2db4a79b093a41b9526e5a6fc6ef5cb949bde3be379c7");
1900 fn test_per_commitment_storage() {
1901 // Test vectors from BOLT 3:
1902 let mut secrets: Vec<[u8; 32]> = Vec::new();
1905 macro_rules! test_secrets {
1907 let mut idx = 281474976710655;
1908 for secret in secrets.iter() {
1909 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
1912 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
1913 assert!(monitor.get_secret(idx).is_none());
1918 // insert_secret correct sequence
1919 monitor = CounterpartyCommitmentSecrets::new();
1922 secrets.push([0; 32]);
1923 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
1924 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1927 secrets.push([0; 32]);
1928 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1929 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1932 secrets.push([0; 32]);
1933 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1934 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1937 secrets.push([0; 32]);
1938 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
1939 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
1942 secrets.push([0; 32]);
1943 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
1944 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
1947 secrets.push([0; 32]);
1948 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
1949 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
1952 secrets.push([0; 32]);
1953 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
1954 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
1957 secrets.push([0; 32]);
1958 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
1959 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
1964 // insert_secret #1 incorrect
1965 monitor = CounterpartyCommitmentSecrets::new();
1968 secrets.push([0; 32]);
1969 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1970 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1973 secrets.push([0; 32]);
1974 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
1975 assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
1979 // insert_secret #2 incorrect (#1 derived from incorrect)
1980 monitor = CounterpartyCommitmentSecrets::new();
1983 secrets.push([0; 32]);
1984 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
1985 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
1988 secrets.push([0; 32]);
1989 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
1990 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
1993 secrets.push([0; 32]);
1994 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
1995 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
1998 secrets.push([0; 32]);
1999 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2000 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
2004 // insert_secret #3 incorrect
2005 monitor = CounterpartyCommitmentSecrets::new();
2008 secrets.push([0; 32]);
2009 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2010 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2013 secrets.push([0; 32]);
2014 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2015 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2018 secrets.push([0; 32]);
2019 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2020 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2023 secrets.push([0; 32]);
2024 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2025 assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
2029 // insert_secret #4 incorrect (1,2,3 derived from incorrect)
2030 monitor = CounterpartyCommitmentSecrets::new();
2033 secrets.push([0; 32]);
2034 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2035 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2038 secrets.push([0; 32]);
2039 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2040 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2043 secrets.push([0; 32]);
2044 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2045 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2048 secrets.push([0; 32]);
2049 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
2050 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2053 secrets.push([0; 32]);
2054 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2055 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2058 secrets.push([0; 32]);
2059 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2060 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2063 secrets.push([0; 32]);
2064 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2065 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2068 secrets.push([0; 32]);
2069 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2070 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2074 // insert_secret #5 incorrect
2075 monitor = CounterpartyCommitmentSecrets::new();
2078 secrets.push([0; 32]);
2079 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2080 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2083 secrets.push([0; 32]);
2084 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2085 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2088 secrets.push([0; 32]);
2089 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2090 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2093 secrets.push([0; 32]);
2094 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2095 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2098 secrets.push([0; 32]);
2099 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2100 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2103 secrets.push([0; 32]);
2104 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2105 assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
2109 // insert_secret #6 incorrect (5 derived from incorrect)
2110 monitor = CounterpartyCommitmentSecrets::new();
2113 secrets.push([0; 32]);
2114 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2115 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2118 secrets.push([0; 32]);
2119 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2120 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2123 secrets.push([0; 32]);
2124 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2125 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2128 secrets.push([0; 32]);
2129 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2130 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2133 secrets.push([0; 32]);
2134 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2135 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2138 secrets.push([0; 32]);
2139 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
2140 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2143 secrets.push([0; 32]);
2144 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2145 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2148 secrets.push([0; 32]);
2149 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2150 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2154 // insert_secret #7 incorrect
2155 monitor = CounterpartyCommitmentSecrets::new();
2158 secrets.push([0; 32]);
2159 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2160 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2163 secrets.push([0; 32]);
2164 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2165 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2168 secrets.push([0; 32]);
2169 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2170 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2173 secrets.push([0; 32]);
2174 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2175 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2178 secrets.push([0; 32]);
2179 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2180 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2183 secrets.push([0; 32]);
2184 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2185 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2188 secrets.push([0; 32]);
2189 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2190 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2193 secrets.push([0; 32]);
2194 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2195 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2199 // insert_secret #8 incorrect
2200 monitor = CounterpartyCommitmentSecrets::new();
2203 secrets.push([0; 32]);
2204 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2205 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2208 secrets.push([0; 32]);
2209 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2210 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2213 secrets.push([0; 32]);
2214 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2215 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2218 secrets.push([0; 32]);
2219 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2220 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2223 secrets.push([0; 32]);
2224 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2225 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2228 secrets.push([0; 32]);
2229 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2230 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2233 secrets.push([0; 32]);
2234 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2235 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2238 secrets.push([0; 32]);
2239 secrets.last_mut().unwrap()[0..32].clone_from_slice(&hex::decode("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2240 assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());