1use bitcoin::amount::Amount;
14use bitcoin::constants::WITNESS_SCALE_FACTOR;
15use bitcoin::opcodes;
16use bitcoin::script::{Builder, Script, ScriptBuf};
17use bitcoin::sighash;
18use bitcoin::sighash::EcdsaSighashType;
19use bitcoin::transaction::Version;
20use bitcoin::transaction::{OutPoint, Transaction, TxIn, TxOut};
21use bitcoin::{PubkeyHash, WPubkeyHash};
22
23use bitcoin::hash_types::Txid;
24use bitcoin::hashes::hash160::Hash as Hash160;
25use bitcoin::hashes::ripemd160::Hash as Ripemd160;
26use bitcoin::hashes::sha256::Hash as Sha256;
27use bitcoin::hashes::{Hash, HashEngine};
28
29use crate::chain::chaininterface::{
30 fee_for_weight, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator,
31};
32use crate::chain::package::WEIGHT_REVOKED_OUTPUT;
33use crate::ln::msgs::DecodeError;
34use crate::sign::EntropySource;
35use crate::types::payment::{PaymentHash, PaymentPreimage};
36use crate::util::ser::{Readable, ReadableArgs, RequiredWrapper, Writeable, Writer};
37use crate::util::transaction_utils;
38
39use bitcoin::ecdsa::Signature as BitcoinSignature;
40use bitcoin::locktime::absolute::LockTime;
41use bitcoin::secp256k1::{ecdsa::Signature, Message, Secp256k1};
42use bitcoin::secp256k1::{PublicKey, Scalar, SecretKey};
43use bitcoin::{secp256k1, Sequence, Witness};
44
45use super::channel_keys::{
46 DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, HtlcKey, RevocationBasepoint,
47 RevocationKey,
48};
49use crate::chain;
50use crate::crypto::utils::{sign, sign_with_aux_rand};
51use crate::io;
52use crate::ln::channel::{ANCHOR_OUTPUT_VALUE_SATOSHI, INITIAL_COMMITMENT_NUMBER};
53use crate::types::features::ChannelTypeFeatures;
54use core::cmp;
55use core::ops::Deref;
56
57#[allow(unused_imports)]
58use crate::prelude::*;
59
60pub fn max_htlcs(channel_type: &ChannelTypeFeatures) -> u16 {
66 if channel_type.supports_anchor_zero_fee_commitments() {
67 114
69 } else {
70 483
71 }
72}
73pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
75pub const OFFERED_HTLC_SCRIPT_WEIGHT_KEYED_ANCHORS: usize = 136;
77
78pub(crate) const MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 136;
81pub const MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 143;
85
86#[cfg(feature = "grind_signatures")]
88pub const ANCHOR_INPUT_WITNESS_WEIGHT: u64 = 114;
89#[cfg(not(feature = "grind_signatures"))]
91pub const ANCHOR_INPUT_WITNESS_WEIGHT: u64 = 115;
92
93pub const EMPTY_WITNESS_WEIGHT: u64 = 1;
95
96pub const P2A_MAX_VALUE: u64 = 240;
98
99pub const TRUC_MAX_WEIGHT: u64 = 10_000 * WITNESS_SCALE_FACTOR as u64;
101
102pub const TRUC_CHILD_MAX_WEIGHT: u64 = 1000 * WITNESS_SCALE_FACTOR as u64;
104
105pub const HTLC_TIMEOUT_INPUT_KEYED_ANCHOR_WITNESS_WEIGHT: u64 = 288;
107pub const HTLC_TIMEOUT_INPUT_P2A_ANCHOR_WITNESS_WEIGHT: u64 = 285;
110pub const HTLC_SUCCESS_INPUT_KEYED_ANCHOR_WITNESS_WEIGHT: u64 = 327;
112pub const HTLC_SUCCESS_INPUT_P2A_ANCHOR_WITNESS_WEIGHT: u64 = 324;
115
116const MULTISIG_SCRIPT_SIZE: u64 = 1 + 1 + crate::sign::COMPRESSED_PUBLIC_KEY_SIZE as u64 + 1 + crate::sign::COMPRESSED_PUBLIC_KEY_SIZE as u64 + 1 + 1; pub const FUNDING_TRANSACTION_WITNESS_WEIGHT: u64 = 1 + 1 + 1 + crate::sign::MAX_STANDARD_SIGNATURE_SIZE as u64 + 1 + crate::sign::MAX_STANDARD_SIGNATURE_SIZE as u64 + 1 + MULTISIG_SCRIPT_SIZE;
142
143pub(crate) const BASE_TX_SIZE: u64 = 4 + 1 + 1 + 4 ;
144pub(crate) const SEGWIT_MARKER_FLAG_WEIGHT: u64 = 2;
145pub(crate) const EMPTY_SCRIPT_SIG_WEIGHT: u64 =
146 1 * WITNESS_SCALE_FACTOR as u64;
147pub(crate) const BASE_INPUT_SIZE: u64 = 32 + 4 + 4 ;
148pub(crate) const BASE_INPUT_WEIGHT: u64 = BASE_INPUT_SIZE * WITNESS_SCALE_FACTOR as u64;
149pub(crate) const P2WSH_TXOUT_WEIGHT: u64 =
150 (8 + 1 + 34) * WITNESS_SCALE_FACTOR as u64;
151
152#[inline]
154#[rustfmt::skip]
155pub fn htlc_success_tx_weight(channel_type_features: &ChannelTypeFeatures) -> u64 {
156 const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
157 const HTLC_SUCCESS_ANCHOR_TX_WEIGHT: u64 = 706;
158 if channel_type_features.supports_anchors_zero_fee_htlc_tx() { HTLC_SUCCESS_ANCHOR_TX_WEIGHT } else { HTLC_SUCCESS_TX_WEIGHT }
159}
160
161pub fn aggregated_htlc_success_input_output_pair_weight(
163 channel_type_features: &ChannelTypeFeatures,
164) -> u64 {
165 let satisfaction_weight = if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
166 EMPTY_SCRIPT_SIG_WEIGHT + HTLC_SUCCESS_INPUT_KEYED_ANCHOR_WITNESS_WEIGHT
167 } else {
168 EMPTY_SCRIPT_SIG_WEIGHT + HTLC_SUCCESS_INPUT_P2A_ANCHOR_WITNESS_WEIGHT
169 };
170 BASE_INPUT_WEIGHT + P2WSH_TXOUT_WEIGHT + satisfaction_weight
171}
172
173#[inline]
175#[rustfmt::skip]
176pub fn htlc_timeout_tx_weight(channel_type_features: &ChannelTypeFeatures) -> u64 {
177 const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
178 const HTLC_TIMEOUT_ANCHOR_TX_WEIGHT: u64 = 666;
179 if channel_type_features.supports_anchors_zero_fee_htlc_tx() { HTLC_TIMEOUT_ANCHOR_TX_WEIGHT } else { HTLC_TIMEOUT_TX_WEIGHT }
180}
181
182pub fn aggregated_htlc_timeout_input_output_pair_weight(
184 channel_type_features: &ChannelTypeFeatures,
185) -> u64 {
186 let satisfaction_weight = if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
187 EMPTY_SCRIPT_SIG_WEIGHT + HTLC_TIMEOUT_INPUT_KEYED_ANCHOR_WITNESS_WEIGHT
188 } else {
189 EMPTY_SCRIPT_SIG_WEIGHT + HTLC_TIMEOUT_INPUT_P2A_ANCHOR_WITNESS_WEIGHT
190 };
191 BASE_INPUT_WEIGHT + P2WSH_TXOUT_WEIGHT + satisfaction_weight
192}
193
194#[derive(PartialEq, Eq)]
196pub enum HTLCClaim {
197 OfferedTimeout,
199 OfferedPreimage,
201 AcceptedTimeout,
203 AcceptedPreimage,
205 Revocation,
207}
208
209impl HTLCClaim {
210 #[rustfmt::skip]
212 pub fn from_witness(witness: &Witness) -> Option<Self> {
213 debug_assert_eq!(OFFERED_HTLC_SCRIPT_WEIGHT_KEYED_ANCHORS, MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT);
214 if witness.len() < 2 {
215 return None;
216 }
217 let witness_script = witness.last().unwrap();
218 let second_to_last = witness.second_to_last().unwrap();
219 if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT {
220 if witness.len() == 3 && second_to_last.len() == 33 {
221 Some(Self::Revocation)
223 } else if witness.len() == 3 && second_to_last.len() == 32 {
224 Some(Self::OfferedPreimage)
226 } else if witness.len() == 5 && second_to_last.len() == 0 {
227 Some(Self::OfferedTimeout)
229 } else {
230 None
231 }
232 } else if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT_KEYED_ANCHORS {
233 if witness.len() == 3 && second_to_last.len() == 33 {
236 Some(Self::Revocation)
238 } else if witness.len() == 3 && second_to_last.len() == 32 {
239 Some(Self::OfferedPreimage)
241 } else if witness.len() == 5 && second_to_last.len() == 0 {
242 Some(Self::OfferedTimeout)
244 } else if witness.len() == 3 && second_to_last.len() == 0 {
245 Some(Self::AcceptedTimeout)
247 } else if witness.len() == 5 && second_to_last.len() == 32 {
248 Some(Self::AcceptedPreimage)
250 } else {
251 None
252 }
253 } else if witness_script.len() > MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT &&
254 witness_script.len() <= MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT {
255 if witness.len() == 3 && second_to_last.len() == 33 {
257 Some(Self::Revocation)
259 } else if witness.len() == 3 && second_to_last.len() == 0 {
260 Some(Self::AcceptedTimeout)
262 } else if witness.len() == 5 && second_to_last.len() == 32 {
263 Some(Self::AcceptedPreimage)
265 } else {
266 None
267 }
268 } else {
269 None
270 }
271 }
272}
273
274#[cfg(not(any(test, feature = "_test_utils")))]
275const COMMITMENT_TX_WEIGHT_PER_HTLC: u64 = 172;
276#[cfg(any(test, feature = "_test_utils"))]
277pub const COMMITMENT_TX_WEIGHT_PER_HTLC: u64 = 172;
278
279#[rustfmt::skip]
280pub(crate) fn commitment_tx_base_weight(channel_type_features: &ChannelTypeFeatures) -> u64 {
281 const COMMITMENT_TX_BASE_WEIGHT: u64 = 724;
282 const COMMITMENT_TX_BASE_ANCHOR_WEIGHT: u64 = 1124;
283 if channel_type_features.supports_anchors_zero_fee_htlc_tx() { COMMITMENT_TX_BASE_ANCHOR_WEIGHT } else { COMMITMENT_TX_BASE_WEIGHT }
284}
285
286#[rustfmt::skip]
289pub(crate) fn commit_tx_fee_sat(feerate_per_kw: u32, num_htlcs: usize, channel_type_features: &ChannelTypeFeatures) -> u64 {
290 feerate_per_kw as u64 *
291 (commitment_tx_base_weight(channel_type_features) +
292 num_htlcs as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)
293 / 1000
294}
295
296pub(crate) fn second_stage_tx_fees_sat(
298 channel_type: &ChannelTypeFeatures, feerate_sat_per_1000_weight: u32,
299) -> (u64, u64) {
300 if channel_type.supports_anchors_zero_fee_htlc_tx()
301 || channel_type.supports_anchor_zero_fee_commitments()
302 {
303 (0, 0)
304 } else {
305 (
306 feerate_sat_per_1000_weight as u64 * htlc_success_tx_weight(channel_type) / 1000,
307 feerate_sat_per_1000_weight as u64 * htlc_timeout_tx_weight(channel_type) / 1000,
308 )
309 }
310}
311
312#[rustfmt::skip]
313pub(crate) fn htlc_tx_fees_sat(feerate_per_kw: u32, num_accepted_htlcs: usize, num_offered_htlcs: usize, channel_type_features: &ChannelTypeFeatures) -> u64 {
314 let (htlc_success_tx_fee_sat, htlc_timeout_tx_fee_sat) = second_stage_tx_fees_sat(
315 channel_type_features, feerate_per_kw,
316 );
317
318 num_accepted_htlcs as u64 * htlc_success_tx_fee_sat + num_offered_htlcs as u64 * htlc_timeout_tx_fee_sat
319}
320
321pub(super) fn selected_commitment_sat_per_1000_weight<F: Deref>(
324 fee_estimator: &LowerBoundedFeeEstimator<F>, channel_type: &ChannelTypeFeatures,
325) -> u32
326where
327 F::Target: FeeEstimator,
328{
329 if channel_type.supports_anchor_zero_fee_commitments() {
330 0
331 } else if channel_type.supports_anchors_zero_fee_htlc_tx() {
332 fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee)
333 } else {
334 fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee)
335 }
336}
337
338pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
343 let mut res: [u8; 32] = commitment_seed.clone();
344 for i in 0..48 {
345 let bitpos = 47 - i;
346 if idx & (1 << bitpos) == (1 << bitpos) {
347 res[bitpos / 8] ^= 1 << (bitpos & 7);
348 res = Sha256::hash(&res).to_byte_array();
349 }
350 }
351 res
352}
353
354#[rustfmt::skip]
356pub fn build_closing_transaction(to_holder_value_sat: Amount, to_counterparty_value_sat: Amount, to_holder_script: ScriptBuf, to_counterparty_script: ScriptBuf, funding_outpoint: OutPoint) -> Transaction {
357 let txins = {
358 let ins: Vec<TxIn> = vec![TxIn {
359 previous_output: funding_outpoint,
360 script_sig: ScriptBuf::new(),
361 sequence: Sequence::MAX,
362 witness: Witness::new(),
363 }];
364 ins
365 };
366
367 let mut txouts: Vec<(TxOut, ())> = Vec::new();
368
369 if to_counterparty_value_sat > Amount::ZERO {
370 txouts.push((TxOut {
371 script_pubkey: to_counterparty_script,
372 value: to_counterparty_value_sat
373 }, ()));
374 }
375
376 if to_holder_value_sat > Amount::ZERO {
377 txouts.push((TxOut {
378 script_pubkey: to_holder_script,
379 value: to_holder_value_sat
380 }, ()));
381 }
382
383 transaction_utils::sort_outputs(&mut txouts, |_, _| { cmp::Ordering::Equal }); let mut outputs: Vec<TxOut> = Vec::new();
386 for out in txouts.drain(..) {
387 outputs.push(out.0);
388 }
389
390 Transaction {
391 version: Version::TWO,
392 lock_time: LockTime::ZERO,
393 input: txins,
394 output: outputs,
395 }
396}
397
398#[derive(Clone)]
404pub struct CounterpartyCommitmentSecrets {
405 old_secrets: [([u8; 32], u64); 49],
406}
407
408impl Eq for CounterpartyCommitmentSecrets {}
409impl PartialEq for CounterpartyCommitmentSecrets {
410 #[rustfmt::skip]
411 fn eq(&self, other: &Self) -> bool {
412 for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
413 if secret != o_secret || idx != o_idx {
414 return false
415 }
416 }
417 true
418 }
419}
420
421impl CounterpartyCommitmentSecrets {
422 #[rustfmt::skip]
424 pub fn new() -> Self {
425 Self { old_secrets: [([0; 32], 1 << 48); 49], }
426 }
427
428 #[inline]
429 #[rustfmt::skip]
430 fn place_secret(idx: u64) -> u8 {
431 for i in 0..48 {
432 if idx & (1 << i) == (1 << i) {
433 return i
434 }
435 }
436 48
437 }
438
439 pub fn get_min_seen_secret(&self) -> u64 {
442 let mut min = 1 << 48;
444 for &(_, idx) in self.old_secrets.iter() {
445 if idx < min {
446 min = idx;
447 }
448 }
449 min
450 }
451
452 #[inline]
453 fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
454 let mut res: [u8; 32] = secret;
455 for i in 0..bits {
456 let bitpos = bits - 1 - i;
457 if idx & (1 << bitpos) == (1 << bitpos) {
458 res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
459 res = Sha256::hash(&res).to_byte_array();
460 }
461 }
462 res
463 }
464
465 pub fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
468 let pos = Self::place_secret(idx);
469 for i in 0..pos {
470 let (old_secret, old_idx) = self.old_secrets[i as usize];
471 if Self::derive_secret(secret, pos, old_idx) != old_secret {
472 return Err(());
473 }
474 }
475 if self.get_min_seen_secret() <= idx {
476 return Ok(());
477 }
478 self.old_secrets[pos as usize] = (secret, idx);
479 Ok(())
480 }
481
482 #[rustfmt::skip]
485 pub fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
486 for i in 0..self.old_secrets.len() {
487 if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
488 return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
489 }
490 }
491 assert!(idx < self.get_min_seen_secret());
492 None
493 }
494}
495
496impl Writeable for CounterpartyCommitmentSecrets {
497 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
498 for &(ref secret, ref idx) in self.old_secrets.iter() {
499 writer.write_all(secret)?;
500 writer.write_all(&idx.to_be_bytes())?;
501 }
502 write_tlv_fields!(writer, {});
503 Ok(())
504 }
505}
506impl Readable for CounterpartyCommitmentSecrets {
507 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
508 let mut old_secrets = [([0; 32], 1 << 48); 49];
509 for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
510 *secret = Readable::read(reader)?;
511 *idx = Readable::read(reader)?;
512 }
513 read_tlv_fields!(reader, {});
514 Ok(Self { old_secrets })
515 }
516}
517
518pub fn derive_private_key<T: secp256k1::Signing>(
521 secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey,
522) -> SecretKey {
523 let mut sha = Sha256::engine();
524 sha.input(&per_commitment_point.serialize());
525 sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
526 let res = Sha256::from_engine(sha).to_byte_array();
527
528 base_secret.clone().add_tweak(&Scalar::from_be_bytes(res).unwrap())
529 .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.")
530}
531
532#[rustfmt::skip]
539pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>,
540 per_commitment_secret: &SecretKey, countersignatory_revocation_base_secret: &SecretKey)
541-> SecretKey {
542 let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
543 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
544
545 let rev_append_commit_hash_key = {
546 let mut sha = Sha256::engine();
547 sha.input(&countersignatory_revocation_base_point.serialize());
548 sha.input(&per_commitment_point.serialize());
549
550 Sha256::from_engine(sha).to_byte_array()
551 };
552 let commit_append_rev_hash_key = {
553 let mut sha = Sha256::engine();
554 sha.input(&per_commitment_point.serialize());
555 sha.input(&countersignatory_revocation_base_point.serialize());
556
557 Sha256::from_engine(sha).to_byte_array()
558 };
559
560 let countersignatory_contrib = countersignatory_revocation_base_secret.clone().mul_tweak(&Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
561 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
562 let broadcaster_contrib = per_commitment_secret.clone().mul_tweak(&Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
563 .expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
564 countersignatory_contrib.add_tweak(&Scalar::from_be_bytes(broadcaster_contrib.secret_bytes()).unwrap())
565 .expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
566}
567
568#[derive(PartialEq, Eq, Clone, Debug)]
580pub struct TxCreationKeys {
581 pub per_commitment_point: PublicKey,
583 pub revocation_key: RevocationKey,
587 pub broadcaster_htlc_key: HtlcKey,
589 pub countersignatory_htlc_key: HtlcKey,
591 pub broadcaster_delayed_payment_key: DelayedPaymentKey,
593}
594
595impl_writeable_tlv_based!(TxCreationKeys, {
596 (0, per_commitment_point, required),
597 (2, revocation_key, required),
598 (4, broadcaster_htlc_key, required),
599 (6, countersignatory_htlc_key, required),
600 (8, broadcaster_delayed_payment_key, required),
601});
602
603#[derive(Clone, Debug, Hash, PartialEq, Eq)]
605pub struct ChannelPublicKeys {
606 pub funding_pubkey: PublicKey,
609 pub revocation_basepoint: RevocationBasepoint,
614 pub payment_point: PublicKey,
618 pub delayed_payment_basepoint: DelayedPaymentBasepoint,
622 pub htlc_basepoint: HtlcBasepoint,
625}
626
627impl_writeable_tlv_based!(ChannelPublicKeys, {
628 (0, funding_pubkey, required),
629 (2, revocation_basepoint, required),
630 (4, payment_point, required),
631 (6, delayed_payment_basepoint, required),
632 (8, htlc_basepoint, required),
633});
634
635impl TxCreationKeys {
636 #[rustfmt::skip]
639 pub fn derive_new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, broadcaster_delayed_payment_base: &DelayedPaymentBasepoint, broadcaster_htlc_base: &HtlcBasepoint, countersignatory_revocation_base: &RevocationBasepoint, countersignatory_htlc_base: &HtlcBasepoint) -> TxCreationKeys {
640 TxCreationKeys {
641 per_commitment_point: per_commitment_point.clone(),
642 revocation_key: RevocationKey::from_basepoint(&secp_ctx, &countersignatory_revocation_base, &per_commitment_point),
643 broadcaster_htlc_key: HtlcKey::from_basepoint(&secp_ctx, &broadcaster_htlc_base, &per_commitment_point),
644 countersignatory_htlc_key: HtlcKey::from_basepoint(&secp_ctx, &countersignatory_htlc_base, &per_commitment_point),
645 broadcaster_delayed_payment_key: DelayedPaymentKey::from_basepoint(&secp_ctx, &broadcaster_delayed_payment_base, &per_commitment_point),
646 }
647 }
648
649 pub fn from_channel_static_keys<T: secp256k1::Signing + secp256k1::Verification>(
652 per_commitment_point: &PublicKey, broadcaster_keys: &ChannelPublicKeys,
653 countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>,
654 ) -> TxCreationKeys {
655 TxCreationKeys::derive_new(
656 &secp_ctx,
657 &per_commitment_point,
658 &broadcaster_keys.delayed_payment_basepoint,
659 &broadcaster_keys.htlc_basepoint,
660 &countersignatory_keys.revocation_basepoint,
661 &countersignatory_keys.htlc_basepoint,
662 )
663 }
664}
665
666pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 4 + 34 * 2;
672
673#[rustfmt::skip]
677pub fn get_revokeable_redeemscript(revocation_key: &RevocationKey, contest_delay: u16, broadcaster_delayed_payment_key: &DelayedPaymentKey) -> ScriptBuf {
678 let res = Builder::new().push_opcode(opcodes::all::OP_IF)
679 .push_slice(&revocation_key.to_public_key().serialize())
680 .push_opcode(opcodes::all::OP_ELSE)
681 .push_int(contest_delay as i64)
682 .push_opcode(opcodes::all::OP_CSV)
683 .push_opcode(opcodes::all::OP_DROP)
684 .push_slice(&broadcaster_delayed_payment_key.to_public_key().serialize())
685 .push_opcode(opcodes::all::OP_ENDIF)
686 .push_opcode(opcodes::all::OP_CHECKSIG)
687 .into_script();
688 debug_assert!(res.len() <= REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH);
689 res
690}
691
692pub fn get_countersigner_payment_script(
695 channel_type_features: &ChannelTypeFeatures, payment_key: &PublicKey,
696) -> ScriptBuf {
697 if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
698 get_to_countersigner_keyed_anchor_redeemscript(payment_key).to_p2wsh()
699 } else {
700 ScriptBuf::new_p2wpkh(&WPubkeyHash::hash(&payment_key.serialize()))
701 }
702}
703
704#[derive(Clone, Debug, PartialEq, Eq)]
706pub struct HTLCOutputInCommitment {
707 pub offered: bool,
712 pub amount_msat: u64,
715 pub cltv_expiry: u32,
717 pub payment_hash: PaymentHash,
719 pub transaction_output_index: Option<u32>,
723}
724
725impl HTLCOutputInCommitment {
726 pub const fn to_bitcoin_amount(&self) -> Amount {
730 Amount::from_sat(self.amount_msat / 1000)
731 }
732
733 pub(crate) fn is_data_equal(&self, other: &HTLCOutputInCommitment) -> bool {
736 self.offered == other.offered
737 && self.amount_msat == other.amount_msat
738 && self.cltv_expiry == other.cltv_expiry
739 && self.payment_hash == other.payment_hash
740 }
741}
742
743impl_writeable_tlv_based!(HTLCOutputInCommitment, {
744 (0, offered, required),
745 (2, amount_msat, required),
746 (4, cltv_expiry, required),
747 (6, payment_hash, required),
748 (8, transaction_output_index, option),
749});
750
751#[inline]
752#[rustfmt::skip]
753pub(crate) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, broadcaster_htlc_key: &HtlcKey, countersignatory_htlc_key: &HtlcKey, revocation_key: &RevocationKey) -> ScriptBuf {
754 let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).to_byte_array();
755 if htlc.offered {
756 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
757 .push_opcode(opcodes::all::OP_HASH160)
758 .push_slice(PubkeyHash::hash(&revocation_key.to_public_key().serialize()))
759 .push_opcode(opcodes::all::OP_EQUAL)
760 .push_opcode(opcodes::all::OP_IF)
761 .push_opcode(opcodes::all::OP_CHECKSIG)
762 .push_opcode(opcodes::all::OP_ELSE)
763 .push_slice(&countersignatory_htlc_key.to_public_key().serialize())
764 .push_opcode(opcodes::all::OP_SWAP)
765 .push_opcode(opcodes::all::OP_SIZE)
766 .push_int(32)
767 .push_opcode(opcodes::all::OP_EQUAL)
768 .push_opcode(opcodes::all::OP_NOTIF)
769 .push_opcode(opcodes::all::OP_DROP)
770 .push_int(2)
771 .push_opcode(opcodes::all::OP_SWAP)
772 .push_slice(&broadcaster_htlc_key.to_public_key().serialize())
773 .push_int(2)
774 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
775 .push_opcode(opcodes::all::OP_ELSE)
776 .push_opcode(opcodes::all::OP_HASH160)
777 .push_slice(&payment_hash160)
778 .push_opcode(opcodes::all::OP_EQUALVERIFY)
779 .push_opcode(opcodes::all::OP_CHECKSIG)
780 .push_opcode(opcodes::all::OP_ENDIF);
781 if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
782 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
783 .push_opcode(opcodes::all::OP_CSV)
784 .push_opcode(opcodes::all::OP_DROP);
785 }
786 bldr.push_opcode(opcodes::all::OP_ENDIF)
787 .into_script()
788 } else {
789 let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
790 .push_opcode(opcodes::all::OP_HASH160)
791 .push_slice(&PubkeyHash::hash(&revocation_key.to_public_key().serialize()))
792 .push_opcode(opcodes::all::OP_EQUAL)
793 .push_opcode(opcodes::all::OP_IF)
794 .push_opcode(opcodes::all::OP_CHECKSIG)
795 .push_opcode(opcodes::all::OP_ELSE)
796 .push_slice(&countersignatory_htlc_key.to_public_key().serialize())
797 .push_opcode(opcodes::all::OP_SWAP)
798 .push_opcode(opcodes::all::OP_SIZE)
799 .push_int(32)
800 .push_opcode(opcodes::all::OP_EQUAL)
801 .push_opcode(opcodes::all::OP_IF)
802 .push_opcode(opcodes::all::OP_HASH160)
803 .push_slice(&payment_hash160)
804 .push_opcode(opcodes::all::OP_EQUALVERIFY)
805 .push_int(2)
806 .push_opcode(opcodes::all::OP_SWAP)
807 .push_slice(&broadcaster_htlc_key.to_public_key().serialize())
808 .push_int(2)
809 .push_opcode(opcodes::all::OP_CHECKMULTISIG)
810 .push_opcode(opcodes::all::OP_ELSE)
811 .push_opcode(opcodes::all::OP_DROP)
812 .push_int(htlc.cltv_expiry as i64)
813 .push_opcode(opcodes::all::OP_CLTV)
814 .push_opcode(opcodes::all::OP_DROP)
815 .push_opcode(opcodes::all::OP_CHECKSIG)
816 .push_opcode(opcodes::all::OP_ENDIF);
817 if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
818 bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
819 .push_opcode(opcodes::all::OP_CSV)
820 .push_opcode(opcodes::all::OP_DROP);
821 }
822 bldr.push_opcode(opcodes::all::OP_ENDIF)
823 .into_script()
824 }
825}
826
827#[inline]
830#[rustfmt::skip]
831pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, keys: &TxCreationKeys) -> ScriptBuf {
832 get_htlc_redeemscript_with_explicit_keys(htlc, channel_type_features, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
833}
834
835pub fn make_funding_redeemscript(
838 broadcaster: &PublicKey, countersignatory: &PublicKey,
839) -> ScriptBuf {
840 let broadcaster_funding_key = broadcaster.serialize();
841 let countersignatory_funding_key = countersignatory.serialize();
842
843 make_funding_redeemscript_from_slices(&broadcaster_funding_key, &countersignatory_funding_key)
844}
845
846#[rustfmt::skip]
847pub(crate) fn make_funding_redeemscript_from_slices(broadcaster_funding_key: &[u8; 33], countersignatory_funding_key: &[u8; 33]) -> ScriptBuf {
848 let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
849 if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
850 builder.push_slice(broadcaster_funding_key)
851 .push_slice(countersignatory_funding_key)
852 } else {
853 builder.push_slice(countersignatory_funding_key)
854 .push_slice(broadcaster_funding_key)
855 }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
856}
857
858pub fn build_htlc_transaction(
866 commitment_txid: &Txid, feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment,
867 channel_type_features: &ChannelTypeFeatures,
868 broadcaster_delayed_payment_key: &DelayedPaymentKey, revocation_key: &RevocationKey,
869) -> Transaction {
870 let txins = vec![build_htlc_input(commitment_txid, htlc, channel_type_features)];
871
872 let txouts: Vec<TxOut> = vec![build_htlc_output(
873 feerate_per_kw,
874 contest_delay,
875 htlc,
876 channel_type_features,
877 broadcaster_delayed_payment_key,
878 revocation_key,
879 )];
880
881 let version = if channel_type_features.supports_anchor_zero_fee_commitments() {
882 Version::non_standard(3)
883 } else {
884 Version::TWO
885 };
886
887 Transaction {
888 version,
889 lock_time: LockTime::from_consensus(if htlc.offered { htlc.cltv_expiry } else { 0 }),
890 input: txins,
891 output: txouts,
892 }
893}
894
895#[rustfmt::skip]
896pub(crate) fn build_htlc_input(commitment_txid: &Txid, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures) -> TxIn {
897 TxIn {
898 previous_output: OutPoint {
899 txid: commitment_txid.clone(),
900 vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
901 },
902 script_sig: ScriptBuf::new(),
903 sequence: Sequence(if channel_type_features.supports_anchors_zero_fee_htlc_tx() { 1 } else { 0 }),
904 witness: Witness::new(),
905 }
906}
907
908#[rustfmt::skip]
909pub(crate) fn build_htlc_output(
910 feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, broadcaster_delayed_payment_key: &DelayedPaymentKey, revocation_key: &RevocationKey
911) -> TxOut {
912 let (htlc_success_tx_fee_sat, htlc_timeout_tx_fee_sat) = second_stage_tx_fees_sat(
913 channel_type_features, feerate_per_kw,
914 );
915
916 let output_value = {
917 let total_fee = if htlc.offered {
918 htlc_timeout_tx_fee_sat
919 } else {
920 htlc_success_tx_fee_sat
921 };
922 htlc.to_bitcoin_amount() - Amount::from_sat(total_fee)
923 };
924
925 TxOut {
926 script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_p2wsh(),
927 value: output_value,
928 }
929}
930
931pub fn build_htlc_input_witness(
933 local_sig: &Signature, remote_sig: &Signature, preimage: &Option<PaymentPreimage>,
934 redeem_script: &Script, channel_type_features: &ChannelTypeFeatures,
935) -> Witness {
936 let remote_sighash_type = if channel_type_features.supports_anchors_zero_fee_htlc_tx()
937 || channel_type_features.supports_anchor_zero_fee_commitments()
938 {
939 EcdsaSighashType::SinglePlusAnyoneCanPay
940 } else {
941 EcdsaSighashType::All
942 };
943
944 let mut witness = Witness::new();
945 witness.push(vec![]);
947 witness.push_ecdsa_signature(&BitcoinSignature {
948 signature: *remote_sig,
949 sighash_type: remote_sighash_type,
950 });
951 witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(*local_sig));
952 if let Some(preimage) = preimage {
953 witness.push(preimage.0.to_vec());
954 } else {
955 witness.push(vec![]);
957 }
958 witness.push(redeem_script.to_bytes());
959 witness
960}
961
962pub(crate) fn legacy_deserialization_prevention_marker_for_channel_type_features(
982 features: &ChannelTypeFeatures,
983) -> Option<()> {
984 let mut legacy_version_bit_set = ChannelTypeFeatures::only_static_remote_key();
985 legacy_version_bit_set.set_scid_privacy_required();
986 legacy_version_bit_set.set_zero_conf_required();
987
988 debug_assert!(!legacy_version_bit_set.supports_any_optional_bits());
989 debug_assert!(!features.supports_any_optional_bits());
990 if features.requires_unknown_bits_from(&legacy_version_bit_set) {
991 Some(())
992 } else {
993 None
994 }
995}
996
997#[inline]
999pub fn get_to_countersigner_keyed_anchor_redeemscript(payment_point: &PublicKey) -> ScriptBuf {
1000 Builder::new()
1001 .push_slice(payment_point.serialize())
1002 .push_opcode(opcodes::all::OP_CHECKSIGVERIFY)
1003 .push_int(1)
1004 .push_opcode(opcodes::all::OP_CSV)
1005 .into_script()
1006}
1007
1008pub fn shared_anchor_script_pubkey() -> ScriptBuf {
1010 Builder::new().push_int(1).push_slice(&[0x4e, 0x73]).into_script()
1011}
1012
1013#[rustfmt::skip]
1022pub fn get_keyed_anchor_redeemscript(funding_pubkey: &PublicKey) -> ScriptBuf {
1023 Builder::new().push_slice(funding_pubkey.serialize())
1024 .push_opcode(opcodes::all::OP_CHECKSIG)
1025 .push_opcode(opcodes::all::OP_IFDUP)
1026 .push_opcode(opcodes::all::OP_NOTIF)
1027 .push_int(16)
1028 .push_opcode(opcodes::all::OP_CSV)
1029 .push_opcode(opcodes::all::OP_ENDIF)
1030 .into_script()
1031}
1032
1033pub fn build_keyed_anchor_input_witness(
1036 funding_key: &PublicKey, funding_sig: &Signature,
1037) -> Witness {
1038 let anchor_redeem_script = get_keyed_anchor_redeemscript(funding_key);
1039 let mut ret = Witness::new();
1040 ret.push_ecdsa_signature(&BitcoinSignature::sighash_all(*funding_sig));
1041 ret.push(anchor_redeem_script.as_bytes());
1042 ret
1043}
1044
1045#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1051pub struct ChannelTransactionParameters {
1052 pub holder_pubkeys: ChannelPublicKeys,
1054 pub holder_selected_contest_delay: u16,
1056 pub is_outbound_from_holder: bool,
1059 pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
1062 pub funding_outpoint: Option<chain::transaction::OutPoint>,
1064 pub splice_parent_funding_txid: Option<Txid>,
1075 pub channel_type_features: ChannelTypeFeatures,
1078 pub channel_value_satoshis: u64,
1080}
1081
1082#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1084pub struct CounterpartyChannelTransactionParameters {
1085 pub pubkeys: ChannelPublicKeys,
1087 pub selected_contest_delay: u16,
1089}
1090
1091impl ChannelTransactionParameters {
1092 pub fn is_populated(&self) -> bool {
1094 self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
1095 }
1096
1097 #[rustfmt::skip]
1102 pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters<'_> {
1103 assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
1104 DirectedChannelTransactionParameters {
1105 inner: self,
1106 holder_is_broadcaster: true
1107 }
1108 }
1109
1110 #[rustfmt::skip]
1115 pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters<'_> {
1116 assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
1117 DirectedChannelTransactionParameters {
1118 inner: self,
1119 holder_is_broadcaster: false
1120 }
1121 }
1122
1123 pub(crate) fn make_funding_redeemscript(&self) -> ScriptBuf {
1124 self.make_funding_redeemscript_opt().unwrap()
1125 }
1126
1127 pub(crate) fn make_funding_redeemscript_opt(&self) -> Option<ScriptBuf> {
1128 self.counterparty_parameters.as_ref().map(|p| {
1129 make_funding_redeemscript(
1130 &self.holder_pubkeys.funding_pubkey,
1131 &p.pubkeys.funding_pubkey,
1132 )
1133 })
1134 }
1135
1136 pub fn counterparty_pubkeys(&self) -> Option<&ChannelPublicKeys> {
1138 self.counterparty_parameters.as_ref().map(|params| ¶ms.pubkeys)
1139 }
1140
1141 #[cfg(test)]
1142 #[rustfmt::skip]
1143 pub fn test_dummy(channel_value_satoshis: u64) -> Self {
1144 let dummy_keys = ChannelPublicKeys {
1145 funding_pubkey: PublicKey::from_slice(&[2; 33]).unwrap(),
1146 revocation_basepoint: PublicKey::from_slice(&[2; 33]).unwrap().into(),
1147 payment_point: PublicKey::from_slice(&[2; 33]).unwrap(),
1148 delayed_payment_basepoint: PublicKey::from_slice(&[2; 33]).unwrap().into(),
1149 htlc_basepoint: PublicKey::from_slice(&[2; 33]).unwrap().into(),
1150 };
1151 Self {
1152 holder_pubkeys: dummy_keys.clone(),
1153 holder_selected_contest_delay: 42,
1154 is_outbound_from_holder: true,
1155 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
1156 pubkeys: dummy_keys,
1157 selected_contest_delay: 42,
1158 }),
1159 funding_outpoint: Some(chain::transaction::OutPoint {
1160 txid: Txid::from_byte_array([42; 32]), index: 0
1161 }),
1162 splice_parent_funding_txid: None,
1163 channel_type_features: ChannelTypeFeatures::empty(),
1164 channel_value_satoshis,
1165 }
1166 }
1167}
1168
1169impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, {
1170 (0, pubkeys, required),
1171 (2, selected_contest_delay, required),
1172});
1173
1174impl Writeable for ChannelTransactionParameters {
1175 #[rustfmt::skip]
1176 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1177 let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
1178 write_tlv_fields!(writer, {
1179 (0, self.holder_pubkeys, required),
1180 (2, self.holder_selected_contest_delay, required),
1181 (4, self.is_outbound_from_holder, required),
1182 (6, self.counterparty_parameters, option),
1183 (8, self.funding_outpoint, option),
1184 (10, legacy_deserialization_prevention_marker, option),
1185 (11, self.channel_type_features, required),
1186 (12, self.splice_parent_funding_txid, option),
1187 (13, self.channel_value_satoshis, required),
1188 });
1189 Ok(())
1190 }
1191}
1192
1193impl ReadableArgs<Option<u64>> for ChannelTransactionParameters {
1194 #[rustfmt::skip]
1195 fn read<R: io::Read>(reader: &mut R, read_args: Option<u64>) -> Result<Self, DecodeError> {
1196 let mut holder_pubkeys = RequiredWrapper(None);
1197 let mut holder_selected_contest_delay = RequiredWrapper(None);
1198 let mut is_outbound_from_holder = RequiredWrapper(None);
1199 let mut counterparty_parameters = None;
1200 let mut funding_outpoint = None;
1201 let mut splice_parent_funding_txid = None;
1202 let mut _legacy_deserialization_prevention_marker: Option<()> = None;
1203 let mut channel_type_features = None;
1204 let mut channel_value_satoshis = None;
1205
1206 read_tlv_fields!(reader, {
1207 (0, holder_pubkeys, required),
1208 (2, holder_selected_contest_delay, required),
1209 (4, is_outbound_from_holder, required),
1210 (6, counterparty_parameters, option),
1211 (8, funding_outpoint, option),
1212 (10, _legacy_deserialization_prevention_marker, option),
1213 (11, channel_type_features, option),
1214 (12, splice_parent_funding_txid, option),
1215 (13, channel_value_satoshis, option),
1216 });
1217
1218 let channel_value_satoshis = match read_args {
1219 None => channel_value_satoshis.ok_or(DecodeError::InvalidValue)?,
1220 Some(expected_value) => {
1221 let channel_value_satoshis = channel_value_satoshis.unwrap_or(expected_value);
1222 if channel_value_satoshis == expected_value {
1223 channel_value_satoshis
1224 } else {
1225 return Err(DecodeError::InvalidValue);
1226 }
1227 },
1228 };
1229
1230 let mut additional_features = ChannelTypeFeatures::empty();
1231 additional_features.set_anchors_nonzero_fee_htlc_tx_required();
1232 chain::package::verify_channel_type_features(&channel_type_features, Some(&additional_features))?;
1233
1234 Ok(Self {
1235 holder_pubkeys: holder_pubkeys.0.unwrap(),
1236 holder_selected_contest_delay: holder_selected_contest_delay.0.unwrap(),
1237 is_outbound_from_holder: is_outbound_from_holder.0.unwrap(),
1238 counterparty_parameters,
1239 funding_outpoint,
1240 splice_parent_funding_txid,
1241 channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key()),
1242 channel_value_satoshis,
1243 })
1244 }
1245}
1246
1247pub struct DirectedChannelTransactionParameters<'a> {
1253 inner: &'a ChannelTransactionParameters,
1255 holder_is_broadcaster: bool,
1257}
1258
1259impl<'a> DirectedChannelTransactionParameters<'a> {
1260 pub fn broadcaster_pubkeys(&self) -> &'a ChannelPublicKeys {
1262 if self.holder_is_broadcaster {
1263 &self.inner.holder_pubkeys
1264 } else {
1265 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
1266 }
1267 }
1268
1269 pub fn countersignatory_pubkeys(&self) -> &'a ChannelPublicKeys {
1271 if self.holder_is_broadcaster {
1272 &self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
1273 } else {
1274 &self.inner.holder_pubkeys
1275 }
1276 }
1277
1278 #[rustfmt::skip]
1281 pub fn contest_delay(&self) -> u16 {
1282 let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
1283 if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
1284 }
1285
1286 #[rustfmt::skip]
1291 pub fn is_outbound(&self) -> bool {
1292 if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
1293 }
1294
1295 pub fn funding_outpoint(&self) -> OutPoint {
1297 self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
1298 }
1299
1300 pub fn channel_type_features(&self) -> &'a ChannelTypeFeatures {
1302 &self.inner.channel_type_features
1303 }
1304
1305 pub fn channel_value_satoshis(&self) -> u64 {
1307 self.inner.channel_value_satoshis
1308 }
1309}
1310
1311#[derive(Clone, Debug)]
1315pub struct HolderCommitmentTransaction {
1316 inner: CommitmentTransaction,
1317 pub counterparty_sig: Signature,
1319 pub counterparty_htlc_sigs: Vec<Signature>,
1321 holder_sig_first: bool,
1324}
1325
1326impl Deref for HolderCommitmentTransaction {
1327 type Target = CommitmentTransaction;
1328
1329 #[rustfmt::skip]
1330 fn deref(&self) -> &Self::Target { &self.inner }
1331}
1332
1333impl Eq for HolderCommitmentTransaction {}
1334impl PartialEq for HolderCommitmentTransaction {
1335 fn eq(&self, o: &Self) -> bool {
1337 self.inner == o.inner
1338 }
1339}
1340
1341impl_writeable_tlv_based!(HolderCommitmentTransaction, {
1342 (0, inner, required),
1343 (2, counterparty_sig, required),
1344 (4, holder_sig_first, required),
1345 (6, counterparty_htlc_sigs, required_vec),
1346});
1347
1348impl HolderCommitmentTransaction {
1349 #[cfg(test)]
1350 #[rustfmt::skip]
1351 pub fn dummy(channel_value_satoshis: u64, funding_outpoint: chain::transaction::OutPoint, nondust_htlcs: Vec<HTLCOutputInCommitment>) -> Self {
1352 let secp_ctx = Secp256k1::new();
1353 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1354 let dummy_sig = sign(&secp_ctx, &secp256k1::Message::from_digest([42; 32]), &SecretKey::from_slice(&[42; 32]).unwrap());
1355
1356 let channel_pubkeys = ChannelPublicKeys {
1357 funding_pubkey: dummy_key.clone(),
1358 revocation_basepoint: RevocationBasepoint::from(dummy_key),
1359 payment_point: dummy_key.clone(),
1360 delayed_payment_basepoint: DelayedPaymentBasepoint::from(dummy_key.clone()),
1361 htlc_basepoint: HtlcBasepoint::from(dummy_key.clone())
1362 };
1363 let channel_parameters = ChannelTransactionParameters {
1364 holder_pubkeys: channel_pubkeys.clone(),
1365 holder_selected_contest_delay: 0,
1366 is_outbound_from_holder: false,
1367 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
1368 funding_outpoint: Some(funding_outpoint),
1369 splice_parent_funding_txid: None,
1370 channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
1371 channel_value_satoshis,
1372 };
1373 let mut counterparty_htlc_sigs = Vec::new();
1374 for _ in 0..nondust_htlcs.len() {
1375 counterparty_htlc_sigs.push(dummy_sig);
1376 }
1377 let inner = CommitmentTransaction::new(0, &dummy_key, 0, 0, 0, nondust_htlcs, &channel_parameters.as_counterparty_broadcastable(), &secp_ctx);
1378 HolderCommitmentTransaction {
1379 inner,
1380 counterparty_sig: dummy_sig,
1381 counterparty_htlc_sigs,
1382 holder_sig_first: false
1383 }
1384 }
1385
1386 #[rustfmt::skip]
1389 pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
1390 Self {
1391 inner: commitment_tx,
1392 counterparty_sig,
1393 counterparty_htlc_sigs,
1394 holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
1395 }
1396 }
1397
1398 #[rustfmt::skip]
1399 pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
1400 let mut tx = self.inner.built.transaction.clone();
1402 tx.input[0].witness.push(Vec::new());
1403
1404 if self.holder_sig_first {
1405 tx.input[0].witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(holder_sig));
1406 tx.input[0].witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(self.counterparty_sig));
1407 } else {
1408 tx.input[0].witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(self.counterparty_sig));
1409 tx.input[0].witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(holder_sig));
1410 }
1411
1412 tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
1413 tx
1414 }
1415}
1416
1417#[derive(Clone, Debug)]
1419pub struct BuiltCommitmentTransaction {
1420 pub transaction: Transaction,
1422 pub txid: Txid,
1427}
1428
1429impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
1430 (0, transaction, required),
1431 (2, txid, required),
1432});
1433
1434impl BuiltCommitmentTransaction {
1435 #[rustfmt::skip]
1439 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1440 let sighash = &sighash::SighashCache::new(&self.transaction).p2wsh_signature_hash(0, funding_redeemscript, Amount::from_sat(channel_value_satoshis), EcdsaSighashType::All).unwrap()[..];
1441 hash_to_message!(sighash)
1442 }
1443
1444 pub fn sign_counterparty_commitment<T: secp256k1::Signing>(
1446 &self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64,
1447 secp_ctx: &Secp256k1<T>,
1448 ) -> Signature {
1449 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1450 sign(secp_ctx, &sighash, funding_key)
1451 }
1452
1453 pub fn sign_holder_commitment<T: secp256k1::Signing, ES: Deref>(
1455 &self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64,
1456 entropy_source: &ES, secp_ctx: &Secp256k1<T>,
1457 ) -> Signature
1458 where
1459 ES::Target: EntropySource,
1460 {
1461 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1462 sign_with_aux_rand(secp_ctx, &sighash, funding_key, entropy_source)
1463 }
1464}
1465
1466#[derive(Clone, Hash, PartialEq, Eq)]
1472pub struct ClosingTransaction {
1473 to_holder_value_sat: Amount,
1474 to_counterparty_value_sat: Amount,
1475 to_holder_script: ScriptBuf,
1476 to_counterparty_script: ScriptBuf,
1477 built: Transaction,
1478}
1479
1480impl ClosingTransaction {
1481 #[rustfmt::skip]
1483 pub fn new(
1484 to_holder_value_sat: u64,
1485 to_counterparty_value_sat: u64,
1486 to_holder_script: ScriptBuf,
1487 to_counterparty_script: ScriptBuf,
1488 funding_outpoint: OutPoint,
1489 ) -> Self {
1490 let to_holder_value_sat = Amount::from_sat(to_holder_value_sat);
1491 let to_counterparty_value_sat = Amount::from_sat(to_counterparty_value_sat);
1492 let built = build_closing_transaction(
1493 to_holder_value_sat, to_counterparty_value_sat,
1494 to_holder_script.clone(), to_counterparty_script.clone(),
1495 funding_outpoint
1496 );
1497 ClosingTransaction {
1498 to_holder_value_sat,
1499 to_counterparty_value_sat,
1500 to_holder_script,
1501 to_counterparty_script,
1502 built
1503 }
1504 }
1505
1506 pub fn trust(&self) -> TrustedClosingTransaction<'_> {
1513 TrustedClosingTransaction { inner: self }
1514 }
1515
1516 #[rustfmt::skip]
1523 pub fn verify(&self, funding_outpoint: OutPoint) -> Result<TrustedClosingTransaction<'_>, ()> {
1524 let built = build_closing_transaction(
1525 self.to_holder_value_sat, self.to_counterparty_value_sat,
1526 self.to_holder_script.clone(), self.to_counterparty_script.clone(),
1527 funding_outpoint
1528 );
1529 if self.built != built {
1530 return Err(())
1531 }
1532 Ok(TrustedClosingTransaction { inner: self })
1533 }
1534
1535 pub fn to_holder_value_sat(&self) -> u64 {
1537 self.to_holder_value_sat.to_sat()
1538 }
1539
1540 pub fn to_counterparty_value_sat(&self) -> u64 {
1542 self.to_counterparty_value_sat.to_sat()
1543 }
1544
1545 pub fn to_holder_script(&self) -> &Script {
1547 &self.to_holder_script
1548 }
1549
1550 pub fn to_counterparty_script(&self) -> &Script {
1552 &self.to_counterparty_script
1553 }
1554}
1555
1556pub struct TrustedClosingTransaction<'a> {
1563 inner: &'a ClosingTransaction,
1564}
1565
1566impl<'a> Deref for TrustedClosingTransaction<'a> {
1567 type Target = ClosingTransaction;
1568
1569 #[rustfmt::skip]
1570 fn deref(&self) -> &Self::Target { self.inner }
1571}
1572
1573impl<'a> TrustedClosingTransaction<'a> {
1574 pub fn built_transaction(&self) -> &'a Transaction {
1576 &self.inner.built
1577 }
1578
1579 #[rustfmt::skip]
1583 pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1584 let sighash = &sighash::SighashCache::new(&self.inner.built).p2wsh_signature_hash(0, funding_redeemscript, Amount::from_sat(channel_value_satoshis), EcdsaSighashType::All).unwrap()[..];
1585 hash_to_message!(sighash)
1586 }
1587
1588 pub fn sign<T: secp256k1::Signing>(
1591 &self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64,
1592 secp_ctx: &Secp256k1<T>,
1593 ) -> Signature {
1594 let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1595 sign(secp_ctx, &sighash, funding_key)
1596 }
1597}
1598
1599#[derive(Clone, Debug)]
1606pub struct CommitmentTransaction {
1607 commitment_number: u64,
1608 to_broadcaster_value_sat: Amount,
1609 to_countersignatory_value_sat: Amount,
1610 to_broadcaster_delay: Option<u16>, feerate_per_kw: u32,
1612 nondust_htlcs: Vec<HTLCOutputInCommitment>,
1615 channel_type_features: ChannelTypeFeatures,
1617 keys: TxCreationKeys,
1619 built: BuiltCommitmentTransaction,
1621}
1622
1623impl Eq for CommitmentTransaction {}
1624impl PartialEq for CommitmentTransaction {
1625 #[rustfmt::skip]
1626 fn eq(&self, o: &Self) -> bool {
1627 let eq = self.commitment_number == o.commitment_number &&
1628 self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
1629 self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
1630 self.feerate_per_kw == o.feerate_per_kw &&
1631 self.nondust_htlcs == o.nondust_htlcs &&
1632 self.channel_type_features == o.channel_type_features &&
1633 self.keys == o.keys;
1634 if eq {
1635 debug_assert_eq!(self.built.transaction, o.built.transaction);
1636 debug_assert_eq!(self.built.txid, o.built.txid);
1637 }
1638 eq
1639 }
1640}
1641
1642impl Writeable for CommitmentTransaction {
1643 #[rustfmt::skip]
1644 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1645 let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
1646 write_tlv_fields!(writer, {
1647 (0, self.commitment_number, required),
1648 (1, self.to_broadcaster_delay, option),
1649 (2, self.to_broadcaster_value_sat, required),
1650 (4, self.to_countersignatory_value_sat, required),
1651 (6, self.feerate_per_kw, required),
1652 (8, self.keys, required),
1653 (10, self.built, required),
1654 (12, self.nondust_htlcs, required_vec),
1655 (14, legacy_deserialization_prevention_marker, option),
1656 (15, self.channel_type_features, required),
1657 });
1658 Ok(())
1659 }
1660}
1661
1662impl Readable for CommitmentTransaction {
1663 #[rustfmt::skip]
1664 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1665 _init_and_read_len_prefixed_tlv_fields!(reader, {
1666 (0, commitment_number, required),
1667 (1, to_broadcaster_delay, option),
1668 (2, to_broadcaster_value_sat, required),
1669 (4, to_countersignatory_value_sat, required),
1670 (6, feerate_per_kw, required),
1671 (8, keys, required),
1672 (10, built, required),
1673 (12, nondust_htlcs, required_vec),
1674 (14, _legacy_deserialization_prevention_marker, (option, explicit_type: ())),
1675 (15, channel_type_features, option),
1676 });
1677
1678 let mut additional_features = ChannelTypeFeatures::empty();
1679 additional_features.set_anchors_nonzero_fee_htlc_tx_required();
1680 chain::package::verify_channel_type_features(&channel_type_features, Some(&additional_features))?;
1681
1682 Ok(Self {
1683 commitment_number: commitment_number.0.unwrap(),
1684 to_broadcaster_value_sat: to_broadcaster_value_sat.0.unwrap(),
1685 to_countersignatory_value_sat: to_countersignatory_value_sat.0.unwrap(),
1686 to_broadcaster_delay,
1687 feerate_per_kw: feerate_per_kw.0.unwrap(),
1688 keys: keys.0.unwrap(),
1689 built: built.0.unwrap(),
1690 nondust_htlcs,
1691 channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
1692 })
1693 }
1694}
1695
1696impl CommitmentTransaction {
1697 #[rustfmt::skip]
1703 pub fn new(commitment_number: u64, per_commitment_point: &PublicKey, to_broadcaster_value_sat: u64, to_countersignatory_value_sat: u64, feerate_per_kw: u32, mut nondust_htlcs: Vec<HTLCOutputInCommitment>, channel_parameters: &DirectedChannelTransactionParameters, secp_ctx: &Secp256k1<secp256k1::All>) -> CommitmentTransaction {
1704 let to_broadcaster_value_sat = Amount::from_sat(to_broadcaster_value_sat);
1705 let to_countersignatory_value_sat = Amount::from_sat(to_countersignatory_value_sat);
1706 let keys = TxCreationKeys::from_channel_static_keys(per_commitment_point, channel_parameters.broadcaster_pubkeys(), channel_parameters.countersignatory_pubkeys(), secp_ctx);
1707
1708 let outputs = Self::build_outputs_and_htlcs(&keys, to_broadcaster_value_sat, to_countersignatory_value_sat, &mut nondust_htlcs, channel_parameters);
1712
1713 let (obscured_commitment_transaction_number, txins) = Self::build_inputs(commitment_number, channel_parameters);
1714 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs, channel_parameters);
1715 let txid = transaction.compute_txid();
1716 CommitmentTransaction {
1717 commitment_number,
1718 to_broadcaster_value_sat,
1719 to_countersignatory_value_sat,
1720 to_broadcaster_delay: Some(channel_parameters.contest_delay()),
1721 feerate_per_kw,
1722 nondust_htlcs,
1723 channel_type_features: channel_parameters.channel_type_features().clone(),
1724 keys,
1725 built: BuiltCommitmentTransaction {
1726 transaction,
1727 txid
1728 },
1729 }
1730 }
1731
1732 pub fn with_non_zero_fee_anchors(mut self) -> Self {
1736 self.channel_type_features.set_anchors_nonzero_fee_htlc_tx_required();
1737 self
1738 }
1739
1740 #[rustfmt::skip]
1750 fn is_left_greater(i: usize, txouts: &Vec<TxOut>, nondust_htlcs: &Vec<HTLCOutputInCommitment>) -> bool {
1751 txouts[i - 1].value.cmp(&txouts[i].value)
1752 .then(txouts[i - 1].script_pubkey.cmp(&txouts[i].script_pubkey))
1753 .then(nondust_htlcs[i - 1].cltv_expiry.cmp(&nondust_htlcs[i].cltv_expiry))
1754 .then(nondust_htlcs[i - 1].payment_hash.cmp(&nondust_htlcs[i].payment_hash))
1758 .is_gt()
1759 }
1760
1761 #[rustfmt::skip]
1762 fn rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters) -> Result<BuiltCommitmentTransaction, ()> {
1763 let (obscured_commitment_transaction_number, txins) = Self::build_inputs(self.commitment_number, channel_parameters);
1764
1765 let mut outputs = Self::build_htlc_outputs(keys, &self.nondust_htlcs, channel_parameters.channel_type_features());
1767
1768 let nondust_htlcs_value_sum_sat = self.nondust_htlcs.iter().map(|htlc| htlc.to_bitcoin_amount()).sum();
1769
1770 if (1..outputs.len()).into_iter().any(|i| Self::is_left_greater(i, &outputs, &self.nondust_htlcs)) {
1773 return Err(())
1774 }
1775
1776 let insert_non_htlc_output = |non_htlc_output: TxOut| {
1778 let idx = match outputs.binary_search_by(|output| output.value.cmp(&non_htlc_output.value).then(output.script_pubkey.cmp(&non_htlc_output.script_pubkey))) {
1779 Ok(i) => i,
1782 Err(i) => i,
1783 };
1784 outputs.insert(idx, non_htlc_output);
1785 };
1786
1787 Self::insert_non_htlc_outputs(
1788 keys,
1789 self.to_broadcaster_value_sat,
1790 self.to_countersignatory_value_sat,
1791 channel_parameters,
1792 nondust_htlcs_value_sum_sat,
1793 insert_non_htlc_output
1794 );
1795
1796 let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs, channel_parameters);
1797 let txid = transaction.compute_txid();
1798 let built_transaction = BuiltCommitmentTransaction {
1799 transaction,
1800 txid
1801 };
1802 Ok(built_transaction)
1803 }
1804
1805 #[rustfmt::skip]
1806 fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>, channel_parameters: &DirectedChannelTransactionParameters) -> Transaction {
1807 let version = if channel_parameters.channel_type_features().supports_anchor_zero_fee_commitments() {
1808 Version::non_standard(3)
1809 } else {
1810 Version::TWO
1811 };
1812 Transaction {
1813 version,
1814 lock_time: LockTime::from_consensus(((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32)),
1815 input: txins,
1816 output: outputs,
1817 }
1818 }
1819
1820 #[rustfmt::skip]
1821 fn build_outputs_and_htlcs(
1822 keys: &TxCreationKeys,
1823 to_broadcaster_value_sat: Amount,
1824 to_countersignatory_value_sat: Amount,
1825 nondust_htlcs: &mut Vec<HTLCOutputInCommitment>,
1826 channel_parameters: &DirectedChannelTransactionParameters
1827 ) -> Vec<TxOut> {
1828 let mut outputs = Self::build_sorted_htlc_outputs(keys, nondust_htlcs, channel_parameters.channel_type_features());
1831
1832 let nondust_htlcs_value_sum_sat = nondust_htlcs.iter().map(|htlc| htlc.to_bitcoin_amount()).sum();
1833
1834 nondust_htlcs
1837 .iter_mut()
1838 .enumerate()
1839 .for_each(|(i, htlc)| htlc.transaction_output_index = Some(i as u32));
1840
1841 let insert_non_htlc_output = |non_htlc_output: TxOut| {
1843 let idx = match outputs.binary_search_by(|output| output.value.cmp(&non_htlc_output.value).then(output.script_pubkey.cmp(&non_htlc_output.script_pubkey))) {
1844 Ok(i) => i,
1847 Err(i) => i,
1848 };
1849 outputs.insert(idx, non_htlc_output);
1850
1851 nondust_htlcs
1854 .iter_mut()
1855 .rev()
1856 .map_while(|htlc| {
1857 let i = htlc.transaction_output_index.as_mut().unwrap();
1859 (*i >= idx as u32).then(|| i)
1860 })
1861 .for_each(|i| *i += 1);
1862 };
1863
1864 Self::insert_non_htlc_outputs(
1865 keys,
1866 to_broadcaster_value_sat,
1867 to_countersignatory_value_sat,
1868 channel_parameters,
1869 nondust_htlcs_value_sum_sat,
1870 insert_non_htlc_output
1871 );
1872
1873 outputs
1874 }
1875
1876 #[rustfmt::skip]
1877 fn insert_non_htlc_outputs<F>(
1878 keys: &TxCreationKeys,
1879 to_broadcaster_value_sat: Amount,
1880 to_countersignatory_value_sat: Amount,
1881 channel_parameters: &DirectedChannelTransactionParameters,
1882 nondust_htlcs_value_sum_sat: Amount,
1883 mut insert_non_htlc_output: F,
1884 ) where
1885 F: FnMut(TxOut),
1886 {
1887 let countersignatory_payment_point = &channel_parameters.countersignatory_pubkeys().payment_point;
1888 let countersignatory_funding_key = &channel_parameters.countersignatory_pubkeys().funding_pubkey;
1889 let broadcaster_funding_key = &channel_parameters.broadcaster_pubkeys().funding_pubkey;
1890 let channel_type = channel_parameters.channel_type_features();
1891 let contest_delay = channel_parameters.contest_delay();
1892 let tx_has_htlc_outputs = nondust_htlcs_value_sum_sat != Amount::ZERO;
1893
1894 if to_countersignatory_value_sat > Amount::ZERO {
1895 let script = if channel_type.supports_anchors_zero_fee_htlc_tx() {
1896 get_to_countersigner_keyed_anchor_redeemscript(countersignatory_payment_point).to_p2wsh()
1897 } else {
1898 ScriptBuf::new_p2wpkh(&Hash160::hash(&countersignatory_payment_point.serialize()).into())
1899 };
1900 insert_non_htlc_output(TxOut {
1901 script_pubkey: script,
1902 value: to_countersignatory_value_sat,
1903 });
1904 }
1905
1906 if to_broadcaster_value_sat > Amount::ZERO {
1907 let redeem_script = get_revokeable_redeemscript(
1908 &keys.revocation_key,
1909 contest_delay,
1910 &keys.broadcaster_delayed_payment_key,
1911 );
1912 insert_non_htlc_output(TxOut {
1913 script_pubkey: redeem_script.to_p2wsh(),
1914 value: to_broadcaster_value_sat,
1915 });
1916 }
1917
1918 if channel_type.supports_anchors_zero_fee_htlc_tx() {
1919 if to_broadcaster_value_sat > Amount::ZERO || tx_has_htlc_outputs {
1920 let anchor_script = get_keyed_anchor_redeemscript(broadcaster_funding_key);
1921 insert_non_htlc_output(TxOut {
1922 script_pubkey: anchor_script.to_p2wsh(),
1923 value: Amount::from_sat(ANCHOR_OUTPUT_VALUE_SATOSHI),
1924 });
1925 }
1926
1927 if to_countersignatory_value_sat > Amount::ZERO || tx_has_htlc_outputs {
1928 let anchor_script = get_keyed_anchor_redeemscript(countersignatory_funding_key);
1929 insert_non_htlc_output(TxOut {
1930 script_pubkey: anchor_script.to_p2wsh(),
1931 value: Amount::from_sat(ANCHOR_OUTPUT_VALUE_SATOSHI),
1932 });
1933 }
1934 }
1935
1936 if channel_type.supports_anchor_zero_fee_commitments() {
1937 let channel_value_satoshis = Amount::from_sat(channel_parameters.channel_value_satoshis());
1938 let trimmed_sum_sat = channel_value_satoshis - nondust_htlcs_value_sum_sat - to_broadcaster_value_sat - to_countersignatory_value_sat;
1940 insert_non_htlc_output(TxOut {
1941 script_pubkey: shared_anchor_script_pubkey(),
1942 value: cmp::min(Amount::from_sat(P2A_MAX_VALUE), trimmed_sum_sat),
1943 });
1944 }
1945 }
1946
1947 #[rustfmt::skip]
1948 fn build_htlc_outputs(keys: &TxCreationKeys, nondust_htlcs: &Vec<HTLCOutputInCommitment>, channel_type: &ChannelTypeFeatures) -> Vec<TxOut> {
1949 let mut txouts = Vec::with_capacity(nondust_htlcs.len() + 4);
1951
1952 for htlc in nondust_htlcs {
1953 let script = get_htlc_redeemscript(htlc, channel_type, keys);
1954 let txout = TxOut {
1955 script_pubkey: script.to_p2wsh(),
1956 value: htlc.to_bitcoin_amount(),
1957 };
1958 txouts.push(txout);
1959 }
1960
1961 txouts
1962 }
1963
1964 #[rustfmt::skip]
1965 fn build_sorted_htlc_outputs(
1966 keys: &TxCreationKeys,
1967 nondust_htlcs: &mut Vec<HTLCOutputInCommitment>,
1968 channel_type: &ChannelTypeFeatures
1969 ) -> Vec<TxOut> {
1970 let mut txouts = Self::build_htlc_outputs(keys, nondust_htlcs, channel_type);
1972
1973 for i in 1..txouts.len() {
1986 let mut j = i;
1987 while j > 0 && Self::is_left_greater(j, &txouts, &nondust_htlcs) {
1991 txouts.swap(j - 1, j);
1992 nondust_htlcs.swap(j - 1, j);
1993 j -= 1;
1994 }
1995 }
1996
1997 txouts
1998 }
1999
2000 #[rustfmt::skip]
2001 fn build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
2002 let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
2003 let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
2004 let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
2005 &broadcaster_pubkeys.payment_point,
2006 &countersignatory_pubkeys.payment_point,
2007 channel_parameters.is_outbound(),
2008 );
2009
2010 let obscured_commitment_transaction_number =
2011 commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
2012
2013 let txins = {
2014 let ins: Vec<TxIn> = vec![TxIn {
2015 previous_output: channel_parameters.funding_outpoint(),
2016 script_sig: ScriptBuf::new(),
2017 sequence: Sequence(((0x80 as u32) << 8 * 3)
2018 | ((obscured_commitment_transaction_number >> 3 * 8) as u32)),
2019 witness: Witness::new(),
2020 }];
2021 ins
2022 };
2023 (obscured_commitment_transaction_number, txins)
2024 }
2025
2026 pub fn commitment_number(&self) -> u64 {
2028 self.commitment_number
2029 }
2030
2031 pub fn per_commitment_point(&self) -> PublicKey {
2033 self.keys.per_commitment_point
2034 }
2035
2036 pub fn to_broadcaster_value_sat(&self) -> u64 {
2038 self.to_broadcaster_value_sat.to_sat()
2039 }
2040
2041 pub fn to_countersignatory_value_sat(&self) -> u64 {
2043 self.to_countersignatory_value_sat.to_sat()
2044 }
2045
2046 pub fn negotiated_feerate_per_kw(&self) -> u32 {
2051 self.feerate_per_kw
2052 }
2053
2054 pub fn nondust_htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
2061 &self.nondust_htlcs
2062 }
2063
2064 pub fn trust(&self) -> TrustedCommitmentTransaction<'_> {
2071 TrustedCommitmentTransaction { inner: self }
2072 }
2073
2074 #[rustfmt::skip]
2081 pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction<'_>, ()> {
2082 let per_commitment_point = &self.keys.per_commitment_point;
2084 let keys = TxCreationKeys::from_channel_static_keys(per_commitment_point, channel_parameters.broadcaster_pubkeys(), channel_parameters.countersignatory_pubkeys(), secp_ctx);
2085 if keys != self.keys {
2086 return Err(());
2087 }
2088 let tx = self.rebuild_transaction(&keys, channel_parameters)?;
2089 if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
2090 return Err(());
2091 }
2092 Ok(TrustedCommitmentTransaction { inner: self })
2093 }
2094}
2095
2096pub struct TrustedCommitmentTransaction<'a> {
2103 inner: &'a CommitmentTransaction,
2104}
2105
2106impl<'a> Deref for TrustedCommitmentTransaction<'a> {
2107 type Target = CommitmentTransaction;
2108
2109 #[rustfmt::skip]
2110 fn deref(&self) -> &Self::Target { self.inner }
2111}
2112
2113impl<'a> TrustedCommitmentTransaction<'a> {
2114 pub fn txid(&self) -> Txid {
2116 self.inner.built.txid
2117 }
2118
2119 pub fn built_transaction(&self) -> &'a BuiltCommitmentTransaction {
2121 &self.inner.built
2122 }
2123
2124 pub fn keys(&self) -> &'a TxCreationKeys {
2126 &self.inner.keys
2127 }
2128
2129 pub fn channel_type_features(&self) -> &'a ChannelTypeFeatures {
2131 &self.inner.channel_type_features
2132 }
2133
2134 #[rustfmt::skip]
2141 pub fn get_htlc_sigs<T: secp256k1::Signing, ES: Deref>(
2142 &self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters,
2143 entropy_source: &ES, secp_ctx: &Secp256k1<T>,
2144 ) -> Result<Vec<Signature>, ()> where ES::Target: EntropySource {
2145 let inner = self.inner;
2146 let keys = &inner.keys;
2147 let txid = inner.built.txid;
2148 let mut ret = Vec::with_capacity(inner.nondust_htlcs.len());
2149 let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key);
2150
2151 for this_htlc in inner.nondust_htlcs.iter() {
2152 assert!(this_htlc.transaction_output_index.is_some());
2153 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);
2154
2155 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);
2156
2157 let sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).p2wsh_signature_hash(0, &htlc_redeemscript, this_htlc.to_bitcoin_amount(), EcdsaSighashType::All).unwrap()[..]);
2158 ret.push(sign_with_aux_rand(secp_ctx, &sighash, &holder_htlc_key, entropy_source));
2159 }
2160 Ok(ret)
2161 }
2162
2163 #[rustfmt::skip]
2173 pub fn revokeable_output_index(&self) -> Option<usize> {
2174 let revokeable_redeemscript = get_revokeable_redeemscript(
2175 &self.keys.revocation_key,
2176 self.to_broadcaster_delay?,
2177 &self.keys.broadcaster_delayed_payment_key,
2178 );
2179 let revokeable_p2wsh = revokeable_redeemscript.to_p2wsh();
2180 let outputs = &self.inner.built.transaction.output;
2181 outputs.iter().enumerate()
2182 .find(|(_, out)| out.script_pubkey == revokeable_p2wsh)
2183 .map(|(idx, _)| idx)
2184 }
2185
2186 #[rustfmt::skip]
2198 pub fn build_to_local_justice_tx(&self, feerate_per_kw: u64, destination_script: ScriptBuf)
2199 -> Result<Transaction, ()> {
2200 let output_idx = self.revokeable_output_index().ok_or(())?;
2201 let input = vec![TxIn {
2202 previous_output: OutPoint {
2203 txid: self.trust().txid(),
2204 vout: output_idx as u32,
2205 },
2206 script_sig: ScriptBuf::new(),
2207 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
2208 witness: Witness::new(),
2209 }];
2210 let value = self.inner.built.transaction.output[output_idx].value;
2211 let output = vec![TxOut {
2212 script_pubkey: destination_script,
2213 value,
2214 }];
2215 let mut justice_tx = Transaction {
2216 version: Version::TWO,
2217 lock_time: LockTime::ZERO,
2218 input,
2219 output,
2220 };
2221 let weight = justice_tx.weight().to_wu() + WEIGHT_REVOKED_OUTPUT;
2222 let fee = Amount::from_sat(fee_for_weight(feerate_per_kw as u32, weight));
2223 justice_tx.output[0].value = value.checked_sub(fee).ok_or(())?;
2224 Ok(justice_tx)
2225 }
2226}
2227
2228pub fn get_commitment_transaction_number_obscure_factor(
2235 broadcaster_payment_basepoint: &PublicKey, countersignatory_payment_basepoint: &PublicKey,
2236 outbound_from_broadcaster: bool,
2237) -> u64 {
2238 let mut sha = Sha256::engine();
2239
2240 if outbound_from_broadcaster {
2241 sha.input(&broadcaster_payment_basepoint.serialize());
2242 sha.input(&countersignatory_payment_basepoint.serialize());
2243 } else {
2244 sha.input(&countersignatory_payment_basepoint.serialize());
2245 sha.input(&broadcaster_payment_basepoint.serialize());
2246 }
2247 let res = Sha256::from_engine(sha).to_byte_array();
2248
2249 ((res[26] as u64) << 5 * 8)
2250 | ((res[27] as u64) << 4 * 8)
2251 | ((res[28] as u64) << 3 * 8)
2252 | ((res[29] as u64) << 2 * 8)
2253 | ((res[30] as u64) << 1 * 8)
2254 | ((res[31] as u64) << 0 * 8)
2255}
2256
2257#[cfg(test)]
2258mod tests {
2259 use super::{ChannelPublicKeys, CounterpartyCommitmentSecrets};
2260 use crate::chain;
2261 use crate::ln::chan_utils::{
2262 get_htlc_redeemscript, get_keyed_anchor_redeemscript,
2263 get_to_countersigner_keyed_anchor_redeemscript, shared_anchor_script_pubkey,
2264 BuiltCommitmentTransaction, ChannelTransactionParameters, CommitmentTransaction,
2265 CounterpartyChannelTransactionParameters, HTLCOutputInCommitment,
2266 TrustedCommitmentTransaction,
2267 };
2268 use crate::sign::{ChannelSigner, SignerProvider};
2269 use crate::types::features::ChannelTypeFeatures;
2270 use crate::types::payment::PaymentHash;
2271 use crate::util::test_utils;
2272 use bitcoin::hashes::Hash;
2273 use bitcoin::hex::FromHex;
2274 use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey};
2275 use bitcoin::PublicKey as BitcoinPublicKey;
2276 use bitcoin::{CompressedPublicKey, Network, ScriptBuf, Txid};
2277
2278 #[allow(unused_imports)]
2279 use crate::prelude::*;
2280
2281 struct TestCommitmentTxBuilder {
2282 commitment_number: u64,
2283 per_commitment_point: PublicKey,
2284 feerate_per_kw: u32,
2285 channel_parameters: ChannelTransactionParameters,
2286 counterparty_pubkeys: ChannelPublicKeys,
2287 secp_ctx: Secp256k1<secp256k1::All>,
2288 }
2289
2290 impl TestCommitmentTxBuilder {
2291 #[rustfmt::skip]
2292 fn new() -> Self {
2293 let secp_ctx = Secp256k1::new();
2294 let seed = [42; 32];
2295 let network = Network::Testnet;
2296 let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
2297 let signer = keys_provider.derive_channel_signer(keys_provider.generate_channel_keys_id(false, 0));
2298 let counterparty_signer = keys_provider.derive_channel_signer(keys_provider.generate_channel_keys_id(true, 1));
2299 let per_commitment_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
2300 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
2301 let holder_pubkeys = signer.pubkeys(&secp_ctx);
2302 let counterparty_pubkeys = counterparty_signer.pubkeys(&secp_ctx).clone();
2303 let channel_parameters = ChannelTransactionParameters {
2304 holder_pubkeys: holder_pubkeys.clone(),
2305 holder_selected_contest_delay: 0,
2306 is_outbound_from_holder: false,
2307 counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: counterparty_pubkeys.clone(), selected_contest_delay: 0 }),
2308 funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
2309 splice_parent_funding_txid: None,
2310 channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
2311 channel_value_satoshis: 4000,
2312 };
2313
2314 Self {
2315 commitment_number: 0,
2316 per_commitment_point,
2317 feerate_per_kw: 1,
2318 channel_parameters,
2319 counterparty_pubkeys,
2320 secp_ctx,
2321 }
2322 }
2323
2324 #[rustfmt::skip]
2325 fn build(&self, to_broadcaster_sats: u64, to_countersignatory_sats: u64, nondust_htlcs: Vec<HTLCOutputInCommitment>) -> CommitmentTransaction {
2326 CommitmentTransaction::new(
2327 self.commitment_number, &self.per_commitment_point, to_broadcaster_sats, to_countersignatory_sats, self.feerate_per_kw,
2328 nondust_htlcs, &self.channel_parameters.as_holder_broadcastable(), &self.secp_ctx
2329 )
2330 }
2331
2332 fn verify<'a>(
2333 &self, tx: &'a CommitmentTransaction,
2334 ) -> Result<TrustedCommitmentTransaction<'a>, ()> {
2335 tx.verify(&self.channel_parameters.as_holder_broadcastable(), &self.secp_ctx)
2336 }
2337 }
2338
2339 #[test]
2340 #[rustfmt::skip]
2341 fn test_anchors() {
2342 let mut builder = TestCommitmentTxBuilder::new();
2343
2344 let tx = builder.build(1000, 2000, Vec::new());
2346 assert_eq!(tx.built.transaction.output.len(), 2);
2347 assert_eq!(tx.built.transaction.output[1].script_pubkey, bitcoin::address::Address::p2wpkh(&CompressedPublicKey(builder.counterparty_pubkeys.payment_point), Network::Testnet).script_pubkey());
2348
2349 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
2351 let tx = builder.build(1000, 2000, Vec::new());
2352 assert_eq!(tx.built.transaction.output.len(), 4);
2353 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_to_countersigner_keyed_anchor_redeemscript(&builder.counterparty_pubkeys.payment_point).to_p2wsh());
2354 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_keyed_anchor_redeemscript(&builder.channel_parameters.holder_pubkeys.funding_pubkey).to_p2wsh());
2355 assert_eq!(tx.built.transaction.output[0].value.to_sat(), 330);
2356 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_keyed_anchor_redeemscript(&builder.counterparty_pubkeys.funding_pubkey).to_p2wsh());
2357 assert_eq!(tx.built.transaction.output[1].value.to_sat(), 330);
2358
2359 let tx = builder.build(3000, 0, Vec::new());
2361 assert_eq!(tx.built.transaction.output.len(), 2);
2362 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_keyed_anchor_redeemscript(&builder.channel_parameters.holder_pubkeys.funding_pubkey).to_p2wsh());
2363 assert_eq!(tx.built.transaction.output[0].value.to_sat(), 330);
2364
2365 let tx = builder.build(0, 3000, Vec::new());
2367 assert_eq!(tx.built.transaction.output.len(), 2);
2368 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_keyed_anchor_redeemscript(&builder.counterparty_pubkeys.funding_pubkey).to_p2wsh());
2369 assert_eq!(tx.built.transaction.output[0].value.to_sat(), 330);
2370
2371 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_fee_commitments();
2373 let tx = builder.build(1000, 2000, Vec::new());
2374 assert_eq!(tx.built.transaction.output.len(), 3);
2375 assert_eq!(tx.built.transaction.output[2].script_pubkey, bitcoin::address::Address::p2wpkh(&CompressedPublicKey(builder.counterparty_pubkeys.payment_point), Network::Testnet).script_pubkey());
2376 assert_eq!(tx.built.transaction.output[0].script_pubkey, shared_anchor_script_pubkey());
2377 assert_eq!(tx.built.transaction.output[0].value.to_sat(), 240); let tx = builder.build(3000, 0, Vec::new());
2381 assert_eq!(tx.built.transaction.output.len(), 2);
2382 assert_eq!(tx.built.transaction.output[0].script_pubkey, shared_anchor_script_pubkey());
2383 assert_eq!(tx.built.transaction.output[0].value.to_sat(), 240); let tx = builder.build(0, 3000, Vec::new());
2387 assert_eq!(tx.built.transaction.output.len(), 2);
2388 assert_eq!(tx.built.transaction.output[0].script_pubkey, shared_anchor_script_pubkey());
2389 assert_eq!(tx.built.transaction.output[0].value.to_sat(), 240); let received_htlc = HTLCOutputInCommitment {
2392 offered: false,
2393 amount_msat: 400000,
2394 cltv_expiry: 100,
2395 payment_hash: PaymentHash([42; 32]),
2396 transaction_output_index: None,
2397 };
2398
2399 let offered_htlc = HTLCOutputInCommitment {
2400 offered: true,
2401 amount_msat: 600000,
2402 cltv_expiry: 100,
2403 payment_hash: PaymentHash([43; 32]),
2404 transaction_output_index: None,
2405 };
2406
2407 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::only_static_remote_key();
2409 let tx = builder.build(3000, 0, vec![received_htlc.clone(), offered_htlc.clone()]);
2410 let keys = tx.trust().keys();
2411 assert_eq!(tx.built.transaction.output.len(), 3);
2412 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_p2wsh());
2413 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_p2wsh());
2414 assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_p2wsh().to_hex_string(),
2415 "0020e43a7c068553003fe68fcae424fb7b28ec5ce48cd8b6744b3945631389bad2fb");
2416 assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_p2wsh().to_hex_string(),
2417 "0020215d61bba56b19e9eadb6107f5a85d7f99c40f65992443f69229c290165bc00d");
2418
2419 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
2421 let tx = builder.build(3000, 0, vec![received_htlc.clone(), offered_htlc.clone()]);
2422 assert_eq!(tx.built.transaction.output.len(), 5);
2423 assert_eq!(tx.built.transaction.output[0].script_pubkey, get_keyed_anchor_redeemscript(&builder.channel_parameters.holder_pubkeys.funding_pubkey).to_p2wsh());
2424 assert_eq!(tx.built.transaction.output[0].value.to_sat(), 330);
2425 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_keyed_anchor_redeemscript(&builder.counterparty_pubkeys.funding_pubkey).to_p2wsh());
2426 assert_eq!(tx.built.transaction.output[1].value.to_sat(), 330);
2427 assert_eq!(tx.built.transaction.output[2].script_pubkey, get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_p2wsh());
2428 assert_eq!(tx.built.transaction.output[3].script_pubkey, get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_p2wsh());
2429 assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_p2wsh().to_hex_string(),
2430 "0020b70d0649c72b38756885c7a30908d912a7898dd5d79457a7280b8e9a20f3f2bc");
2431 assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_p2wsh().to_hex_string(),
2432 "002087a3faeb1950a469c0e2db4a79b093a41b9526e5a6fc6ef5cb949bde3be379c7");
2433
2434 builder.channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_fee_commitments();
2436 let tx = builder.build(3000, 0, vec![received_htlc.clone(), offered_htlc.clone()]);
2437 assert_eq!(tx.built.transaction.output.len(), 4);
2438 assert_eq!(tx.built.transaction.output[0].script_pubkey, shared_anchor_script_pubkey());
2439 assert_eq!(tx.built.transaction.output[0].value.to_sat(), 0);
2440 assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::anchors_zero_fee_commitments(), &keys).to_p2wsh());
2441 assert_eq!(tx.built.transaction.output[2].script_pubkey, get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::anchors_zero_fee_commitments(), &keys).to_p2wsh());
2442 assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::anchors_zero_fee_commitments(), &keys).to_p2wsh().to_hex_string(),
2443 "0020e43a7c068553003fe68fcae424fb7b28ec5ce48cd8b6744b3945631389bad2fb");
2444 assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::anchors_zero_fee_commitments(), &keys).to_p2wsh().to_hex_string(),
2445 "0020215d61bba56b19e9eadb6107f5a85d7f99c40f65992443f69229c290165bc00d");
2446 }
2447
2448 #[test]
2449 fn test_finding_revokeable_output_index() {
2450 let builder = TestCommitmentTxBuilder::new();
2451
2452 let tx = builder.build(1000, 2000, Vec::new());
2454 assert_eq!(tx.built.transaction.output.len(), 2);
2455 assert_eq!(tx.trust().revokeable_output_index(), Some(0));
2456
2457 let tx = CommitmentTransaction { to_broadcaster_delay: None, ..tx };
2459 assert_eq!(tx.built.transaction.output.len(), 2);
2460 assert_eq!(tx.trust().revokeable_output_index(), None);
2461
2462 let tx = builder.build(0, 2000, Vec::new());
2464 assert_eq!(tx.built.transaction.output.len(), 1);
2465 assert_eq!(tx.trust().revokeable_output_index(), None);
2466 }
2467
2468 #[test]
2469 #[rustfmt::skip]
2470 fn test_building_to_local_justice_tx() {
2471 let builder = TestCommitmentTxBuilder::new();
2472
2473 let tx = builder.build(0, 2000, Vec::new());
2475 assert_eq!(tx.built.transaction.output.len(), 1);
2476 assert!(tx.trust().build_to_local_justice_tx(253, ScriptBuf::new()).is_err());
2477
2478 let tx = builder.build(1000, 2000, Vec::new());
2480 assert_eq!(tx.built.transaction.output.len(), 2);
2481
2482 assert!(tx.trust().build_to_local_justice_tx(100_000, ScriptBuf::new()).is_err());
2484
2485 let secret_key = SecretKey::from_slice(
2487 &<Vec<u8>>::from_hex("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100")
2488 .unwrap()[..]).unwrap();
2489 let pubkey_hash = BitcoinPublicKey::new(
2490 PublicKey::from_secret_key(&Secp256k1::new(), &secret_key)).wpubkey_hash().unwrap();
2491 let destination_script = ScriptBuf::new_p2wpkh(&pubkey_hash);
2492
2493 let justice_tx = tx.trust().build_to_local_justice_tx(253, destination_script.clone()).unwrap();
2494 assert_eq!(justice_tx.input.len(), 1);
2495 assert_eq!(justice_tx.input[0].previous_output.txid, tx.built.transaction.compute_txid());
2496 assert_eq!(justice_tx.input[0].previous_output.vout, tx.trust().revokeable_output_index().unwrap() as u32);
2497 assert!(justice_tx.input[0].sequence.is_rbf());
2498
2499 assert_eq!(justice_tx.output.len(), 1);
2500 assert!(justice_tx.output[0].value.to_sat() < 1000);
2501 assert_eq!(justice_tx.output[0].script_pubkey, destination_script);
2502 }
2503
2504 #[test]
2505 fn test_per_commitment_storage() {
2506 let mut secrets: Vec<[u8; 32]> = Vec::new();
2508 let mut monitor;
2509
2510 #[rustfmt::skip]
2511 macro_rules! test_secrets {
2512 () => {
2513 let mut idx = 281474976710655;
2514 for secret in secrets.iter() {
2515 assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
2516 idx -= 1;
2517 }
2518 assert_eq!(monitor.get_min_seen_secret(), idx + 1);
2519 assert!(monitor.get_secret(idx).is_none());
2520 };
2521 }
2522
2523 {
2524 monitor = CounterpartyCommitmentSecrets::new();
2526 secrets.clear();
2527
2528 let hex = "7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc";
2529 secrets.push([0; 32]);
2530 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2531 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2532 test_secrets!();
2533
2534 let hex = "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964";
2535 secrets.push([0; 32]);
2536 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2537 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2538 test_secrets!();
2539
2540 let hex = "2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8";
2541 secrets.push([0; 32]);
2542 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2543 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2544 test_secrets!();
2545
2546 let hex = "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116";
2547 secrets.push([0; 32]);
2548 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2549 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2550 test_secrets!();
2551
2552 let hex = "c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd";
2553 secrets.push([0; 32]);
2554 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2555 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2556 test_secrets!();
2557
2558 let hex = "969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2";
2559 secrets.push([0; 32]);
2560 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2561 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2562 test_secrets!();
2563
2564 let hex = "a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32";
2565 secrets.push([0; 32]);
2566 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2567 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2568 test_secrets!();
2569
2570 let hex = "05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17";
2571 secrets.push([0; 32]);
2572 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2573 monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
2574 test_secrets!();
2575 }
2576
2577 {
2578 monitor = CounterpartyCommitmentSecrets::new();
2580 secrets.clear();
2581
2582 let hex = "02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148";
2583 secrets.push([0; 32]);
2584 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2585 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2586 test_secrets!();
2587
2588 let hex = "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964";
2589 secrets.push([0; 32]);
2590 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2591 assert!(monitor
2592 .provide_secret(281474976710654, secrets.last().unwrap().clone())
2593 .is_err());
2594 }
2595
2596 {
2597 monitor = CounterpartyCommitmentSecrets::new();
2599 secrets.clear();
2600
2601 let hex = "02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148";
2602 secrets.push([0; 32]);
2603 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2604 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2605 test_secrets!();
2606
2607 let hex = "dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3";
2608 secrets.push([0; 32]);
2609 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2610 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2611 test_secrets!();
2612
2613 let hex = "2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8";
2614 secrets.push([0; 32]);
2615 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2616 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2617 test_secrets!();
2618
2619 let hex = "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116";
2620 secrets.push([0; 32]);
2621 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2622 assert!(monitor
2623 .provide_secret(281474976710652, secrets.last().unwrap().clone())
2624 .is_err());
2625 }
2626
2627 {
2628 monitor = CounterpartyCommitmentSecrets::new();
2630 secrets.clear();
2631
2632 let hex = "7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc";
2633 secrets.push([0; 32]);
2634 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2635 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2636 test_secrets!();
2637
2638 let hex = "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964";
2639 secrets.push([0; 32]);
2640 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2641 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2642 test_secrets!();
2643
2644 let hex = "c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a";
2645 secrets.push([0; 32]);
2646 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2647 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2648 test_secrets!();
2649
2650 let hex = "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116";
2651 secrets.push([0; 32]);
2652 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2653 assert!(monitor
2654 .provide_secret(281474976710652, secrets.last().unwrap().clone())
2655 .is_err());
2656 }
2657
2658 {
2659 monitor = CounterpartyCommitmentSecrets::new();
2661 secrets.clear();
2662
2663 let hex = "02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148";
2664 secrets.push([0; 32]);
2665 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2666 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2667 test_secrets!();
2668
2669 let hex = "dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3";
2670 secrets.push([0; 32]);
2671 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2672 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2673 test_secrets!();
2674
2675 let hex = "c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a";
2676 secrets.push([0; 32]);
2677 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2678 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2679 test_secrets!();
2680
2681 let hex = "ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4";
2682 secrets.push([0; 32]);
2683 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2684 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2685 test_secrets!();
2686
2687 let hex = "c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd";
2688 secrets.push([0; 32]);
2689 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2690 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2691 test_secrets!();
2692
2693 let hex = "969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2";
2694 secrets.push([0; 32]);
2695 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2696 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2697 test_secrets!();
2698
2699 let hex = "a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32";
2700 secrets.push([0; 32]);
2701 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2702 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2703 test_secrets!();
2704
2705 let hex = "05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17";
2706 secrets.push([0; 32]);
2707 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2708 assert!(monitor
2709 .provide_secret(281474976710648, secrets.last().unwrap().clone())
2710 .is_err());
2711 }
2712
2713 {
2714 monitor = CounterpartyCommitmentSecrets::new();
2716 secrets.clear();
2717
2718 let hex = "7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc";
2719 secrets.push([0; 32]);
2720 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2721 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2722 test_secrets!();
2723
2724 let hex = "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964";
2725 secrets.push([0; 32]);
2726 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2727 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2728 test_secrets!();
2729
2730 let hex = "2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8";
2731 secrets.push([0; 32]);
2732 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2733 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2734 test_secrets!();
2735
2736 let hex = "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116";
2737 secrets.push([0; 32]);
2738 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2739 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2740 test_secrets!();
2741
2742 let hex = "631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6";
2743 secrets.push([0; 32]);
2744 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2745 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2746 test_secrets!();
2747
2748 let hex = "969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2";
2749 secrets.push([0; 32]);
2750 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2751 assert!(monitor
2752 .provide_secret(281474976710650, secrets.last().unwrap().clone())
2753 .is_err());
2754 }
2755
2756 {
2757 monitor = CounterpartyCommitmentSecrets::new();
2759 secrets.clear();
2760
2761 let hex = "7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc";
2762 secrets.push([0; 32]);
2763 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2764 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2765 test_secrets!();
2766
2767 let hex = "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964";
2768 secrets.push([0; 32]);
2769 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2770 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2771 test_secrets!();
2772
2773 let hex = "2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8";
2774 secrets.push([0; 32]);
2775 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2776 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2777 test_secrets!();
2778
2779 let hex = "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116";
2780 secrets.push([0; 32]);
2781 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2782 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2783 test_secrets!();
2784
2785 let hex = "631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6";
2786 secrets.push([0; 32]);
2787 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2788 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2789 test_secrets!();
2790
2791 let hex = "b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1";
2792 secrets.push([0; 32]);
2793 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2794 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2795 test_secrets!();
2796
2797 let hex = "a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32";
2798 secrets.push([0; 32]);
2799 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2800 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2801 test_secrets!();
2802
2803 let hex = "05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17";
2804 secrets.push([0; 32]);
2805 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2806 assert!(monitor
2807 .provide_secret(281474976710648, secrets.last().unwrap().clone())
2808 .is_err());
2809 }
2810
2811 {
2812 monitor = CounterpartyCommitmentSecrets::new();
2814 secrets.clear();
2815
2816 let hex = "7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc";
2817 secrets.push([0; 32]);
2818 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2819 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2820 test_secrets!();
2821
2822 let hex = "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964";
2823 secrets.push([0; 32]);
2824 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2825 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2826 test_secrets!();
2827
2828 let hex = "2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8";
2829 secrets.push([0; 32]);
2830 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2831 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2832 test_secrets!();
2833
2834 let hex = "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116";
2835 secrets.push([0; 32]);
2836 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2837 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2838 test_secrets!();
2839
2840 let hex = "c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd";
2841 secrets.push([0; 32]);
2842 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2843 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2844 test_secrets!();
2845
2846 let hex = "969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2";
2847 secrets.push([0; 32]);
2848 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2849 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2850 test_secrets!();
2851
2852 let hex = "e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3";
2853 secrets.push([0; 32]);
2854 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2855 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2856 test_secrets!();
2857
2858 let hex = "05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17";
2859 secrets.push([0; 32]);
2860 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2861 assert!(monitor
2862 .provide_secret(281474976710648, secrets.last().unwrap().clone())
2863 .is_err());
2864 }
2865
2866 {
2867 monitor = CounterpartyCommitmentSecrets::new();
2869 secrets.clear();
2870
2871 let hex = "7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc";
2872 secrets.push([0; 32]);
2873 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2874 monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2875 test_secrets!();
2876
2877 let hex = "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964";
2878 secrets.push([0; 32]);
2879 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2880 monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2881 test_secrets!();
2882
2883 let hex = "2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8";
2884 secrets.push([0; 32]);
2885 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2886 monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2887 test_secrets!();
2888
2889 let hex = "27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116";
2890 secrets.push([0; 32]);
2891 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2892 monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2893 test_secrets!();
2894
2895 let hex = "c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd";
2896 secrets.push([0; 32]);
2897 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2898 monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2899 test_secrets!();
2900
2901 let hex = "969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2";
2902 secrets.push([0; 32]);
2903 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2904 monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2905 test_secrets!();
2906
2907 let hex = "a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32";
2908 secrets.push([0; 32]);
2909 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2910 monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2911 test_secrets!();
2912
2913 let hex = "a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4";
2914 secrets.push([0; 32]);
2915 secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex(hex).unwrap());
2916 assert!(monitor
2917 .provide_secret(281474976710648, secrets.last().unwrap().clone())
2918 .is_err());
2919 }
2920 }
2921
2922 #[test]
2923 fn test_verify_sorted_htlcs() {
2924 #[rustfmt::skip]
2927 macro_rules! swap_htlcs {
2928 ($small_htlc: expr, $big_htlc: expr) => {
2929 let builder = TestCommitmentTxBuilder::new();
2930
2931 let nondust_htlcs = vec![$small_htlc.clone(), $big_htlc.clone()];
2932 let mut commit_tx = builder.build(0, 0, nondust_htlcs.clone());
2933 builder.verify(&commit_tx).unwrap();
2935 assert_eq!(commit_tx.nondust_htlcs, nondust_htlcs);
2937
2938 commit_tx.nondust_htlcs.swap(0, 1);
2940
2941 let mut transaction = commit_tx.built.transaction.clone();
2943 assert_eq!(transaction.output.len(), 2);
2945 transaction.output.swap(0, 1);
2946 let txid = transaction.compute_txid();
2947 let built = BuiltCommitmentTransaction {
2948 transaction,
2949 txid,
2950 };
2951 commit_tx.built = built;
2952
2953 assert!(builder.verify(&commit_tx).is_err());
2956 }
2957 }
2958
2959 let small_htlc = HTLCOutputInCommitment {
2961 offered: true,
2962 amount_msat: 10_000,
2963 cltv_expiry: 123,
2964 payment_hash: PaymentHash([0xbb; 32]),
2965 transaction_output_index: Some(0),
2966 };
2967
2968 let mut big_htlc = small_htlc.clone();
2970 big_htlc.amount_msat = 20_000;
2971 big_htlc.transaction_output_index = Some(1);
2972
2973 swap_htlcs!(small_htlc.clone(), big_htlc);
2974
2975 let mut big_htlc = small_htlc.clone();
2977 big_htlc.payment_hash = PaymentHash([0xaa; 32]);
2979 big_htlc.transaction_output_index = Some(1);
2980
2981 swap_htlcs!(small_htlc.clone(), big_htlc);
2982
2983 let mut big_htlc = small_htlc.clone();
2986 big_htlc.cltv_expiry = 124;
2987 big_htlc.transaction_output_index = Some(1);
2988
2989 swap_htlcs!(small_htlc, big_htlc);
2990 }
2991}