lightning/ln/
chan_utils.rs

1// This file is Copyright its original authors, visible in version control
2// history.
3//
4// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7// You may not use this file except in accordance with one or both of these
8// licenses.
9
10//! Various utilities for building scripts related to channels. These are
11//! largely of interest for those implementing the traits on [`crate::sign`] by hand.
12
13use 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
60/// Maximum number of in-flight HTLCs in each direction allowed by the lightning protocol.
61///
62/// 483 for non-zero-fee-commitment channels and 114 for zero-fee-commitment channels.
63///
64/// Actual maximums can be set equal to or below this value by each channel participant.
65pub fn max_htlcs(channel_type: &ChannelTypeFeatures) -> u16 {
66	if channel_type.supports_anchor_zero_fee_commitments() {
67		// TRUC restricts the size of our commitment transactions to 10K vB rather than 100K vB
68		114
69	} else {
70		483
71	}
72}
73/// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, non-anchor and p2a anchor variant.
74pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
75/// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, keyed anchor variant.
76pub const OFFERED_HTLC_SCRIPT_WEIGHT_KEYED_ANCHORS: usize = 136;
77
78/// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
79/// We define a range that encompasses both its non-anchors and anchors variants.
80pub(crate) const MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 136;
81/// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
82/// We define a range that encompasses both its non-anchors and anchors variants.
83/// This is the maximum post-anchor value.
84pub const MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 143;
85
86/// The upper bound weight of an anchor input.
87#[cfg(feature = "grind_signatures")]
88pub const ANCHOR_INPUT_WITNESS_WEIGHT: u64 = 114;
89/// The upper bound weight of an anchor input.
90#[cfg(not(feature = "grind_signatures"))]
91pub const ANCHOR_INPUT_WITNESS_WEIGHT: u64 = 115;
92
93/// The weight of an empty witness; used to spend a P2A output.
94pub const EMPTY_WITNESS_WEIGHT: u64 = 1;
95
96/// The maximum value of a P2A anchor.
97pub const P2A_MAX_VALUE: u64 = 240;
98
99/// The maximum weight of a TRUC transaction, see BIP431.
100pub const TRUC_MAX_WEIGHT: u64 = 10_000 * WITNESS_SCALE_FACTOR as u64;
101
102/// The maximum weight of a TRUC transaction with an unconfirmed TRUC ancestor, see BIP431.
103pub const TRUC_CHILD_MAX_WEIGHT: u64 = 1000 * WITNESS_SCALE_FACTOR as u64;
104
105/// The upper bound weight of an HTLC timeout input from a commitment transaction with keyed anchor outputs.
106pub const HTLC_TIMEOUT_INPUT_KEYED_ANCHOR_WITNESS_WEIGHT: u64 = 288;
107/// The upper bound weight of an HTLC timeout input from a commitment transaction with a p2a anchor output.
108/// Note the corresponding outputs no longer have the 1 CSV lock.
109pub const HTLC_TIMEOUT_INPUT_P2A_ANCHOR_WITNESS_WEIGHT: u64 = 285;
110/// The upper bound weight of an HTLC success input from a commitment transaction with keyed anchor outputs.
111pub const HTLC_SUCCESS_INPUT_KEYED_ANCHOR_WITNESS_WEIGHT: u64 = 327;
112/// The upper bound weight of an HTLC success input from a commitment transaction with a p2a anchor output.
113/// Note the corresponding outputs no longer have the 1 CSV lock.
114pub const HTLC_SUCCESS_INPUT_P2A_ANCHOR_WITNESS_WEIGHT: u64 = 324;
115
116/// The size of the 2-of-2 multisig script
117const MULTISIG_SCRIPT_SIZE: u64 = 1 + // OP_2
118	1 + // data len
119	crate::sign::COMPRESSED_PUBLIC_KEY_SIZE as u64 + // pubkey1
120	1 + // data len
121	crate::sign::COMPRESSED_PUBLIC_KEY_SIZE as u64 + // pubkey2
122	1 + // OP_2
123	1; // OP_CHECKMULTISIG
124
125/// The weight of a funding transaction input (2-of-2 P2WSH).
126///
127/// Unlike in the [spec], 72 WU is used for the max signature size since 73 WU signatures are
128/// non-standard.
129///
130/// Note: If you have the `grind_signatures` feature enabled, this will be at least 1 byte
131/// shorter.
132///
133/// [spec]: https://github.com/lightning/bolts/blob/master/03-transactions.md#expected-weight-of-the-commitment-transaction
134pub const FUNDING_TRANSACTION_WITNESS_WEIGHT: u64 = 1 + // number_of_witness_elements
135	1 + // nil_len
136	1 + // sig len
137	crate::sign::MAX_STANDARD_SIGNATURE_SIZE as u64 + // sig1
138	1 + // sig len
139	crate::sign::MAX_STANDARD_SIGNATURE_SIZE as u64 + // sig2
140	1 + // witness_script_length
141	MULTISIG_SCRIPT_SIZE;
142
143pub(crate) const BASE_TX_SIZE: u64 = 4 /* version */ + 1 /* input count */ + 1 /* output count */ + 4 /* locktime */;
144pub(crate) const SEGWIT_MARKER_FLAG_WEIGHT: u64 = 2;
145pub(crate) const EMPTY_SCRIPT_SIG_WEIGHT: u64 =
146	1 /* empty script_sig */ * WITNESS_SCALE_FACTOR as u64;
147pub(crate) const BASE_INPUT_SIZE: u64 = 32 /* txid */ + 4 /* vout */ + 4 /* sequence */;
148pub(crate) const BASE_INPUT_WEIGHT: u64 = BASE_INPUT_SIZE * WITNESS_SCALE_FACTOR as u64;
149pub(crate) const P2WSH_TXOUT_WEIGHT: u64 =
150	(8 /* value */ + 1 /* var_int */ + 34/* p2wsh spk */) * WITNESS_SCALE_FACTOR as u64;
151
152/// Gets the weight for an HTLC-Success transaction.
153#[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
161/// Gets the weight of a single input-output pair in externally funded HTLC-success transactions
162pub 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/// Gets the weight for an HTLC-Timeout transaction.
174#[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
182/// Gets the weight of a single input-output pair in externally funded HTLC-timeout transactions
183pub 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/// Describes the type of HTLC claim as determined by analyzing the witness.
195#[derive(PartialEq, Eq)]
196pub enum HTLCClaim {
197	/// Claims an offered output on a commitment transaction through the timeout path.
198	OfferedTimeout,
199	/// Claims an offered output on a commitment transaction through the success path.
200	OfferedPreimage,
201	/// Claims an accepted output on a commitment transaction through the timeout path.
202	AcceptedTimeout,
203	/// Claims an accepted output on a commitment transaction through the success path.
204	AcceptedPreimage,
205	/// Claims an offered/accepted output on a commitment transaction through the revocation path.
206	Revocation,
207}
208
209impl HTLCClaim {
210	/// Check if a given input witness attempts to claim a HTLC.
211	#[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				// <revocation sig> <revocationpubkey> <witness_script>
222				Some(Self::Revocation)
223			} else if witness.len() == 3 && second_to_last.len() == 32 {
224				// <remotehtlcsig> <payment_preimage> <witness_script>
225				Some(Self::OfferedPreimage)
226			} else if witness.len() == 5 && second_to_last.len() == 0 {
227				// 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
228				Some(Self::OfferedTimeout)
229			} else {
230				None
231			}
232		} else if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT_KEYED_ANCHORS {
233			// It's possible for the weight of `offered_htlc_script` and `accepted_htlc_script` to
234			// match so we check for both here.
235			if witness.len() == 3 && second_to_last.len() == 33 {
236				// <revocation sig> <revocationpubkey> <witness_script>
237				Some(Self::Revocation)
238			} else if witness.len() == 3 && second_to_last.len() == 32 {
239				// <remotehtlcsig> <payment_preimage> <witness_script>
240				Some(Self::OfferedPreimage)
241			} else if witness.len() == 5 && second_to_last.len() == 0 {
242				// 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
243				Some(Self::OfferedTimeout)
244			} else if witness.len() == 3 && second_to_last.len() == 0 {
245				// <remotehtlcsig> <> <witness_script>
246				Some(Self::AcceptedTimeout)
247			} else if witness.len() == 5 && second_to_last.len() == 32 {
248				// 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
249				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			// Handle remaining range of ACCEPTED_HTLC_SCRIPT_WEIGHT.
256			if witness.len() == 3 && second_to_last.len() == 33 {
257				// <revocation sig> <revocationpubkey> <witness_script>
258				Some(Self::Revocation)
259			} else if witness.len() == 3 && second_to_last.len() == 0 {
260				// <remotehtlcsig> <> <witness_script>
261				Some(Self::AcceptedTimeout)
262			} else if witness.len() == 5 && second_to_last.len() == 32 {
263				// 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
264				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/// Get the fee cost of a commitment tx with a given number of HTLC outputs.
287/// Note that num_htlcs should not include dust HTLCs.
288#[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
296/// Returns the fees for success and timeout second stage HTLC transactions.
297pub(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
321/// Returns a fee estimate for the commitment transaction that we would ideally like to set,
322/// depending on channel type.
323pub(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
338// Various functions for key derivation and transaction creation for use within channels. Primarily
339// used in Channel and ChannelMonitor.
340
341/// Build the commitment secret from the seed and the commitment number
342pub 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/// Build a closing transaction
355#[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 }); // Ordering doesnt matter if they used our pubkey...
384
385	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/// Implements the per-commitment secret storage scheme from
399/// [BOLT 3](https://github.com/lightning/bolts/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
400///
401/// Allows us to keep track of all of the revocation secrets of our counterparty in just 50*32 bytes
402/// or so.
403#[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	/// Creates a new empty `CounterpartyCommitmentSecrets` structure.
423	#[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	/// Returns the minimum index of all stored secrets. Note that indexes start
440	/// at 1 << 48 and get decremented by one for each new secret.
441	pub fn get_min_seen_secret(&self) -> u64 {
442		//TODO This can be optimized?
443		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	/// Inserts the `secret` at `idx`. Returns `Ok(())` if the secret
466	/// was generated in accordance with BOLT 3 and is consistent with previous secrets.
467	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	/// Returns the secret at `idx`.
483	/// Returns `None` if `idx` is < [`CounterpartyCommitmentSecrets::get_min_seen_secret`].
484	#[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
518/// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
519/// from the base secret and the per_commitment_point.
520pub 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/// Derives a per-commitment-transaction revocation key from its constituent parts.
533///
534/// Only the cheating participant owns a valid witness to propagate a revoked
535/// commitment transaction, thus per_commitment_secret always come from cheater
536/// and revocation_base_secret always come from punisher, which is the broadcaster
537/// of the transaction spending with this key knowledge.
538#[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/// The set of public keys which are used in the creation of one commitment transaction.
569/// These are derived from the channel base keys and per-commitment data.
570///
571/// A broadcaster key is provided from potential broadcaster of the computed transaction.
572/// A countersignatory key is coming from a protocol participant unable to broadcast the
573/// transaction.
574///
575/// These keys are assumed to be good, either because the code derived them from
576/// channel basepoints via the new function, or they were obtained via
577/// CommitmentTransaction.trust().keys() because we trusted the source of the
578/// pre-calculated keys.
579#[derive(PartialEq, Eq, Clone, Debug)]
580pub struct TxCreationKeys {
581	/// The broadcaster's per-commitment public key which was used to derive the other keys.
582	pub per_commitment_point: PublicKey,
583	/// The revocation key which is used to allow the broadcaster of the commitment
584	/// transaction to provide their counterparty the ability to punish them if they broadcast
585	/// an old state.
586	pub revocation_key: RevocationKey,
587	/// Broadcaster's HTLC Key
588	pub broadcaster_htlc_key: HtlcKey,
589	/// Countersignatory's HTLC Key
590	pub countersignatory_htlc_key: HtlcKey,
591	/// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
592	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/// One counterparty's public keys which do not change over the life of a channel.
604#[derive(Clone, Debug, Hash, PartialEq, Eq)]
605pub struct ChannelPublicKeys {
606	/// The public key which is used to sign all commitment transactions, as it appears in the
607	/// on-chain channel lock-in 2-of-2 multisig output.
608	pub funding_pubkey: PublicKey,
609	/// The base point which is used (with [`RevocationKey::from_basepoint`]) to derive per-commitment
610	/// revocation keys. This is combined with the per-commitment-secret generated by the
611	/// counterparty to create a secret which the counterparty can reveal to revoke previous
612	/// states.
613	pub revocation_basepoint: RevocationBasepoint,
614	/// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
615	/// spendable primary channel balance on the broadcaster's commitment transaction. This key is
616	/// static across every commitment transaction.
617	pub payment_point: PublicKey,
618	/// The base point which is used (with derive_public_key) to derive a per-commitment payment
619	/// public key which receives non-HTLC-encumbered funds which are only available for spending
620	/// after some delay (or can be claimed via the revocation path).
621	pub delayed_payment_basepoint: DelayedPaymentBasepoint,
622	/// The base point which is used (with derive_public_key) to derive a per-commitment public key
623	/// which is used to encumber HTLC-in-flight outputs.
624	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	/// Create per-state keys from channel base points and the per-commitment point.
637	/// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
638	#[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	/// Generate per-state keys from channel static keys.
650	/// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
651	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
666/// The maximum length of a script returned by get_revokeable_redeemscript.
667// Calculated as 6 bytes of opcodes, 1 byte push plus 3 bytes for contest_delay, and two public
668// keys of 33 bytes (+ 1 push). Generally, pushes are only 2 bytes (for values below 0x7fff, i.e.
669// around 7 months), however, a 7 month contest delay shouldn't result in being unable to reclaim
670// on-chain funds.
671pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 4 + 34 * 2;
672
673/// A script either spendable by the revocation
674/// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
675/// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
676#[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
692/// Returns the script for the countersigner's (i.e. non-broadcaster's) output on a commitment
693/// transaction based on the channel type.
694pub 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/// Information about an HTLC as it appears in a commitment transaction
705#[derive(Clone, Debug, PartialEq, Eq)]
706pub struct HTLCOutputInCommitment {
707	/// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
708	/// Note that this is not the same as whether it is ountbound *from us*. To determine that you
709	/// need to compare this value to whether the commitment transaction in question is that of
710	/// the counterparty or our own.
711	pub offered: bool,
712	/// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
713	/// this divided by 1000.
714	pub amount_msat: u64,
715	/// The CLTV lock-time at which this HTLC expires.
716	pub cltv_expiry: u32,
717	/// The hash of the preimage which unlocks this HTLC.
718	pub payment_hash: PaymentHash,
719	/// The position within the commitment transactions' outputs. This may be None if the value is
720	/// below the dust limit (in which case no output appears in the commitment transaction and the
721	/// value is spent to additional transaction fees).
722	pub transaction_output_index: Option<u32>,
723}
724
725impl HTLCOutputInCommitment {
726	/// Converts HTLC's value with millisatoshi precision into [bitcoin::Amount] with satoshi precision.
727	/// Typically this conversion is needed when transitioning from LN into base-layer Bitcoin,
728	/// e. g. in commitment transactions.
729	pub const fn to_bitcoin_amount(&self) -> Amount {
730		Amount::from_sat(self.amount_msat / 1000)
731	}
732
733	/// This method intentionally does not compare the transaction output indices, as it serves to
734	/// match HTLCs that do not have their output index populated with those that do.
735	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/// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
828/// does not need to have its previous_output_index filled.
829#[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
835/// Gets the redeemscript for a funding output from the two funding public keys.
836/// Note that the order of funding public keys does not matter.
837pub 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
858/// Builds an unsigned HTLC-Success or HTLC-Timeout transaction from the given channel and HTLC
859/// parameters. This is used by [`TrustedCommitmentTransaction::get_htlc_sigs`] to fetch the
860/// transaction which needs signing, and can be used to construct an HTLC transaction which is
861/// broadcastable given a counterparty HTLC signature.
862///
863/// Panics if htlc.transaction_output_index.is_none() (as such HTLCs do not appear in the
864/// commitment transaction).
865pub 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
931/// Returns the witness required to satisfy and spend a HTLC input.
932pub 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	// First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
946	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		// Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
956		witness.push(vec![]);
957	}
958	witness.push(redeem_script.to_bytes());
959	witness
960}
961
962/// Pre-anchors channel type features did not use to get serialized in the following six structs:
963/// — [`ChannelTransactionParameters`]
964/// — [`CommitmentTransaction`]
965/// — [`CounterpartyOfferedHTLCOutput`]
966/// — [`CounterpartyReceivedHTLCOutput`]
967/// — [`HolderHTLCOutput`]
968/// — [`HolderFundingOutput`]
969///
970/// To ensure a forwards-compatible serialization, we use odd TLV fields. However, if new features
971/// are used that could break security, where old signers should be prevented from handling the
972/// serialized data, an optional even-field TLV will be used as a stand-in to break compatibility.
973///
974/// This method determines whether or not that option needs to be set based on the chanenl type
975/// features, and returns it.
976///
977/// [`CounterpartyOfferedHTLCOutput`]: crate::chain::package::CounterpartyOfferedHTLCOutput
978/// [`CounterpartyReceivedHTLCOutput`]: crate::chain::package::CounterpartyReceivedHTLCOutput
979/// [`HolderHTLCOutput`]: crate::chain::package::HolderHTLCOutput
980/// [`HolderFundingOutput`]: crate::chain::package::HolderFundingOutput
981pub(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/// Gets the witnessScript for the to_remote output when anchors are enabled.
998#[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
1008/// Gets the script_pubkey for a shared anchor
1009pub fn shared_anchor_script_pubkey() -> ScriptBuf {
1010	Builder::new().push_int(1).push_slice(&[0x4e, 0x73]).into_script()
1011}
1012
1013/// Gets the witnessScript for a keyed anchor (non-zero-fee-commitments) output from the funding
1014/// public key.
1015///
1016/// The witness in the spending input must be:
1017/// <BIP 143 funding_signature>
1018/// After 16 blocks of confirmation, an alternative satisfying witness could be:
1019/// <>
1020/// (empty vector required to satisfy compliance with MINIMALIF-standard rule)
1021#[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
1033/// Returns the witness required to satisfy and spend a keyed anchor (non-zero-fee-commitments)
1034/// input.
1035pub 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/// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
1046/// The fields are organized by holder/counterparty.
1047///
1048/// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
1049/// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
1050#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1051pub struct ChannelTransactionParameters {
1052	/// Holder public keys
1053	pub holder_pubkeys: ChannelPublicKeys,
1054	/// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
1055	pub holder_selected_contest_delay: u16,
1056	/// Whether the holder is the initiator of this channel.
1057	/// This is an input to the commitment number obscure factor computation.
1058	pub is_outbound_from_holder: bool,
1059	/// The late-bound counterparty channel transaction parameters.
1060	/// These parameters are populated at the point in the protocol where the counterparty provides them.
1061	pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
1062	/// The late-bound funding outpoint
1063	pub funding_outpoint: Option<chain::transaction::OutPoint>,
1064	/// The parent funding txid for a channel that has been spliced.
1065	///
1066	/// If a channel was funded with transaction A, and later spliced with transaction B, this field
1067	/// tracks the txid of transaction A.
1068	///
1069	/// See [`compute_funding_key_tweak`] and [`ChannelSigner::new_funding_pubkey`] for more context
1070	/// on how this may be used.
1071	///
1072	/// [`compute_funding_key_tweak`]: crate::sign::compute_funding_key_tweak
1073	/// [`ChannelSigner::new_funding_pubkey`]: crate::sign::ChannelSigner::new_funding_pubkey
1074	pub splice_parent_funding_txid: Option<Txid>,
1075	/// This channel's type, as negotiated during channel open. For old objects where this field
1076	/// wasn't serialized, it will default to static_remote_key at deserialization.
1077	pub channel_type_features: ChannelTypeFeatures,
1078	/// The value locked in the channel, denominated in satoshis.
1079	pub channel_value_satoshis: u64,
1080}
1081
1082/// Late-bound per-channel counterparty data used to build transactions.
1083#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1084pub struct CounterpartyChannelTransactionParameters {
1085	/// Counter-party public keys
1086	pub pubkeys: ChannelPublicKeys,
1087	/// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
1088	pub selected_contest_delay: u16,
1089}
1090
1091impl ChannelTransactionParameters {
1092	/// Whether the late bound parameters are populated.
1093	pub fn is_populated(&self) -> bool {
1094		self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
1095	}
1096
1097	/// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
1098	/// given that the holder is the broadcaster.
1099	///
1100	/// self.is_populated() must be true before calling this function.
1101	#[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	/// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
1111	/// given that the counterparty is the broadcaster.
1112	///
1113	/// self.is_populated() must be true before calling this function.
1114	#[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	/// Returns the counterparty's pubkeys.
1137	pub fn counterparty_pubkeys(&self) -> Option<&ChannelPublicKeys> {
1138		self.counterparty_parameters.as_ref().map(|params| &params.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
1247/// Static channel fields used to build transactions given per-commitment fields, organized by
1248/// broadcaster/countersignatory.
1249///
1250/// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
1251/// as_holder_broadcastable and as_counterparty_broadcastable functions.
1252pub struct DirectedChannelTransactionParameters<'a> {
1253	/// The holder's channel static parameters
1254	inner: &'a ChannelTransactionParameters,
1255	/// Whether the holder is the broadcaster
1256	holder_is_broadcaster: bool,
1257}
1258
1259impl<'a> DirectedChannelTransactionParameters<'a> {
1260	/// Get the channel pubkeys for the broadcaster
1261	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	/// Get the channel pubkeys for the countersignatory
1270	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	/// Get the contest delay applicable to the transactions.
1279	/// Note that the contest delay was selected by the countersignatory.
1280	#[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	/// Whether the channel is outbound from the broadcaster.
1287	///
1288	/// The boolean representing the side that initiated the channel is
1289	/// an input to the commitment number obscure factor computation.
1290	#[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	/// The funding outpoint
1296	pub fn funding_outpoint(&self) -> OutPoint {
1297		self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
1298	}
1299
1300	/// The type of channel these parameters are for
1301	pub fn channel_type_features(&self) -> &'a ChannelTypeFeatures {
1302		&self.inner.channel_type_features
1303	}
1304
1305	/// The value locked in the channel, denominated in satoshis.
1306	pub fn channel_value_satoshis(&self) -> u64 {
1307		self.inner.channel_value_satoshis
1308	}
1309}
1310
1311/// Information needed to build and sign a holder's commitment transaction.
1312///
1313/// The transaction is only signed once we are ready to broadcast.
1314#[derive(Clone, Debug)]
1315pub struct HolderCommitmentTransaction {
1316	inner: CommitmentTransaction,
1317	/// Our counterparty's signature for the transaction
1318	pub counterparty_sig: Signature,
1319	/// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
1320	pub counterparty_htlc_sigs: Vec<Signature>,
1321	// Which order the signatures should go in when constructing the final commitment tx witness.
1322	// The user should be able to reconstruct this themselves, so we don't bother to expose it.
1323	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	// We dont care whether we are signed in equality comparison
1336	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	/// Create a new holder transaction with the given counterparty signatures.
1387	/// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
1388	#[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		// First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
1401		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/// A pre-built Bitcoin commitment transaction and its txid.
1418#[derive(Clone, Debug)]
1419pub struct BuiltCommitmentTransaction {
1420	/// The commitment transaction
1421	pub transaction: Transaction,
1422	/// The txid for the commitment transaction.
1423	///
1424	/// This is provided as a performance optimization, instead of calling transaction.txid()
1425	/// multiple times.
1426	pub txid: Txid,
1427}
1428
1429impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
1430	(0, transaction, required),
1431	(2, txid, required),
1432});
1433
1434impl BuiltCommitmentTransaction {
1435	/// Get the SIGHASH_ALL sighash value of the transaction.
1436	///
1437	/// This can be used to verify a signature.
1438	#[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	/// Signs the counterparty's commitment transaction.
1445	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	/// Signs the holder commitment transaction because we are about to broadcast it.
1454	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/// This class tracks the per-transaction information needed to build a closing transaction and will
1467/// actually build it and sign.
1468///
1469/// This class can be used inside a signer implementation to generate a signature given the relevant
1470/// secret key.
1471#[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	/// Construct an object of the class
1482	#[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	/// Trust our pre-built transaction.
1507	///
1508	/// Applies a wrapper which allows access to the transaction.
1509	///
1510	/// This should only be used if you fully trust the builder of this object. It should not
1511	/// be used by an external signer - instead use the verify function.
1512	pub fn trust(&self) -> TrustedClosingTransaction<'_> {
1513		TrustedClosingTransaction { inner: self }
1514	}
1515
1516	/// Verify our pre-built transaction.
1517	///
1518	/// Applies a wrapper which allows access to the transaction.
1519	///
1520	/// An external validating signer must call this method before signing
1521	/// or using the built transaction.
1522	#[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	/// The value to be sent to the holder, or zero if the output will be omitted
1536	pub fn to_holder_value_sat(&self) -> u64 {
1537		self.to_holder_value_sat.to_sat()
1538	}
1539
1540	/// The value to be sent to the counterparty, or zero if the output will be omitted
1541	pub fn to_counterparty_value_sat(&self) -> u64 {
1542		self.to_counterparty_value_sat.to_sat()
1543	}
1544
1545	/// The destination of the holder's output
1546	pub fn to_holder_script(&self) -> &Script {
1547		&self.to_holder_script
1548	}
1549
1550	/// The destination of the counterparty's output
1551	pub fn to_counterparty_script(&self) -> &Script {
1552		&self.to_counterparty_script
1553	}
1554}
1555
1556/// A wrapper on ClosingTransaction indicating that the built bitcoin
1557/// transaction is trusted.
1558///
1559/// See trust() and verify() functions on CommitmentTransaction.
1560///
1561/// This structure implements Deref.
1562pub 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	/// The pre-built Bitcoin commitment transaction
1575	pub fn built_transaction(&self) -> &'a Transaction {
1576		&self.inner.built
1577	}
1578
1579	/// Get the SIGHASH_ALL sighash value of the transaction.
1580	///
1581	/// This can be used to verify a signature.
1582	#[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	/// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1589	/// because we are about to broadcast a holder transaction.
1590	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/// This class tracks the per-transaction information needed to build a commitment transaction and will
1600/// actually build it and sign.  It is used for holder transactions that we sign only when needed
1601/// and for transactions we sign for the counterparty.
1602///
1603/// This class can be used inside a signer implementation to generate a signature given the relevant
1604/// secret key.
1605#[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>, // Added in 0.0.117
1611	feerate_per_kw: u32,
1612	// The set of non-dust HTLCs included in the commitment. They must be sorted in increasing
1613	// output index order.
1614	nondust_htlcs: Vec<HTLCOutputInCommitment>,
1615	// Note that on upgrades, some features of existing outputs may be missed.
1616	channel_type_features: ChannelTypeFeatures,
1617	// A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
1618	keys: TxCreationKeys,
1619	// For access to the pre-built transaction, see doc for trust()
1620	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	/// Constructs a new `CommitmentTransaction` from the list of HTLCs and the direct balances.
1698	///
1699	/// All HTLCs MUST be above the dust limit for the channel.
1700	/// The broadcaster and countersignatory amounts MUST be either 0 or above dust. If the amount
1701	/// is 0, the corresponding output will be omitted from the transaction.
1702	#[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		// Build and sort the outputs of the transaction.
1709		// Also sort the HTLC output data in `nondust_htlcs` in the same order, and populate the
1710		// transaction output indices therein.
1711		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	/// Use non-zero fee anchors
1733	///
1734	/// This is not exported to bindings users due to move, and also not likely to be useful for binding users
1735	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	// A helper function that checks if the HTLC to the left of the HTLC at i is greater than itself,
1741	// first by value, then by script pubkey, then by cltv expiry.
1742	//
1743	// It does so by reading both a vector of `TxOut` and a vector of `HTLCOutputInCommitment`.
1744	//
1745	// We use this function to both sort HTLCs, and to check that a set of HTLCs is sorted.
1746	//
1747	// `txouts` and `nondust_htlcs` MUST be of equal length, and of length >= 2.
1748	// For all `i < len`, the `TxOut` at `txouts[i]` MUST correspond to the HTLC at `nondust_htlcs[i]`.
1749	#[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			// Note that due to hash collisions, we have to have a fallback comparison
1755			// here for fuzzing mode (otherwise at least chanmon_fail_consistency
1756			// may fail)!
1757			.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		// First rebuild the htlc outputs, note that `outputs` is now the same length as `self.nondust_htlcs`
1766		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		// Check that the HTLC outputs are sorted by value, script pubkey, and cltv expiry.
1771		// Note that this only iterates if the length of `outputs` and `self.nondust_htlcs` is >= 2.
1772		if (1..outputs.len()).into_iter().any(|i| Self::is_left_greater(i, &outputs, &self.nondust_htlcs)) {
1773			return Err(())
1774		}
1775
1776		// Then insert the max-4 non-htlc outputs, ordered by value, then by script pubkey
1777		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				// For non-HTLC outputs, if they're copying our SPK we don't really care if we
1780				// close the channel due to mismatches - they're doing something dumb
1781				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		// First build and sort the HTLC outputs.
1829		// Also sort the HTLC output data in `nondust_htlcs` in the same order.
1830		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		// Initialize the transaction output indices; we will update them below when we
1835		// add the non-htlc transaction outputs.
1836		nondust_htlcs
1837			.iter_mut()
1838			.enumerate()
1839			.for_each(|(i, htlc)| htlc.transaction_output_index = Some(i as u32));
1840
1841		// Then insert the max-4 non-htlc outputs, ordered by value, then by script pubkey
1842		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				// For non-HTLC outputs, if they're copying our SPK we don't really care if we
1845				// close the channel due to mismatches - they're doing something dumb
1846				Ok(i) => i,
1847				Err(i) => i,
1848			};
1849			outputs.insert(idx, non_htlc_output);
1850
1851			// Increment the transaction output indices of all the HTLCs that come after the output we
1852			// just inserted.
1853			nondust_htlcs
1854				.iter_mut()
1855				.rev()
1856				.map_while(|htlc| {
1857					// This unwrap is safe; we've initialized all the transaction output indices above
1858					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				// These subtractions panic on underflow, but this should never happen
1939				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		// Allocate memory for the 4 possible non-htlc outputs
1950		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		// Note that `txouts` has the same length as `nondust_htlcs` here
1971		let mut txouts = Self::build_htlc_outputs(keys, nondust_htlcs, channel_type);
1972
1973		// Sort the HTLC outputs by value, then by script pubkey, then by cltv expiration height.
1974		//
1975		// Also sort the HTLC output data in `nondust_htlcs` in the same order.
1976		//
1977		// This is insertion sort. In the worst case this is O(n^2) over 2 * 483 HTLCs in the
1978		// channel. We expect people to transition soon to zero-fee-commitment channels,
1979		// where n will be 2 * 114.
1980		//
1981		// These are small numbers, and channels today rarely reach this protocol-max, if ever,
1982		// so we accept the performance tradeoff.
1983
1984		// Note that if we enter this loop, the length of `txouts` and `nondust_htlcs` is at least 2
1985		for i in 1..txouts.len() {
1986			let mut j = i;
1987			// While there is a value to the left of j,
1988			// and that value is greater than the value at j,
1989			// swap the two values.
1990			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	/// The backwards-counting commitment number
2027	pub fn commitment_number(&self) -> u64 {
2028		self.commitment_number
2029	}
2030
2031	/// The per commitment point used by the broadcaster.
2032	pub fn per_commitment_point(&self) -> PublicKey {
2033		self.keys.per_commitment_point
2034	}
2035
2036	/// The value to be sent to the broadcaster
2037	pub fn to_broadcaster_value_sat(&self) -> u64 {
2038		self.to_broadcaster_value_sat.to_sat()
2039	}
2040
2041	/// The value to be sent to the counterparty
2042	pub fn to_countersignatory_value_sat(&self) -> u64 {
2043		self.to_countersignatory_value_sat.to_sat()
2044	}
2045
2046	/// The feerate paid per 1000-weight-unit we negotiated with our
2047	/// peer for this commitment transaction. Note that the actual
2048	/// feerate of the commitment transaction may be higher than the
2049	/// negotiated feerate.
2050	pub fn negotiated_feerate_per_kw(&self) -> u32 {
2051		self.feerate_per_kw
2052	}
2053
2054	/// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
2055	/// which were included in this commitment transaction in output order.
2056	/// The transaction index is always populated.
2057	///
2058	/// This is not exported to bindings users as we cannot currently convert Vec references to/from C, though we should
2059	/// expose a less effecient version which creates a Vec of references in the future.
2060	pub fn nondust_htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
2061		&self.nondust_htlcs
2062	}
2063
2064	/// Trust our pre-built transaction and derived transaction creation public keys.
2065	///
2066	/// Applies a wrapper which allows access to these fields.
2067	///
2068	/// This should only be used if you fully trust the builder of this object.  It should not
2069	/// be used by an external signer - instead use the verify function.
2070	pub fn trust(&self) -> TrustedCommitmentTransaction<'_> {
2071		TrustedCommitmentTransaction { inner: self }
2072	}
2073
2074	/// Verify our pre-built transaction and derived transaction creation public keys.
2075	///
2076	/// Applies a wrapper which allows access to these fields.
2077	///
2078	/// An external validating signer must call this method before signing
2079	/// or using the built transaction.
2080	#[rustfmt::skip]
2081	pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction<'_>, ()> {
2082		// This is the only field of the key cache that we trust
2083		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
2096/// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
2097/// transaction and the transaction creation keys) are trusted.
2098///
2099/// See trust() and verify() functions on CommitmentTransaction.
2100///
2101/// This structure implements Deref.
2102pub 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	/// The transaction ID of the built Bitcoin transaction
2115	pub fn txid(&self) -> Txid {
2116		self.inner.built.txid
2117	}
2118
2119	/// The pre-built Bitcoin commitment transaction
2120	pub fn built_transaction(&self) -> &'a BuiltCommitmentTransaction {
2121		&self.inner.built
2122	}
2123
2124	/// The pre-calculated transaction creation public keys.
2125	pub fn keys(&self) -> &'a TxCreationKeys {
2126		&self.inner.keys
2127	}
2128
2129	/// Should anchors be used.
2130	pub fn channel_type_features(&self) -> &'a ChannelTypeFeatures {
2131		&self.inner.channel_type_features
2132	}
2133
2134	/// Get a signature for each HTLC which was included in the commitment transaction (ie for
2135	/// which HTLCOutputInCommitment::transaction_output_index.is_some()).
2136	///
2137	/// The returned Vec has one entry for each HTLC, and in the same order.
2138	///
2139	/// This function is only valid in the holder commitment context, it always uses EcdsaSighashType::All.
2140	#[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	/// Returns the index of the revokeable output, i.e. the `to_local` output sending funds to
2164	/// the broadcaster, in the built transaction, if any exists.
2165	///
2166	/// There are two cases where this may return `None`:
2167	/// - The balance of the revokeable output is below the dust limit (only found on commitments
2168	/// early in the channel's lifetime, i.e. before the channel reserve is met).
2169	/// - This commitment was created before LDK 0.0.117. In this case, the
2170	/// commitment transaction previously didn't contain enough information to locate the
2171	/// revokeable output.
2172	#[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	/// Helper method to build an unsigned justice transaction spending the revokeable
2187	/// `to_local` output to a destination script. Fee estimation accounts for the expected
2188	/// revocation witness data that will be added when signed.
2189	///
2190	/// This method will error if the given fee rate results in a fee greater than the value
2191	/// of the output being spent, or if there exists no revokeable `to_local` output on this
2192	/// commitment transaction. See [`Self::revokeable_output_index`] for more details.
2193	///
2194	/// The built transaction will allow fee bumping with RBF, and this method takes
2195	/// `feerate_per_kw` as an input such that multiple copies of a justice transaction at different
2196	/// fee rates may be built.
2197	#[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
2228/// Commitment transaction numbers which appear in the transactions themselves are XOR'd with a
2229/// shared secret first. This prevents on-chain observers from discovering how many commitment
2230/// transactions occurred in a channel before it was closed.
2231///
2232/// This function gets the shared secret from relevant channel public keys and can be used to
2233/// "decrypt" the commitment transaction number given a commitment transaction on-chain.
2234pub 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		// Generate broadcaster and counterparty outputs
2345		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		// Generate broadcaster and counterparty outputs as well as two anchors
2350		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		// Generate broadcaster output and anchor
2360		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		// Generate counterparty output and anchor
2366		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		// Generate broadcaster and counterparty outputs as well as a single anchor
2372		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); // remember total channel value is 4000sat
2378
2379		// Generate broadcaster output and anchor
2380		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); // remember total channel value is 4000sat
2384
2385		// Generate counterparty output and anchor
2386		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); // remember total channel value is 4000sat
2390
2391		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		// Generate broadcaster output and received and offered HTLC outputs, w/o anchors
2408		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		// Generate broadcaster output and received and offered HTLC outputs, with keyed anchors
2420		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		// Generate broadcaster output and received and offered HTLC outputs, with P2A anchors
2435		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		// Revokeable output present
2453		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		// Revokeable output present (but to_broadcaster_delay missing)
2458		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		// Revokeable output not present (our balance is dust)
2463		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		// Revokeable output not present (our balance is dust)
2474		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		// Revokeable output present
2479		let tx = builder.build(1000, 2000, Vec::new());
2480		assert_eq!(tx.built.transaction.output.len(), 2);
2481
2482		// Too high feerate
2483		assert!(tx.trust().build_to_local_justice_tx(100_000, ScriptBuf::new()).is_err());
2484
2485		// Generate a random public key for destination script
2486		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		// Test vectors from BOLT 3:
2507		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			// insert_secret correct sequence
2525			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			// insert_secret #1 incorrect
2579			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			// insert_secret #2 incorrect (#1 derived from incorrect)
2598			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			// insert_secret #3 incorrect
2629			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			// insert_secret #4 incorrect (1,2,3 derived from incorrect)
2660			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			// insert_secret #5 incorrect
2715			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			// insert_secret #6 incorrect (5 derived from incorrect)
2758			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			// insert_secret #7 incorrect
2813			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			// insert_secret #8 incorrect
2868			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		// Assert that `CommitmentTransaction::verify` checks that the HTLCs are sorted
2925
2926		#[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				// Everything should be OK up to this point
2934				builder.verify(&commit_tx).unwrap();
2935				// Sanity check that `small_htlc` was actually smaller than `big_htlc`
2936				assert_eq!(commit_tx.nondust_htlcs, nondust_htlcs);
2937
2938				// Swap the HTLCs in the `nondust_htlcs` vector
2939				commit_tx.nondust_htlcs.swap(0, 1);
2940
2941				// Also swap the HTLCs in the outputs of the cached transaction
2942				let mut transaction = commit_tx.built.transaction.clone();
2943				// The transaction should just have 2 HTLC outputs
2944				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				// Yes the HTLCs in `nondust_htlcs` are in the same order as in the cached transaction,
2954				// but they are not sorted!
2955				assert!(builder.verify(&commit_tx).is_err());
2956			}
2957		}
2958
2959		// script_pubkey: Script(OP_0 OP_PUSHBYTES_32 1b202f6bdf42cd8ba08e263868b5bd0cf5a7f95c227c27e1935984a8f6130fa3)
2960		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		// Check amount sorting
2969		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		// Check script pubkey sorting
2976		let mut big_htlc = small_htlc.clone();
2977		// script_pubkey: Script(OP_0 OP_PUSHBYTES_32 b929ab63800ff4e350d2e2ad320b44d643829f135f60ad6a4f01e39fff228810)
2978		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		// Check CLTV sorting.
2984		// We want identical `TxOut`'s, so make sure the HTLCs are offered HTLCs with same amounts and payment hashes.
2985		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}