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::{PubkeyHash, WPubkeyHash};
14use bitcoin::amount::Amount;
15use bitcoin::script::{Script, ScriptBuf, Builder};
16use bitcoin::opcodes;
17use bitcoin::transaction::{TxIn,TxOut,OutPoint,Transaction};
18use bitcoin::sighash;
19use bitcoin::sighash::EcdsaSighashType;
20use bitcoin::transaction::Version;
21
22use bitcoin::hashes::{Hash, HashEngine};
23use bitcoin::hashes::hash160::Hash as Hash160;
24use bitcoin::hashes::sha256::Hash as Sha256;
25use bitcoin::hashes::ripemd160::Hash as Ripemd160;
26use bitcoin::hash_types::Txid;
27
28use crate::chain::chaininterface::fee_for_weight;
29use crate::chain::package::WEIGHT_REVOKED_OUTPUT;
30use crate::sign::EntropySource;
31use crate::types::payment::{PaymentHash, PaymentPreimage};
32use crate::ln::msgs::DecodeError;
33use crate::util::ser::{Readable, RequiredWrapper, Writeable, Writer};
34use crate::util::transaction_utils;
35
36use bitcoin::locktime::absolute::LockTime;
37use bitcoin::ecdsa::Signature as BitcoinSignature;
38use bitcoin::secp256k1::{SecretKey, PublicKey, Scalar};
39use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature, Message};
40use bitcoin::{secp256k1, Sequence, Witness};
41
42use crate::io;
43use core::cmp;
44use crate::util::transaction_utils::sort_outputs;
45use crate::ln::channel::{INITIAL_COMMITMENT_NUMBER, ANCHOR_OUTPUT_VALUE_SATOSHI};
46use core::ops::Deref;
47use crate::chain;
48use crate::types::features::ChannelTypeFeatures;
49use crate::crypto::utils::{sign, sign_with_aux_rand};
50use super::channel_keys::{DelayedPaymentBasepoint, DelayedPaymentKey, HtlcKey, HtlcBasepoint, RevocationKey, RevocationBasepoint};
51
52#[allow(unused_imports)]
53use crate::prelude::*;
54
55/// Maximum number of one-way in-flight HTLC (protocol-level value).
56pub const MAX_HTLCS: u16 = 483;
57/// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, non-anchor variant.
58pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
59/// The weight of a BIP141 witnessScript for a BOLT3's "offered HTLC output" on a commitment transaction, anchor variant.
60pub const OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS: usize = 136;
61
62/// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
63/// We define a range that encompasses both its non-anchors and anchors variants.
64pub(crate) const MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 136;
65/// The weight of a BIP141 witnessScript for a BOLT3's "received HTLC output" can vary in function of its CLTV argument value.
66/// We define a range that encompasses both its non-anchors and anchors variants.
67/// This is the maximum post-anchor value.
68pub const MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 143;
69
70/// The upper bound weight of an anchor input.
71#[cfg(feature = "grind_signatures")]
72pub const ANCHOR_INPUT_WITNESS_WEIGHT: u64 = 114;
73/// The upper bound weight of an anchor input.
74#[cfg(not(feature = "grind_signatures"))]
75pub const ANCHOR_INPUT_WITNESS_WEIGHT: u64 = 115;
76
77/// The upper bound weight of an HTLC timeout input from a commitment transaction with anchor
78/// outputs.
79pub const HTLC_TIMEOUT_INPUT_ANCHOR_WITNESS_WEIGHT: u64 = 288;
80/// The upper bound weight of an HTLC success input from a commitment transaction with anchor
81/// outputs.
82pub const HTLC_SUCCESS_INPUT_ANCHOR_WITNESS_WEIGHT: u64 = 327;
83
84/// Gets the weight for an HTLC-Success transaction.
85#[inline]
86pub fn htlc_success_tx_weight(channel_type_features: &ChannelTypeFeatures) -> u64 {
87	const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
88	const HTLC_SUCCESS_ANCHOR_TX_WEIGHT: u64 = 706;
89	if channel_type_features.supports_anchors_zero_fee_htlc_tx() { HTLC_SUCCESS_ANCHOR_TX_WEIGHT } else { HTLC_SUCCESS_TX_WEIGHT }
90}
91
92/// Gets the weight for an HTLC-Timeout transaction.
93#[inline]
94pub fn htlc_timeout_tx_weight(channel_type_features: &ChannelTypeFeatures) -> u64 {
95	const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
96	const HTLC_TIMEOUT_ANCHOR_TX_WEIGHT: u64 = 666;
97	if channel_type_features.supports_anchors_zero_fee_htlc_tx() { HTLC_TIMEOUT_ANCHOR_TX_WEIGHT } else { HTLC_TIMEOUT_TX_WEIGHT }
98}
99
100/// Describes the type of HTLC claim as determined by analyzing the witness.
101#[derive(PartialEq, Eq)]
102pub enum HTLCClaim {
103	/// Claims an offered output on a commitment transaction through the timeout path.
104	OfferedTimeout,
105	/// Claims an offered output on a commitment transaction through the success path.
106	OfferedPreimage,
107	/// Claims an accepted output on a commitment transaction through the timeout path.
108	AcceptedTimeout,
109	/// Claims an accepted output on a commitment transaction through the success path.
110	AcceptedPreimage,
111	/// Claims an offered/accepted output on a commitment transaction through the revocation path.
112	Revocation,
113}
114
115impl HTLCClaim {
116	/// Check if a given input witness attempts to claim a HTLC.
117	pub fn from_witness(witness: &Witness) -> Option<Self> {
118		debug_assert_eq!(OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS, MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT);
119		if witness.len() < 2 {
120			return None;
121		}
122		let witness_script = witness.last().unwrap();
123		let second_to_last = witness.second_to_last().unwrap();
124		if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT {
125			if witness.len() == 3 && second_to_last.len() == 33 {
126				// <revocation sig> <revocationpubkey> <witness_script>
127				Some(Self::Revocation)
128			} else if witness.len() == 3 && second_to_last.len() == 32 {
129				// <remotehtlcsig> <payment_preimage> <witness_script>
130				Some(Self::OfferedPreimage)
131			} else if witness.len() == 5 && second_to_last.len() == 0 {
132				// 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
133				Some(Self::OfferedTimeout)
134			} else {
135				None
136			}
137		} else if witness_script.len() == OFFERED_HTLC_SCRIPT_WEIGHT_ANCHORS {
138			// It's possible for the weight of `offered_htlc_script` and `accepted_htlc_script` to
139			// match so we check for both here.
140			if witness.len() == 3 && second_to_last.len() == 33 {
141				// <revocation sig> <revocationpubkey> <witness_script>
142				Some(Self::Revocation)
143			} else if witness.len() == 3 && second_to_last.len() == 32 {
144				// <remotehtlcsig> <payment_preimage> <witness_script>
145				Some(Self::OfferedPreimage)
146			} else if witness.len() == 5 && second_to_last.len() == 0 {
147				// 0 <remotehtlcsig> <localhtlcsig> <> <witness_script>
148				Some(Self::OfferedTimeout)
149			} else if witness.len() == 3 && second_to_last.len() == 0 {
150				// <remotehtlcsig> <> <witness_script>
151				Some(Self::AcceptedTimeout)
152			} else if witness.len() == 5 && second_to_last.len() == 32 {
153				// 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
154				Some(Self::AcceptedPreimage)
155			} else {
156				None
157			}
158		} else if witness_script.len() > MIN_ACCEPTED_HTLC_SCRIPT_WEIGHT &&
159			witness_script.len() <= MAX_ACCEPTED_HTLC_SCRIPT_WEIGHT {
160			// Handle remaining range of ACCEPTED_HTLC_SCRIPT_WEIGHT.
161			if witness.len() == 3 && second_to_last.len() == 33 {
162				// <revocation sig> <revocationpubkey> <witness_script>
163				Some(Self::Revocation)
164			} else if witness.len() == 3 && second_to_last.len() == 0 {
165				// <remotehtlcsig> <> <witness_script>
166				Some(Self::AcceptedTimeout)
167			} else if witness.len() == 5 && second_to_last.len() == 32 {
168				// 0 <remotehtlcsig> <localhtlcsig> <payment_preimage> <witness_script>
169				Some(Self::AcceptedPreimage)
170			} else {
171				None
172			}
173		} else {
174			None
175		}
176	}
177}
178
179#[cfg(not(test))]
180const COMMITMENT_TX_WEIGHT_PER_HTLC: u64 = 172;
181#[cfg(test)]
182pub const COMMITMENT_TX_WEIGHT_PER_HTLC: u64 = 172;
183
184pub(crate) fn commitment_tx_base_weight(channel_type_features: &ChannelTypeFeatures) -> u64 {
185	const COMMITMENT_TX_BASE_WEIGHT: u64 = 724;
186	const COMMITMENT_TX_BASE_ANCHOR_WEIGHT: u64 = 1124;
187	if channel_type_features.supports_anchors_zero_fee_htlc_tx() { COMMITMENT_TX_BASE_ANCHOR_WEIGHT } else { COMMITMENT_TX_BASE_WEIGHT }
188}
189
190/// Get the fee cost of a commitment tx with a given number of HTLC outputs.
191/// Note that num_htlcs should not include dust HTLCs.
192pub(crate) fn commit_tx_fee_sat(feerate_per_kw: u32, num_htlcs: usize, channel_type_features: &ChannelTypeFeatures) -> u64 {
193	feerate_per_kw as u64 *
194		(commitment_tx_base_weight(channel_type_features) +
195			num_htlcs as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)
196		/ 1000
197}
198
199pub(crate) fn per_outbound_htlc_counterparty_commit_tx_fee_msat(feerate_per_kw: u32, channel_type_features: &ChannelTypeFeatures) -> u64 {
200	// Note that we need to divide before multiplying to round properly,
201	// since the lowest denomination of bitcoin on-chain is the satoshi.
202	let commitment_tx_fee = COMMITMENT_TX_WEIGHT_PER_HTLC * feerate_per_kw as u64 / 1000 * 1000;
203	if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
204		commitment_tx_fee + htlc_success_tx_weight(channel_type_features) * feerate_per_kw as u64 / 1000
205	} else {
206		commitment_tx_fee
207	}
208}
209
210// Various functions for key derivation and transaction creation for use within channels. Primarily
211// used in Channel and ChannelMonitor.
212
213/// Build the commitment secret from the seed and the commitment number
214pub fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
215	let mut res: [u8; 32] = commitment_seed.clone();
216	for i in 0..48 {
217		let bitpos = 47 - i;
218		if idx & (1 << bitpos) == (1 << bitpos) {
219			res[bitpos / 8] ^= 1 << (bitpos & 7);
220			res = Sha256::hash(&res).to_byte_array();
221		}
222	}
223	res
224}
225
226/// Build a closing transaction
227pub 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 {
228	let txins = {
229		let ins: Vec<TxIn> = vec![TxIn {
230			previous_output: funding_outpoint,
231			script_sig: ScriptBuf::new(),
232			sequence: Sequence::MAX,
233			witness: Witness::new(),
234		}];
235		ins
236	};
237
238	let mut txouts: Vec<(TxOut, ())> = Vec::new();
239
240	if to_counterparty_value_sat > Amount::ZERO {
241		txouts.push((TxOut {
242			script_pubkey: to_counterparty_script,
243			value: to_counterparty_value_sat
244		}, ()));
245	}
246
247	if to_holder_value_sat > Amount::ZERO {
248		txouts.push((TxOut {
249			script_pubkey: to_holder_script,
250			value: to_holder_value_sat
251		}, ()));
252	}
253
254	transaction_utils::sort_outputs(&mut txouts, |_, _| { cmp::Ordering::Equal }); // Ordering doesnt matter if they used our pubkey...
255
256	let mut outputs: Vec<TxOut> = Vec::new();
257	for out in txouts.drain(..) {
258		outputs.push(out.0);
259	}
260
261	Transaction {
262		version: Version::TWO,
263		lock_time: LockTime::ZERO,
264		input: txins,
265		output: outputs,
266	}
267}
268
269/// Implements the per-commitment secret storage scheme from
270/// [BOLT 3](https://github.com/lightning/bolts/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
271///
272/// Allows us to keep track of all of the revocation secrets of our counterparty in just 50*32 bytes
273/// or so.
274#[derive(Clone)]
275pub struct CounterpartyCommitmentSecrets {
276	old_secrets: [([u8; 32], u64); 49],
277}
278
279impl Eq for CounterpartyCommitmentSecrets {}
280impl PartialEq for CounterpartyCommitmentSecrets {
281	fn eq(&self, other: &Self) -> bool {
282		for (&(ref secret, ref idx), &(ref o_secret, ref o_idx)) in self.old_secrets.iter().zip(other.old_secrets.iter()) {
283			if secret != o_secret || idx != o_idx {
284				return false
285			}
286		}
287		true
288	}
289}
290
291impl CounterpartyCommitmentSecrets {
292	/// Creates a new empty `CounterpartyCommitmentSecrets` structure.
293	pub fn new() -> Self {
294		Self { old_secrets: [([0; 32], 1 << 48); 49], }
295	}
296
297	#[inline]
298	fn place_secret(idx: u64) -> u8 {
299		for i in 0..48 {
300			if idx & (1 << i) == (1 << i) {
301				return i
302			}
303		}
304		48
305	}
306
307	/// Returns the minimum index of all stored secrets. Note that indexes start
308	/// at 1 << 48 and get decremented by one for each new secret.
309	pub fn get_min_seen_secret(&self) -> u64 {
310		//TODO This can be optimized?
311		let mut min = 1 << 48;
312		for &(_, idx) in self.old_secrets.iter() {
313			if idx < min {
314				min = idx;
315			}
316		}
317		min
318	}
319
320	#[inline]
321	fn derive_secret(secret: [u8; 32], bits: u8, idx: u64) -> [u8; 32] {
322		let mut res: [u8; 32] = secret;
323		for i in 0..bits {
324			let bitpos = bits - 1 - i;
325			if idx & (1 << bitpos) == (1 << bitpos) {
326				res[(bitpos / 8) as usize] ^= 1 << (bitpos & 7);
327				res = Sha256::hash(&res).to_byte_array();
328			}
329		}
330		res
331	}
332
333	/// Inserts the `secret` at `idx`. Returns `Ok(())` if the secret
334	/// was generated in accordance with BOLT 3 and is consistent with previous secrets.
335	pub fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), ()> {
336		let pos = Self::place_secret(idx);
337		for i in 0..pos {
338			let (old_secret, old_idx) = self.old_secrets[i as usize];
339			if Self::derive_secret(secret, pos, old_idx) != old_secret {
340				return Err(());
341			}
342		}
343		if self.get_min_seen_secret() <= idx {
344			return Ok(());
345		}
346		self.old_secrets[pos as usize] = (secret, idx);
347		Ok(())
348	}
349
350	/// Returns the secret at `idx`.
351	/// Returns `None` if `idx` is < [`CounterpartyCommitmentSecrets::get_min_seen_secret`].
352	pub fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
353		for i in 0..self.old_secrets.len() {
354			if (idx & (!((1 << i) - 1))) == self.old_secrets[i].1 {
355				return Some(Self::derive_secret(self.old_secrets[i].0, i as u8, idx))
356			}
357		}
358		assert!(idx < self.get_min_seen_secret());
359		None
360	}
361}
362
363impl Writeable for CounterpartyCommitmentSecrets {
364	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
365		for &(ref secret, ref idx) in self.old_secrets.iter() {
366			writer.write_all(secret)?;
367			writer.write_all(&idx.to_be_bytes())?;
368		}
369		write_tlv_fields!(writer, {});
370		Ok(())
371	}
372}
373impl Readable for CounterpartyCommitmentSecrets {
374	fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
375		let mut old_secrets = [([0; 32], 1 << 48); 49];
376		for &mut (ref mut secret, ref mut idx) in old_secrets.iter_mut() {
377			*secret = Readable::read(reader)?;
378			*idx = Readable::read(reader)?;
379		}
380		read_tlv_fields!(reader, {});
381		Ok(Self { old_secrets })
382	}
383}
384
385/// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
386/// from the base secret and the per_commitment_point.
387pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> SecretKey {
388	let mut sha = Sha256::engine();
389	sha.input(&per_commitment_point.serialize());
390	sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
391	let res = Sha256::from_engine(sha).to_byte_array();
392
393	base_secret.clone().add_tweak(&Scalar::from_be_bytes(res).unwrap())
394		.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.")
395}
396
397/// Derives a per-commitment-transaction revocation key from its constituent parts.
398///
399/// Only the cheating participant owns a valid witness to propagate a revoked
400/// commitment transaction, thus per_commitment_secret always come from cheater
401/// and revocation_base_secret always come from punisher, which is the broadcaster
402/// of the transaction spending with this key knowledge.
403pub fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>,
404	per_commitment_secret: &SecretKey, countersignatory_revocation_base_secret: &SecretKey)
405-> SecretKey {
406	let countersignatory_revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &countersignatory_revocation_base_secret);
407	let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
408
409	let rev_append_commit_hash_key = {
410		let mut sha = Sha256::engine();
411		sha.input(&countersignatory_revocation_base_point.serialize());
412		sha.input(&per_commitment_point.serialize());
413
414		Sha256::from_engine(sha).to_byte_array()
415	};
416	let commit_append_rev_hash_key = {
417		let mut sha = Sha256::engine();
418		sha.input(&per_commitment_point.serialize());
419		sha.input(&countersignatory_revocation_base_point.serialize());
420
421		Sha256::from_engine(sha).to_byte_array()
422	};
423
424	let countersignatory_contrib = countersignatory_revocation_base_secret.clone().mul_tweak(&Scalar::from_be_bytes(rev_append_commit_hash_key).unwrap())
425		.expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
426	let broadcaster_contrib = per_commitment_secret.clone().mul_tweak(&Scalar::from_be_bytes(commit_append_rev_hash_key).unwrap())
427		.expect("Multiplying a secret key by a hash is expected to never fail per secp256k1 docs");
428	countersignatory_contrib.add_tweak(&Scalar::from_be_bytes(broadcaster_contrib.secret_bytes()).unwrap())
429		.expect("Addition only fails if the tweak is the inverse of the key. This is not possible when the tweak commits to the key.")
430}
431
432/// The set of public keys which are used in the creation of one commitment transaction.
433/// These are derived from the channel base keys and per-commitment data.
434///
435/// A broadcaster key is provided from potential broadcaster of the computed transaction.
436/// A countersignatory key is coming from a protocol participant unable to broadcast the
437/// transaction.
438///
439/// These keys are assumed to be good, either because the code derived them from
440/// channel basepoints via the new function, or they were obtained via
441/// CommitmentTransaction.trust().keys() because we trusted the source of the
442/// pre-calculated keys.
443#[derive(PartialEq, Eq, Clone, Debug)]
444pub struct TxCreationKeys {
445	/// The broadcaster's per-commitment public key which was used to derive the other keys.
446	pub per_commitment_point: PublicKey,
447	/// The revocation key which is used to allow the broadcaster of the commitment
448	/// transaction to provide their counterparty the ability to punish them if they broadcast
449	/// an old state.
450	pub revocation_key: RevocationKey,
451	/// Broadcaster's HTLC Key
452	pub broadcaster_htlc_key: HtlcKey,
453	/// Countersignatory's HTLC Key
454	pub countersignatory_htlc_key: HtlcKey,
455	/// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
456	pub broadcaster_delayed_payment_key: DelayedPaymentKey,
457}
458
459impl_writeable_tlv_based!(TxCreationKeys, {
460	(0, per_commitment_point, required),
461	(2, revocation_key, required),
462	(4, broadcaster_htlc_key, required),
463	(6, countersignatory_htlc_key, required),
464	(8, broadcaster_delayed_payment_key, required),
465});
466
467/// One counterparty's public keys which do not change over the life of a channel.
468#[derive(Clone, Debug, Hash, PartialEq, Eq)]
469pub struct ChannelPublicKeys {
470	/// The public key which is used to sign all commitment transactions, as it appears in the
471	/// on-chain channel lock-in 2-of-2 multisig output.
472	pub funding_pubkey: PublicKey,
473	/// The base point which is used (with [`RevocationKey::from_basepoint`]) to derive per-commitment
474	/// revocation keys. This is combined with the per-commitment-secret generated by the
475	/// counterparty to create a secret which the counterparty can reveal to revoke previous
476	/// states.
477	pub revocation_basepoint: RevocationBasepoint,
478	/// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
479	/// spendable primary channel balance on the broadcaster's commitment transaction. This key is
480	/// static across every commitment transaction.
481	pub payment_point: PublicKey,
482	/// The base point which is used (with derive_public_key) to derive a per-commitment payment
483	/// public key which receives non-HTLC-encumbered funds which are only available for spending
484	/// after some delay (or can be claimed via the revocation path).
485	pub delayed_payment_basepoint: DelayedPaymentBasepoint,
486	/// The base point which is used (with derive_public_key) to derive a per-commitment public key
487	/// which is used to encumber HTLC-in-flight outputs.
488	pub htlc_basepoint: HtlcBasepoint,
489}
490
491impl_writeable_tlv_based!(ChannelPublicKeys, {
492	(0, funding_pubkey, required),
493	(2, revocation_basepoint, required),
494	(4, payment_point, required),
495	(6, delayed_payment_basepoint, required),
496	(8, htlc_basepoint, required),
497});
498
499impl TxCreationKeys {
500	/// Create per-state keys from channel base points and the per-commitment point.
501	/// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
502	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 {
503		TxCreationKeys {
504			per_commitment_point: per_commitment_point.clone(),
505			revocation_key: RevocationKey::from_basepoint(&secp_ctx, &countersignatory_revocation_base, &per_commitment_point),
506			broadcaster_htlc_key: HtlcKey::from_basepoint(&secp_ctx, &broadcaster_htlc_base, &per_commitment_point),
507			countersignatory_htlc_key: HtlcKey::from_basepoint(&secp_ctx, &countersignatory_htlc_base, &per_commitment_point),
508			broadcaster_delayed_payment_key: DelayedPaymentKey::from_basepoint(&secp_ctx, &broadcaster_delayed_payment_base, &per_commitment_point),
509		}
510	}
511
512	/// Generate per-state keys from channel static keys.
513	/// Key set is asymmetric and can't be used as part of counter-signatory set of transactions.
514	pub fn from_channel_static_keys<T: secp256k1::Signing + secp256k1::Verification>(per_commitment_point: &PublicKey, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> TxCreationKeys {
515		TxCreationKeys::derive_new(
516			&secp_ctx,
517			&per_commitment_point,
518			&broadcaster_keys.delayed_payment_basepoint,
519			&broadcaster_keys.htlc_basepoint,
520			&countersignatory_keys.revocation_basepoint,
521			&countersignatory_keys.htlc_basepoint,
522		)
523	}
524}
525
526/// The maximum length of a script returned by get_revokeable_redeemscript.
527// Calculated as 6 bytes of opcodes, 1 byte push plus 3 bytes for contest_delay, and two public
528// keys of 33 bytes (+ 1 push). Generally, pushes are only 2 bytes (for values below 0x7fff, i.e.
529// around 7 months), however, a 7 month contest delay shouldn't result in being unable to reclaim
530// on-chain funds.
531pub const REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH: usize = 6 + 4 + 34*2;
532
533/// A script either spendable by the revocation
534/// key or the broadcaster_delayed_payment_key and satisfying the relative-locktime OP_CSV constrain.
535/// Encumbering a `to_holder` output on a commitment transaction or 2nd-stage HTLC transactions.
536pub fn get_revokeable_redeemscript(revocation_key: &RevocationKey, contest_delay: u16, broadcaster_delayed_payment_key: &DelayedPaymentKey) -> ScriptBuf {
537	let res = Builder::new().push_opcode(opcodes::all::OP_IF)
538	              .push_slice(&revocation_key.to_public_key().serialize())
539	              .push_opcode(opcodes::all::OP_ELSE)
540	              .push_int(contest_delay as i64)
541	              .push_opcode(opcodes::all::OP_CSV)
542	              .push_opcode(opcodes::all::OP_DROP)
543	              .push_slice(&broadcaster_delayed_payment_key.to_public_key().serialize())
544	              .push_opcode(opcodes::all::OP_ENDIF)
545	              .push_opcode(opcodes::all::OP_CHECKSIG)
546	              .into_script();
547	debug_assert!(res.len() <= REVOKEABLE_REDEEMSCRIPT_MAX_LENGTH);
548	res
549}
550
551/// Returns the script for the counterparty's output on a holder's commitment transaction based on
552/// the channel type.
553pub fn get_counterparty_payment_script(channel_type_features: &ChannelTypeFeatures, payment_key: &PublicKey) -> ScriptBuf {
554	if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
555		get_to_countersignatory_with_anchors_redeemscript(payment_key).to_p2wsh()
556	} else {
557		ScriptBuf::new_p2wpkh(&WPubkeyHash::hash(&payment_key.serialize()))
558	}
559}
560
561/// Information about an HTLC as it appears in a commitment transaction
562#[derive(Clone, Debug, PartialEq, Eq)]
563pub struct HTLCOutputInCommitment {
564	/// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
565	/// Note that this is not the same as whether it is ountbound *from us*. To determine that you
566	/// need to compare this value to whether the commitment transaction in question is that of
567	/// the counterparty or our own.
568	pub offered: bool,
569	/// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
570	/// this divided by 1000.
571	pub amount_msat: u64,
572	/// The CLTV lock-time at which this HTLC expires.
573	pub cltv_expiry: u32,
574	/// The hash of the preimage which unlocks this HTLC.
575	pub payment_hash: PaymentHash,
576	/// The position within the commitment transactions' outputs. This may be None if the value is
577	/// below the dust limit (in which case no output appears in the commitment transaction and the
578	/// value is spent to additional transaction fees).
579	pub transaction_output_index: Option<u32>,
580}
581
582impl HTLCOutputInCommitment {
583	/// Converts HTLC's value with millisatoshi precision into [bitcoin::Amount] with satoshi precision.
584	/// Typically this conversion is needed when transitioning from LN into base-layer Bitcoin,
585	/// e. g. in commitment transactions.
586	pub const fn to_bitcoin_amount(&self) -> Amount {
587		Amount::from_sat(self.amount_msat / 1000)
588	}
589}
590
591impl_writeable_tlv_based!(HTLCOutputInCommitment, {
592	(0, offered, required),
593	(2, amount_msat, required),
594	(4, cltv_expiry, required),
595	(6, payment_hash, required),
596	(8, transaction_output_index, option),
597});
598
599#[inline]
600pub(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 {
601	let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).to_byte_array();
602	if htlc.offered {
603		let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
604		              .push_opcode(opcodes::all::OP_HASH160)
605		              .push_slice(PubkeyHash::hash(&revocation_key.to_public_key().serialize()))
606		              .push_opcode(opcodes::all::OP_EQUAL)
607		              .push_opcode(opcodes::all::OP_IF)
608		              .push_opcode(opcodes::all::OP_CHECKSIG)
609		              .push_opcode(opcodes::all::OP_ELSE)
610		              .push_slice(&countersignatory_htlc_key.to_public_key().serialize())
611		              .push_opcode(opcodes::all::OP_SWAP)
612		              .push_opcode(opcodes::all::OP_SIZE)
613		              .push_int(32)
614		              .push_opcode(opcodes::all::OP_EQUAL)
615		              .push_opcode(opcodes::all::OP_NOTIF)
616		              .push_opcode(opcodes::all::OP_DROP)
617		              .push_int(2)
618		              .push_opcode(opcodes::all::OP_SWAP)
619		              .push_slice(&broadcaster_htlc_key.to_public_key().serialize())
620		              .push_int(2)
621		              .push_opcode(opcodes::all::OP_CHECKMULTISIG)
622		              .push_opcode(opcodes::all::OP_ELSE)
623		              .push_opcode(opcodes::all::OP_HASH160)
624		              .push_slice(&payment_hash160)
625		              .push_opcode(opcodes::all::OP_EQUALVERIFY)
626		              .push_opcode(opcodes::all::OP_CHECKSIG)
627		              .push_opcode(opcodes::all::OP_ENDIF);
628		if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
629			bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
630				.push_opcode(opcodes::all::OP_CSV)
631				.push_opcode(opcodes::all::OP_DROP);
632		}
633		bldr.push_opcode(opcodes::all::OP_ENDIF)
634			.into_script()
635	} else {
636			let mut bldr = Builder::new().push_opcode(opcodes::all::OP_DUP)
637		              .push_opcode(opcodes::all::OP_HASH160)
638		              .push_slice(&PubkeyHash::hash(&revocation_key.to_public_key().serialize()))
639		              .push_opcode(opcodes::all::OP_EQUAL)
640		              .push_opcode(opcodes::all::OP_IF)
641		              .push_opcode(opcodes::all::OP_CHECKSIG)
642		              .push_opcode(opcodes::all::OP_ELSE)
643		              .push_slice(&countersignatory_htlc_key.to_public_key().serialize())
644		              .push_opcode(opcodes::all::OP_SWAP)
645		              .push_opcode(opcodes::all::OP_SIZE)
646		              .push_int(32)
647		              .push_opcode(opcodes::all::OP_EQUAL)
648		              .push_opcode(opcodes::all::OP_IF)
649		              .push_opcode(opcodes::all::OP_HASH160)
650		              .push_slice(&payment_hash160)
651		              .push_opcode(opcodes::all::OP_EQUALVERIFY)
652		              .push_int(2)
653		              .push_opcode(opcodes::all::OP_SWAP)
654		              .push_slice(&broadcaster_htlc_key.to_public_key().serialize())
655		              .push_int(2)
656		              .push_opcode(opcodes::all::OP_CHECKMULTISIG)
657		              .push_opcode(opcodes::all::OP_ELSE)
658		              .push_opcode(opcodes::all::OP_DROP)
659		              .push_int(htlc.cltv_expiry as i64)
660		              .push_opcode(opcodes::all::OP_CLTV)
661		              .push_opcode(opcodes::all::OP_DROP)
662		              .push_opcode(opcodes::all::OP_CHECKSIG)
663		              .push_opcode(opcodes::all::OP_ENDIF);
664		if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
665			bldr = bldr.push_opcode(opcodes::all::OP_PUSHNUM_1)
666				.push_opcode(opcodes::all::OP_CSV)
667				.push_opcode(opcodes::all::OP_DROP);
668		}
669		bldr.push_opcode(opcodes::all::OP_ENDIF)
670			.into_script()
671	}
672}
673
674/// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
675/// does not need to have its previous_output_index filled.
676#[inline]
677pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, keys: &TxCreationKeys) -> ScriptBuf {
678	get_htlc_redeemscript_with_explicit_keys(htlc, channel_type_features, &keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key)
679}
680
681/// Gets the redeemscript for a funding output from the two funding public keys.
682/// Note that the order of funding public keys does not matter.
683pub fn make_funding_redeemscript(broadcaster: &PublicKey, countersignatory: &PublicKey) -> ScriptBuf {
684	let broadcaster_funding_key = broadcaster.serialize();
685	let countersignatory_funding_key = countersignatory.serialize();
686
687	make_funding_redeemscript_from_slices(&broadcaster_funding_key, &countersignatory_funding_key)
688}
689
690pub(crate) fn make_funding_redeemscript_from_slices(broadcaster_funding_key: &[u8; 33], countersignatory_funding_key: &[u8; 33]) -> ScriptBuf {
691	let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
692	if broadcaster_funding_key[..] < countersignatory_funding_key[..] {
693		builder.push_slice(broadcaster_funding_key)
694			.push_slice(countersignatory_funding_key)
695	} else {
696		builder.push_slice(countersignatory_funding_key)
697			.push_slice(broadcaster_funding_key)
698	}.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
699}
700
701/// Builds an unsigned HTLC-Success or HTLC-Timeout transaction from the given channel and HTLC
702/// parameters. This is used by [`TrustedCommitmentTransaction::get_htlc_sigs`] to fetch the
703/// transaction which needs signing, and can be used to construct an HTLC transaction which is
704/// broadcastable given a counterparty HTLC signature.
705///
706/// Panics if htlc.transaction_output_index.is_none() (as such HTLCs do not appear in the
707/// commitment transaction).
708pub fn build_htlc_transaction(commitment_txid: &Txid, feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, broadcaster_delayed_payment_key: &DelayedPaymentKey, revocation_key: &RevocationKey) -> Transaction {
709	let txins= vec![build_htlc_input(commitment_txid, htlc, channel_type_features)];
710
711	let mut txouts: Vec<TxOut> = Vec::new();
712	txouts.push(build_htlc_output(
713		feerate_per_kw, contest_delay, htlc, channel_type_features,
714		broadcaster_delayed_payment_key, revocation_key
715	));
716
717	Transaction {
718		version: Version::TWO,
719		lock_time: LockTime::from_consensus(if htlc.offered { htlc.cltv_expiry } else { 0 }),
720		input: txins,
721		output: txouts,
722	}
723}
724
725pub(crate) fn build_htlc_input(commitment_txid: &Txid, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures) -> TxIn {
726	TxIn {
727		previous_output: OutPoint {
728			txid: commitment_txid.clone(),
729			vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
730		},
731		script_sig: ScriptBuf::new(),
732		sequence: Sequence(if channel_type_features.supports_anchors_zero_fee_htlc_tx() { 1 } else { 0 }),
733		witness: Witness::new(),
734	}
735}
736
737pub(crate) fn build_htlc_output(
738	feerate_per_kw: u32, contest_delay: u16, htlc: &HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures, broadcaster_delayed_payment_key: &DelayedPaymentKey, revocation_key: &RevocationKey
739) -> TxOut {
740	let weight = if htlc.offered {
741		htlc_timeout_tx_weight(channel_type_features)
742	} else {
743		htlc_success_tx_weight(channel_type_features)
744	};
745	let output_value = if channel_type_features.supports_anchors_zero_fee_htlc_tx() && !channel_type_features.supports_anchors_nonzero_fee_htlc_tx() {
746		htlc.to_bitcoin_amount()
747	} else {
748		let total_fee = Amount::from_sat(feerate_per_kw as u64 * weight / 1000);
749		htlc.to_bitcoin_amount() - total_fee
750	};
751
752	TxOut {
753		script_pubkey: get_revokeable_redeemscript(revocation_key, contest_delay, broadcaster_delayed_payment_key).to_p2wsh(),
754		value: output_value,
755	}
756}
757
758/// Returns the witness required to satisfy and spend a HTLC input.
759pub fn build_htlc_input_witness(
760	local_sig: &Signature, remote_sig: &Signature, preimage: &Option<PaymentPreimage>,
761	redeem_script: &Script, channel_type_features: &ChannelTypeFeatures,
762) -> Witness {
763	let remote_sighash_type = if channel_type_features.supports_anchors_zero_fee_htlc_tx() {
764		EcdsaSighashType::SinglePlusAnyoneCanPay
765	} else {
766		EcdsaSighashType::All
767	};
768
769	let mut witness = Witness::new();
770	// First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
771	witness.push(vec![]);
772	witness.push_ecdsa_signature(&BitcoinSignature { signature: *remote_sig, sighash_type: remote_sighash_type });
773	witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(*local_sig));
774	if let Some(preimage) = preimage {
775		witness.push(preimage.0.to_vec());
776	} else {
777		// Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
778		witness.push(vec![]);
779	}
780	witness.push(redeem_script.to_bytes());
781	witness
782}
783
784/// Pre-anchors channel type features did not use to get serialized in the following six structs:
785/// — [`ChannelTransactionParameters`]
786/// — [`CommitmentTransaction`]
787/// — [`CounterpartyOfferedHTLCOutput`]
788/// — [`CounterpartyReceivedHTLCOutput`]
789/// — [`HolderHTLCOutput`]
790/// — [`HolderFundingOutput`]
791///
792/// To ensure a forwards-compatible serialization, we use odd TLV fields. However, if new features
793/// are used that could break security, where old signers should be prevented from handling the
794/// serialized data, an optional even-field TLV will be used as a stand-in to break compatibility.
795///
796/// This method determines whether or not that option needs to be set based on the chanenl type
797/// features, and returns it.
798///
799/// [`CounterpartyOfferedHTLCOutput`]: crate::chain::package::CounterpartyOfferedHTLCOutput
800/// [`CounterpartyReceivedHTLCOutput`]: crate::chain::package::CounterpartyReceivedHTLCOutput
801/// [`HolderHTLCOutput`]: crate::chain::package::HolderHTLCOutput
802/// [`HolderFundingOutput`]: crate::chain::package::HolderFundingOutput
803pub(crate) fn legacy_deserialization_prevention_marker_for_channel_type_features(features: &ChannelTypeFeatures) -> Option<()> {
804	let mut legacy_version_bit_set = ChannelTypeFeatures::only_static_remote_key();
805	legacy_version_bit_set.set_scid_privacy_required();
806	legacy_version_bit_set.set_zero_conf_required();
807
808	debug_assert!(!legacy_version_bit_set.supports_any_optional_bits());
809	debug_assert!(!features.supports_any_optional_bits());
810	if features.requires_unknown_bits_from(&legacy_version_bit_set) {
811		Some(())
812	} else {
813		None
814	}
815}
816
817/// Gets the witnessScript for the to_remote output when anchors are enabled.
818#[inline]
819pub fn get_to_countersignatory_with_anchors_redeemscript(payment_point: &PublicKey) -> ScriptBuf {
820	Builder::new()
821		.push_slice(payment_point.serialize())
822		.push_opcode(opcodes::all::OP_CHECKSIGVERIFY)
823		.push_int(1)
824		.push_opcode(opcodes::all::OP_CSV)
825		.into_script()
826}
827
828/// Gets the witnessScript for an anchor output from the funding public key.
829/// The witness in the spending input must be:
830/// <BIP 143 funding_signature>
831/// After 16 blocks of confirmation, an alternative satisfying witness could be:
832/// <>
833/// (empty vector required to satisfy compliance with MINIMALIF-standard rule)
834#[inline]
835pub fn get_anchor_redeemscript(funding_pubkey: &PublicKey) -> ScriptBuf {
836	Builder::new().push_slice(funding_pubkey.serialize())
837		.push_opcode(opcodes::all::OP_CHECKSIG)
838		.push_opcode(opcodes::all::OP_IFDUP)
839		.push_opcode(opcodes::all::OP_NOTIF)
840		.push_int(16)
841		.push_opcode(opcodes::all::OP_CSV)
842		.push_opcode(opcodes::all::OP_ENDIF)
843		.into_script()
844}
845
846/// Locates the output with an anchor script paying to `funding_pubkey` within `commitment_tx`.
847pub(crate) fn get_anchor_output<'a>(commitment_tx: &'a Transaction, funding_pubkey: &PublicKey) -> Option<(u32, &'a TxOut)> {
848	let anchor_script = get_anchor_redeemscript(funding_pubkey).to_p2wsh();
849	commitment_tx.output.iter().enumerate()
850		.find(|(_, txout)| txout.script_pubkey == anchor_script)
851		.map(|(idx, txout)| (idx as u32, txout))
852}
853
854/// Returns the witness required to satisfy and spend an anchor input.
855pub fn build_anchor_input_witness(funding_key: &PublicKey, funding_sig: &Signature) -> Witness {
856	let anchor_redeem_script = get_anchor_redeemscript(funding_key);
857	let mut ret = Witness::new();
858	ret.push_ecdsa_signature(&BitcoinSignature::sighash_all(*funding_sig));
859	ret.push(anchor_redeem_script.as_bytes());
860	ret
861}
862
863/// Per-channel data used to build transactions in conjunction with the per-commitment data (CommitmentTransaction).
864/// The fields are organized by holder/counterparty.
865///
866/// Normally, this is converted to the broadcaster/countersignatory-organized DirectedChannelTransactionParameters
867/// before use, via the as_holder_broadcastable and as_counterparty_broadcastable functions.
868#[derive(Clone, Debug, Hash, PartialEq, Eq)]
869pub struct ChannelTransactionParameters {
870	/// Holder public keys
871	pub holder_pubkeys: ChannelPublicKeys,
872	/// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
873	pub holder_selected_contest_delay: u16,
874	/// Whether the holder is the initiator of this channel.
875	/// This is an input to the commitment number obscure factor computation.
876	pub is_outbound_from_holder: bool,
877	/// The late-bound counterparty channel transaction parameters.
878	/// These parameters are populated at the point in the protocol where the counterparty provides them.
879	pub counterparty_parameters: Option<CounterpartyChannelTransactionParameters>,
880	/// The late-bound funding outpoint
881	pub funding_outpoint: Option<chain::transaction::OutPoint>,
882	/// This channel's type, as negotiated during channel open. For old objects where this field
883	/// wasn't serialized, it will default to static_remote_key at deserialization.
884	pub channel_type_features: ChannelTypeFeatures
885}
886
887/// Late-bound per-channel counterparty data used to build transactions.
888#[derive(Clone, Debug, Hash, PartialEq, Eq)]
889pub struct CounterpartyChannelTransactionParameters {
890	/// Counter-party public keys
891	pub pubkeys: ChannelPublicKeys,
892	/// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
893	pub selected_contest_delay: u16,
894}
895
896impl ChannelTransactionParameters {
897	/// Whether the late bound parameters are populated.
898	pub fn is_populated(&self) -> bool {
899		self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
900	}
901
902	/// Whether the channel supports zero-fee HTLC transaction anchors.
903	pub(crate) fn supports_anchors(&self) -> bool {
904		self.channel_type_features.supports_anchors_zero_fee_htlc_tx()
905	}
906
907	/// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
908	/// given that the holder is the broadcaster.
909	///
910	/// self.is_populated() must be true before calling this function.
911	pub fn as_holder_broadcastable(&self) -> DirectedChannelTransactionParameters {
912		assert!(self.is_populated(), "self.late_parameters must be set before using as_holder_broadcastable");
913		DirectedChannelTransactionParameters {
914			inner: self,
915			holder_is_broadcaster: true
916		}
917	}
918
919	/// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
920	/// given that the counterparty is the broadcaster.
921	///
922	/// self.is_populated() must be true before calling this function.
923	pub fn as_counterparty_broadcastable(&self) -> DirectedChannelTransactionParameters {
924		assert!(self.is_populated(), "self.late_parameters must be set before using as_counterparty_broadcastable");
925		DirectedChannelTransactionParameters {
926			inner: self,
927			holder_is_broadcaster: false
928		}
929	}
930
931	#[cfg(test)]
932	pub fn test_dummy() -> Self {
933		let dummy_keys = ChannelPublicKeys {
934			funding_pubkey: PublicKey::from_slice(&[2; 33]).unwrap(),
935			revocation_basepoint: PublicKey::from_slice(&[2; 33]).unwrap().into(),
936			payment_point: PublicKey::from_slice(&[2; 33]).unwrap(),
937			delayed_payment_basepoint: PublicKey::from_slice(&[2; 33]).unwrap().into(),
938			htlc_basepoint: PublicKey::from_slice(&[2; 33]).unwrap().into(),
939		};
940		Self {
941			holder_pubkeys: dummy_keys.clone(),
942			holder_selected_contest_delay: 42,
943			is_outbound_from_holder: true,
944			counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
945				pubkeys: dummy_keys,
946				selected_contest_delay: 42,
947			}),
948			funding_outpoint: Some(chain::transaction::OutPoint {
949				txid: Txid::from_byte_array([42; 32]), index: 0
950			}),
951			channel_type_features: ChannelTypeFeatures::empty(),
952		}
953	}
954}
955
956impl_writeable_tlv_based!(CounterpartyChannelTransactionParameters, {
957	(0, pubkeys, required),
958	(2, selected_contest_delay, required),
959});
960
961impl Writeable for ChannelTransactionParameters {
962	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
963		let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
964		write_tlv_fields!(writer, {
965			(0, self.holder_pubkeys, required),
966			(2, self.holder_selected_contest_delay, required),
967			(4, self.is_outbound_from_holder, required),
968			(6, self.counterparty_parameters, option),
969			(8, self.funding_outpoint, option),
970			(10, legacy_deserialization_prevention_marker, option),
971			(11, self.channel_type_features, required),
972		});
973		Ok(())
974	}
975}
976
977impl Readable for ChannelTransactionParameters {
978	fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
979		let mut holder_pubkeys = RequiredWrapper(None);
980		let mut holder_selected_contest_delay = RequiredWrapper(None);
981		let mut is_outbound_from_holder = RequiredWrapper(None);
982		let mut counterparty_parameters = None;
983		let mut funding_outpoint = None;
984		let mut _legacy_deserialization_prevention_marker: Option<()> = None;
985		let mut channel_type_features = None;
986
987		read_tlv_fields!(reader, {
988			(0, holder_pubkeys, required),
989			(2, holder_selected_contest_delay, required),
990			(4, is_outbound_from_holder, required),
991			(6, counterparty_parameters, option),
992			(8, funding_outpoint, option),
993			(10, _legacy_deserialization_prevention_marker, option),
994			(11, channel_type_features, option),
995		});
996
997		let mut additional_features = ChannelTypeFeatures::empty();
998		additional_features.set_anchors_nonzero_fee_htlc_tx_required();
999		chain::package::verify_channel_type_features(&channel_type_features, Some(&additional_features))?;
1000
1001		Ok(Self {
1002			holder_pubkeys: holder_pubkeys.0.unwrap(),
1003			holder_selected_contest_delay: holder_selected_contest_delay.0.unwrap(),
1004			is_outbound_from_holder: is_outbound_from_holder.0.unwrap(),
1005			counterparty_parameters,
1006			funding_outpoint,
1007			channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
1008		})
1009	}
1010}
1011
1012/// Static channel fields used to build transactions given per-commitment fields, organized by
1013/// broadcaster/countersignatory.
1014///
1015/// This is derived from the holder/counterparty-organized ChannelTransactionParameters via the
1016/// as_holder_broadcastable and as_counterparty_broadcastable functions.
1017pub struct DirectedChannelTransactionParameters<'a> {
1018	/// The holder's channel static parameters
1019	inner: &'a ChannelTransactionParameters,
1020	/// Whether the holder is the broadcaster
1021	holder_is_broadcaster: bool,
1022}
1023
1024impl<'a> DirectedChannelTransactionParameters<'a> {
1025	/// Get the channel pubkeys for the broadcaster
1026	pub fn broadcaster_pubkeys(&self) -> &'a ChannelPublicKeys {
1027		if self.holder_is_broadcaster {
1028			&self.inner.holder_pubkeys
1029		} else {
1030			&self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
1031		}
1032	}
1033
1034	/// Get the channel pubkeys for the countersignatory
1035	pub fn countersignatory_pubkeys(&self) -> &'a ChannelPublicKeys {
1036		if self.holder_is_broadcaster {
1037			&self.inner.counterparty_parameters.as_ref().unwrap().pubkeys
1038		} else {
1039			&self.inner.holder_pubkeys
1040		}
1041	}
1042
1043	/// Get the contest delay applicable to the transactions.
1044	/// Note that the contest delay was selected by the countersignatory.
1045	pub fn contest_delay(&self) -> u16 {
1046		let counterparty_parameters = self.inner.counterparty_parameters.as_ref().unwrap();
1047		if self.holder_is_broadcaster { counterparty_parameters.selected_contest_delay } else { self.inner.holder_selected_contest_delay }
1048	}
1049
1050	/// Whether the channel is outbound from the broadcaster.
1051	///
1052	/// The boolean representing the side that initiated the channel is
1053	/// an input to the commitment number obscure factor computation.
1054	pub fn is_outbound(&self) -> bool {
1055		if self.holder_is_broadcaster { self.inner.is_outbound_from_holder } else { !self.inner.is_outbound_from_holder }
1056	}
1057
1058	/// The funding outpoint
1059	pub fn funding_outpoint(&self) -> OutPoint {
1060		self.inner.funding_outpoint.unwrap().into_bitcoin_outpoint()
1061	}
1062
1063	/// Whether to use anchors for this channel
1064	pub fn channel_type_features(&self) -> &'a ChannelTypeFeatures {
1065		&self.inner.channel_type_features
1066	}
1067}
1068
1069/// Information needed to build and sign a holder's commitment transaction.
1070///
1071/// The transaction is only signed once we are ready to broadcast.
1072#[derive(Clone, Debug)]
1073pub struct HolderCommitmentTransaction {
1074	inner: CommitmentTransaction,
1075	/// Our counterparty's signature for the transaction
1076	pub counterparty_sig: Signature,
1077	/// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
1078	pub counterparty_htlc_sigs: Vec<Signature>,
1079	// Which order the signatures should go in when constructing the final commitment tx witness.
1080	// The user should be able to reconstruct this themselves, so we don't bother to expose it.
1081	holder_sig_first: bool,
1082}
1083
1084impl Deref for HolderCommitmentTransaction {
1085	type Target = CommitmentTransaction;
1086
1087	fn deref(&self) -> &Self::Target { &self.inner }
1088}
1089
1090impl Eq for HolderCommitmentTransaction {}
1091impl PartialEq for HolderCommitmentTransaction {
1092	// We dont care whether we are signed in equality comparison
1093	fn eq(&self, o: &Self) -> bool {
1094		self.inner == o.inner
1095	}
1096}
1097
1098impl_writeable_tlv_based!(HolderCommitmentTransaction, {
1099	(0, inner, required),
1100	(2, counterparty_sig, required),
1101	(4, holder_sig_first, required),
1102	(6, counterparty_htlc_sigs, required_vec),
1103});
1104
1105impl HolderCommitmentTransaction {
1106	#[cfg(test)]
1107	pub fn dummy(htlcs: &mut Vec<(HTLCOutputInCommitment, ())>) -> Self {
1108		let secp_ctx = Secp256k1::new();
1109		let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1110		let dummy_sig = sign(&secp_ctx, &secp256k1::Message::from_digest([42; 32]), &SecretKey::from_slice(&[42; 32]).unwrap());
1111
1112		let keys = TxCreationKeys {
1113			per_commitment_point: dummy_key.clone(),
1114			revocation_key: RevocationKey::from_basepoint(&secp_ctx, &RevocationBasepoint::from(dummy_key), &dummy_key),
1115			broadcaster_htlc_key: HtlcKey::from_basepoint(&secp_ctx, &HtlcBasepoint::from(dummy_key), &dummy_key),
1116			countersignatory_htlc_key: HtlcKey::from_basepoint(&secp_ctx, &HtlcBasepoint::from(dummy_key), &dummy_key),
1117			broadcaster_delayed_payment_key: DelayedPaymentKey::from_basepoint(&secp_ctx, &DelayedPaymentBasepoint::from(dummy_key), &dummy_key),
1118		};
1119		let channel_pubkeys = ChannelPublicKeys {
1120			funding_pubkey: dummy_key.clone(),
1121			revocation_basepoint: RevocationBasepoint::from(dummy_key),
1122			payment_point: dummy_key.clone(),
1123			delayed_payment_basepoint: DelayedPaymentBasepoint::from(dummy_key.clone()),
1124			htlc_basepoint: HtlcBasepoint::from(dummy_key.clone())
1125		};
1126		let channel_parameters = ChannelTransactionParameters {
1127			holder_pubkeys: channel_pubkeys.clone(),
1128			holder_selected_contest_delay: 0,
1129			is_outbound_from_holder: false,
1130			counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: channel_pubkeys.clone(), selected_contest_delay: 0 }),
1131			funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1132			channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
1133		};
1134		let mut counterparty_htlc_sigs = Vec::new();
1135		for _ in 0..htlcs.len() {
1136			counterparty_htlc_sigs.push(dummy_sig);
1137		}
1138		let inner = CommitmentTransaction::new_with_auxiliary_htlc_data(0, 0, 0, dummy_key.clone(), dummy_key.clone(), keys, 0, htlcs, &channel_parameters.as_counterparty_broadcastable());
1139		htlcs.sort_by_key(|htlc| htlc.0.transaction_output_index);
1140		HolderCommitmentTransaction {
1141			inner,
1142			counterparty_sig: dummy_sig,
1143			counterparty_htlc_sigs,
1144			holder_sig_first: false
1145		}
1146	}
1147
1148	/// Create a new holder transaction with the given counterparty signatures.
1149	/// The funding keys are used to figure out which signature should go first when building the transaction for broadcast.
1150	pub fn new(commitment_tx: CommitmentTransaction, counterparty_sig: Signature, counterparty_htlc_sigs: Vec<Signature>, holder_funding_key: &PublicKey, counterparty_funding_key: &PublicKey) -> Self {
1151		Self {
1152			inner: commitment_tx,
1153			counterparty_sig,
1154			counterparty_htlc_sigs,
1155			holder_sig_first: holder_funding_key.serialize()[..] < counterparty_funding_key.serialize()[..],
1156		}
1157	}
1158
1159	pub(crate) fn add_holder_sig(&self, funding_redeemscript: &Script, holder_sig: Signature) -> Transaction {
1160		// First push the multisig dummy, note that due to BIP147 (NULLDUMMY) it must be a zero-length element.
1161		let mut tx = self.inner.built.transaction.clone();
1162		tx.input[0].witness.push(Vec::new());
1163
1164		if self.holder_sig_first {
1165			tx.input[0].witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(holder_sig));
1166			tx.input[0].witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(self.counterparty_sig));
1167		} else {
1168			tx.input[0].witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(self.counterparty_sig));
1169			tx.input[0].witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(holder_sig));
1170		}
1171
1172		tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
1173		tx
1174	}
1175}
1176
1177/// A pre-built Bitcoin commitment transaction and its txid.
1178#[derive(Clone, Debug)]
1179pub struct BuiltCommitmentTransaction {
1180	/// The commitment transaction
1181	pub transaction: Transaction,
1182	/// The txid for the commitment transaction.
1183	///
1184	/// This is provided as a performance optimization, instead of calling transaction.txid()
1185	/// multiple times.
1186	pub txid: Txid,
1187}
1188
1189impl_writeable_tlv_based!(BuiltCommitmentTransaction, {
1190	(0, transaction, required),
1191	(2, txid, required),
1192});
1193
1194impl BuiltCommitmentTransaction {
1195	/// Get the SIGHASH_ALL sighash value of the transaction.
1196	///
1197	/// This can be used to verify a signature.
1198	pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1199		let sighash = &sighash::SighashCache::new(&self.transaction).p2wsh_signature_hash(0, funding_redeemscript, Amount::from_sat(channel_value_satoshis), EcdsaSighashType::All).unwrap()[..];
1200		hash_to_message!(sighash)
1201	}
1202
1203	/// Signs the counterparty's commitment transaction.
1204	pub fn sign_counterparty_commitment<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1205		let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1206		sign(secp_ctx, &sighash, funding_key)
1207	}
1208
1209	/// Signs the holder commitment transaction because we are about to broadcast it.
1210	pub fn sign_holder_commitment<T: secp256k1::Signing, ES: Deref>(
1211		&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64,
1212		entropy_source: &ES, secp_ctx: &Secp256k1<T>
1213	) -> Signature where ES::Target: EntropySource {
1214		let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1215		sign_with_aux_rand(secp_ctx, &sighash, funding_key, entropy_source)
1216	}
1217}
1218
1219/// This class tracks the per-transaction information needed to build a closing transaction and will
1220/// actually build it and sign.
1221///
1222/// This class can be used inside a signer implementation to generate a signature given the relevant
1223/// secret key.
1224#[derive(Clone, Hash, PartialEq, Eq)]
1225pub struct ClosingTransaction {
1226	to_holder_value_sat: Amount,
1227	to_counterparty_value_sat: Amount,
1228	to_holder_script: ScriptBuf,
1229	to_counterparty_script: ScriptBuf,
1230	built: Transaction,
1231}
1232
1233impl ClosingTransaction {
1234	/// Construct an object of the class
1235	pub fn new(
1236		to_holder_value_sat: u64,
1237		to_counterparty_value_sat: u64,
1238		to_holder_script: ScriptBuf,
1239		to_counterparty_script: ScriptBuf,
1240		funding_outpoint: OutPoint,
1241	) -> Self {
1242		let to_holder_value_sat = Amount::from_sat(to_holder_value_sat);
1243		let to_counterparty_value_sat = Amount::from_sat(to_counterparty_value_sat);
1244		let built = build_closing_transaction(
1245			to_holder_value_sat, to_counterparty_value_sat,
1246			to_holder_script.clone(), to_counterparty_script.clone(),
1247			funding_outpoint
1248		);
1249		ClosingTransaction {
1250			to_holder_value_sat,
1251			to_counterparty_value_sat,
1252			to_holder_script,
1253			to_counterparty_script,
1254			built
1255		}
1256	}
1257
1258	/// Trust our pre-built transaction.
1259	///
1260	/// Applies a wrapper which allows access to the transaction.
1261	///
1262	/// This should only be used if you fully trust the builder of this object. It should not
1263	/// be used by an external signer - instead use the verify function.
1264	pub fn trust(&self) -> TrustedClosingTransaction {
1265		TrustedClosingTransaction { inner: self }
1266	}
1267
1268	/// Verify our pre-built transaction.
1269	///
1270	/// Applies a wrapper which allows access to the transaction.
1271	///
1272	/// An external validating signer must call this method before signing
1273	/// or using the built transaction.
1274	pub fn verify(&self, funding_outpoint: OutPoint) -> Result<TrustedClosingTransaction, ()> {
1275		let built = build_closing_transaction(
1276			self.to_holder_value_sat, self.to_counterparty_value_sat,
1277			self.to_holder_script.clone(), self.to_counterparty_script.clone(),
1278			funding_outpoint
1279		);
1280		if self.built != built {
1281			return Err(())
1282		}
1283		Ok(TrustedClosingTransaction { inner: self })
1284	}
1285
1286	/// The value to be sent to the holder, or zero if the output will be omitted
1287	pub fn to_holder_value_sat(&self) -> u64 {
1288		self.to_holder_value_sat.to_sat()
1289	}
1290
1291	/// The value to be sent to the counterparty, or zero if the output will be omitted
1292	pub fn to_counterparty_value_sat(&self) -> u64 {
1293		self.to_counterparty_value_sat.to_sat()
1294	}
1295
1296	/// The destination of the holder's output
1297	pub fn to_holder_script(&self) -> &Script {
1298		&self.to_holder_script
1299	}
1300
1301	/// The destination of the counterparty's output
1302	pub fn to_counterparty_script(&self) -> &Script {
1303		&self.to_counterparty_script
1304	}
1305}
1306
1307/// A wrapper on ClosingTransaction indicating that the built bitcoin
1308/// transaction is trusted.
1309///
1310/// See trust() and verify() functions on CommitmentTransaction.
1311///
1312/// This structure implements Deref.
1313pub struct TrustedClosingTransaction<'a> {
1314	inner: &'a ClosingTransaction,
1315}
1316
1317impl<'a> Deref for TrustedClosingTransaction<'a> {
1318	type Target = ClosingTransaction;
1319
1320	fn deref(&self) -> &Self::Target { self.inner }
1321}
1322
1323impl<'a> TrustedClosingTransaction<'a> {
1324	/// The pre-built Bitcoin commitment transaction
1325	pub fn built_transaction(&self) -> &'a Transaction {
1326		&self.inner.built
1327	}
1328
1329	/// Get the SIGHASH_ALL sighash value of the transaction.
1330	///
1331	/// This can be used to verify a signature.
1332	pub fn get_sighash_all(&self, funding_redeemscript: &Script, channel_value_satoshis: u64) -> Message {
1333		let sighash = &sighash::SighashCache::new(&self.inner.built).p2wsh_signature_hash(0, funding_redeemscript, Amount::from_sat(channel_value_satoshis), EcdsaSighashType::All).unwrap()[..];
1334		hash_to_message!(sighash)
1335	}
1336
1337	/// Sign a transaction, either because we are counter-signing the counterparty's transaction or
1338	/// because we are about to broadcast a holder transaction.
1339	pub fn sign<T: secp256k1::Signing>(&self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) -> Signature {
1340		let sighash = self.get_sighash_all(funding_redeemscript, channel_value_satoshis);
1341		sign(secp_ctx, &sighash, funding_key)
1342	}
1343}
1344
1345/// This class tracks the per-transaction information needed to build a commitment transaction and will
1346/// actually build it and sign.  It is used for holder transactions that we sign only when needed
1347/// and for transactions we sign for the counterparty.
1348///
1349/// This class can be used inside a signer implementation to generate a signature given the relevant
1350/// secret key.
1351#[derive(Clone, Debug)]
1352pub struct CommitmentTransaction {
1353	commitment_number: u64,
1354	to_broadcaster_value_sat: Amount,
1355	to_countersignatory_value_sat: Amount,
1356	to_broadcaster_delay: Option<u16>, // Added in 0.0.117
1357	feerate_per_kw: u32,
1358	htlcs: Vec<HTLCOutputInCommitment>,
1359	// Note that on upgrades, some features of existing outputs may be missed.
1360	channel_type_features: ChannelTypeFeatures,
1361	// A cache of the parties' pubkeys required to construct the transaction, see doc for trust()
1362	keys: TxCreationKeys,
1363	// For access to the pre-built transaction, see doc for trust()
1364	built: BuiltCommitmentTransaction,
1365}
1366
1367impl Eq for CommitmentTransaction {}
1368impl PartialEq for CommitmentTransaction {
1369	fn eq(&self, o: &Self) -> bool {
1370		let eq = self.commitment_number == o.commitment_number &&
1371			self.to_broadcaster_value_sat == o.to_broadcaster_value_sat &&
1372			self.to_countersignatory_value_sat == o.to_countersignatory_value_sat &&
1373			self.feerate_per_kw == o.feerate_per_kw &&
1374			self.htlcs == o.htlcs &&
1375			self.channel_type_features == o.channel_type_features &&
1376			self.keys == o.keys;
1377		if eq {
1378			debug_assert_eq!(self.built.transaction, o.built.transaction);
1379			debug_assert_eq!(self.built.txid, o.built.txid);
1380		}
1381		eq
1382	}
1383}
1384
1385impl Writeable for CommitmentTransaction {
1386	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1387		let legacy_deserialization_prevention_marker = legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
1388		write_tlv_fields!(writer, {
1389			(0, self.commitment_number, required),
1390			(1, self.to_broadcaster_delay, option),
1391			(2, self.to_broadcaster_value_sat, required),
1392			(4, self.to_countersignatory_value_sat, required),
1393			(6, self.feerate_per_kw, required),
1394			(8, self.keys, required),
1395			(10, self.built, required),
1396			(12, self.htlcs, required_vec),
1397			(14, legacy_deserialization_prevention_marker, option),
1398			(15, self.channel_type_features, required),
1399		});
1400		Ok(())
1401	}
1402}
1403
1404impl Readable for CommitmentTransaction {
1405	fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1406		_init_and_read_len_prefixed_tlv_fields!(reader, {
1407			(0, commitment_number, required),
1408			(1, to_broadcaster_delay, option),
1409			(2, to_broadcaster_value_sat, required),
1410			(4, to_countersignatory_value_sat, required),
1411			(6, feerate_per_kw, required),
1412			(8, keys, required),
1413			(10, built, required),
1414			(12, htlcs, required_vec),
1415			(14, _legacy_deserialization_prevention_marker, (option, explicit_type: ())),
1416			(15, channel_type_features, option),
1417		});
1418
1419		let mut additional_features = ChannelTypeFeatures::empty();
1420		additional_features.set_anchors_nonzero_fee_htlc_tx_required();
1421		chain::package::verify_channel_type_features(&channel_type_features, Some(&additional_features))?;
1422
1423		Ok(Self {
1424			commitment_number: commitment_number.0.unwrap(),
1425			to_broadcaster_value_sat: to_broadcaster_value_sat.0.unwrap(),
1426			to_countersignatory_value_sat: to_countersignatory_value_sat.0.unwrap(),
1427			to_broadcaster_delay,
1428			feerate_per_kw: feerate_per_kw.0.unwrap(),
1429			keys: keys.0.unwrap(),
1430			built: built.0.unwrap(),
1431			htlcs,
1432			channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
1433		})
1434	}
1435}
1436
1437impl CommitmentTransaction {
1438	/// Construct an object of the class while assigning transaction output indices to HTLCs.
1439	///
1440	/// Populates HTLCOutputInCommitment.transaction_output_index in htlcs_with_aux.
1441	///
1442	/// The generic T allows the caller to match the HTLC output index with auxiliary data.
1443	/// This auxiliary data is not stored in this object.
1444	///
1445	/// Only include HTLCs that are above the dust limit for the channel.
1446	///
1447	/// This is not exported to bindings users due to the generic though we likely should expose a version without
1448	pub fn new_with_auxiliary_htlc_data<T>(commitment_number: u64, to_broadcaster_value_sat: u64, to_countersignatory_value_sat: u64, broadcaster_funding_key: PublicKey, countersignatory_funding_key: PublicKey, keys: TxCreationKeys, feerate_per_kw: u32, htlcs_with_aux: &mut Vec<(HTLCOutputInCommitment, T)>, channel_parameters: &DirectedChannelTransactionParameters) -> CommitmentTransaction {
1449		let to_broadcaster_value_sat = Amount::from_sat(to_broadcaster_value_sat);
1450		let to_countersignatory_value_sat = Amount::from_sat(to_countersignatory_value_sat);
1451
1452		// Sort outputs and populate output indices while keeping track of the auxiliary data
1453		let (outputs, htlcs) = Self::internal_build_outputs(&keys, to_broadcaster_value_sat, to_countersignatory_value_sat, htlcs_with_aux, channel_parameters, &broadcaster_funding_key, &countersignatory_funding_key).unwrap();
1454
1455		let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(commitment_number, channel_parameters);
1456		let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1457		let txid = transaction.compute_txid();
1458		CommitmentTransaction {
1459			commitment_number,
1460			to_broadcaster_value_sat,
1461			to_countersignatory_value_sat,
1462			to_broadcaster_delay: Some(channel_parameters.contest_delay()),
1463			feerate_per_kw,
1464			htlcs,
1465			channel_type_features: channel_parameters.channel_type_features().clone(),
1466			keys,
1467			built: BuiltCommitmentTransaction {
1468				transaction,
1469				txid
1470			},
1471		}
1472	}
1473
1474	/// Use non-zero fee anchors
1475	///
1476	/// This is not exported to bindings users due to move, and also not likely to be useful for binding users
1477	pub fn with_non_zero_fee_anchors(mut self) -> Self {
1478		self.channel_type_features.set_anchors_nonzero_fee_htlc_tx_required();
1479		self
1480	}
1481
1482	fn internal_rebuild_transaction(&self, keys: &TxCreationKeys, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<BuiltCommitmentTransaction, ()> {
1483		let (obscured_commitment_transaction_number, txins) = Self::internal_build_inputs(self.commitment_number, channel_parameters);
1484
1485		let mut htlcs_with_aux = self.htlcs.iter().map(|h| (h.clone(), ())).collect();
1486		let (outputs, _) = Self::internal_build_outputs(keys, self.to_broadcaster_value_sat, self.to_countersignatory_value_sat, &mut htlcs_with_aux, channel_parameters, broadcaster_funding_key, countersignatory_funding_key)?;
1487
1488		let transaction = Self::make_transaction(obscured_commitment_transaction_number, txins, outputs);
1489		let txid = transaction.compute_txid();
1490		let built_transaction = BuiltCommitmentTransaction {
1491			transaction,
1492			txid
1493		};
1494		Ok(built_transaction)
1495	}
1496
1497	fn make_transaction(obscured_commitment_transaction_number: u64, txins: Vec<TxIn>, outputs: Vec<TxOut>) -> Transaction {
1498		Transaction {
1499			version: Version::TWO,
1500			lock_time: LockTime::from_consensus(((0x20 as u32) << 8 * 3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32)),
1501			input: txins,
1502			output: outputs,
1503		}
1504	}
1505
1506	// This is used in two cases:
1507	// - initial sorting of outputs / HTLCs in the constructor, in which case T is auxiliary data the
1508	//   caller needs to have sorted together with the HTLCs so it can keep track of the output index
1509	// - building of a bitcoin transaction during a verify() call, in which case T is just ()
1510	fn internal_build_outputs<T>(keys: &TxCreationKeys, to_broadcaster_value_sat: Amount, to_countersignatory_value_sat: Amount, htlcs_with_aux: &mut Vec<(HTLCOutputInCommitment, T)>, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_funding_key: &PublicKey, countersignatory_funding_key: &PublicKey) -> Result<(Vec<TxOut>, Vec<HTLCOutputInCommitment>), ()> {
1511		let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1512		let contest_delay = channel_parameters.contest_delay();
1513
1514		let mut txouts: Vec<(TxOut, Option<&mut HTLCOutputInCommitment>)> = Vec::new();
1515
1516		if to_countersignatory_value_sat > Amount::ZERO {
1517			let script = if channel_parameters.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
1518				get_to_countersignatory_with_anchors_redeemscript(&countersignatory_pubkeys.payment_point).to_p2wsh()
1519			} else {
1520				ScriptBuf::new_p2wpkh(&Hash160::hash(&countersignatory_pubkeys.payment_point.serialize()).into())
1521			};
1522			txouts.push((
1523				TxOut {
1524					script_pubkey: script.clone(),
1525					value: to_countersignatory_value_sat,
1526				},
1527				None,
1528			))
1529		}
1530
1531		if to_broadcaster_value_sat > Amount::ZERO {
1532			let redeem_script = get_revokeable_redeemscript(
1533				&keys.revocation_key,
1534				contest_delay,
1535				&keys.broadcaster_delayed_payment_key,
1536			);
1537			txouts.push((
1538				TxOut {
1539					script_pubkey: redeem_script.to_p2wsh(),
1540					value: to_broadcaster_value_sat,
1541				},
1542				None,
1543			));
1544		}
1545
1546		if channel_parameters.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
1547			if to_broadcaster_value_sat > Amount::ZERO || !htlcs_with_aux.is_empty() {
1548				let anchor_script = get_anchor_redeemscript(broadcaster_funding_key);
1549				txouts.push((
1550					TxOut {
1551						script_pubkey: anchor_script.to_p2wsh(),
1552						value: Amount::from_sat(ANCHOR_OUTPUT_VALUE_SATOSHI),
1553					},
1554					None,
1555				));
1556			}
1557
1558			if to_countersignatory_value_sat > Amount::ZERO || !htlcs_with_aux.is_empty() {
1559				let anchor_script = get_anchor_redeemscript(countersignatory_funding_key);
1560				txouts.push((
1561					TxOut {
1562						script_pubkey: anchor_script.to_p2wsh(),
1563						value: Amount::from_sat(ANCHOR_OUTPUT_VALUE_SATOSHI),
1564					},
1565					None,
1566				));
1567			}
1568		}
1569
1570		let mut htlcs = Vec::with_capacity(htlcs_with_aux.len());
1571		for (htlc, _) in htlcs_with_aux {
1572			let script = get_htlc_redeemscript(&htlc, &channel_parameters.channel_type_features(), &keys);
1573			let txout = TxOut {
1574				script_pubkey: script.to_p2wsh(),
1575				value: htlc.to_bitcoin_amount(),
1576			};
1577			txouts.push((txout, Some(htlc)));
1578		}
1579
1580		// Sort output in BIP-69 order (amount, scriptPubkey).  Tie-breaks based on HTLC
1581		// CLTV expiration height.
1582		sort_outputs(&mut txouts, |a, b| {
1583			if let &Some(ref a_htlcout) = a {
1584				if let &Some(ref b_htlcout) = b {
1585					a_htlcout.cltv_expiry.cmp(&b_htlcout.cltv_expiry)
1586						// Note that due to hash collisions, we have to have a fallback comparison
1587						// here for fuzzing mode (otherwise at least chanmon_fail_consistency
1588						// may fail)!
1589						.then(a_htlcout.payment_hash.0.cmp(&b_htlcout.payment_hash.0))
1590				// For non-HTLC outputs, if they're copying our SPK we don't really care if we
1591				// close the channel due to mismatches - they're doing something dumb:
1592				} else { cmp::Ordering::Equal }
1593			} else { cmp::Ordering::Equal }
1594		});
1595
1596		let mut outputs = Vec::with_capacity(txouts.len());
1597		for (idx, out) in txouts.drain(..).enumerate() {
1598			if let Some(htlc) = out.1 {
1599				htlc.transaction_output_index = Some(idx as u32);
1600				htlcs.push(htlc.clone());
1601			}
1602			outputs.push(out.0);
1603		}
1604		Ok((outputs, htlcs))
1605	}
1606
1607	fn internal_build_inputs(commitment_number: u64, channel_parameters: &DirectedChannelTransactionParameters) -> (u64, Vec<TxIn>) {
1608		let broadcaster_pubkeys = channel_parameters.broadcaster_pubkeys();
1609		let countersignatory_pubkeys = channel_parameters.countersignatory_pubkeys();
1610		let commitment_transaction_number_obscure_factor = get_commitment_transaction_number_obscure_factor(
1611			&broadcaster_pubkeys.payment_point,
1612			&countersignatory_pubkeys.payment_point,
1613			channel_parameters.is_outbound(),
1614		);
1615
1616		let obscured_commitment_transaction_number =
1617			commitment_transaction_number_obscure_factor ^ (INITIAL_COMMITMENT_NUMBER - commitment_number);
1618
1619		let txins = {
1620			let ins: Vec<TxIn> = vec![TxIn {
1621				previous_output: channel_parameters.funding_outpoint(),
1622				script_sig: ScriptBuf::new(),
1623				sequence: Sequence(((0x80 as u32) << 8 * 3)
1624					| ((obscured_commitment_transaction_number >> 3 * 8) as u32)),
1625				witness: Witness::new(),
1626			}];
1627			ins
1628		};
1629		(obscured_commitment_transaction_number, txins)
1630	}
1631
1632	/// The backwards-counting commitment number
1633	pub fn commitment_number(&self) -> u64 {
1634		self.commitment_number
1635	}
1636
1637	/// The per commitment point used by the broadcaster.
1638	pub fn per_commitment_point(&self) -> PublicKey {
1639		self.keys.per_commitment_point
1640	}
1641
1642	/// The value to be sent to the broadcaster
1643	pub fn to_broadcaster_value_sat(&self) -> u64 {
1644		self.to_broadcaster_value_sat.to_sat()
1645	}
1646
1647	/// The value to be sent to the counterparty
1648	pub fn to_countersignatory_value_sat(&self) -> u64 {
1649		self.to_countersignatory_value_sat.to_sat()
1650	}
1651
1652	/// The feerate paid per 1000-weight-unit in this commitment transaction.
1653	pub fn feerate_per_kw(&self) -> u32 {
1654		self.feerate_per_kw
1655	}
1656
1657	/// The non-dust HTLCs (direction, amt, height expiration, hash, transaction output index)
1658	/// which were included in this commitment transaction in output order.
1659	/// The transaction index is always populated.
1660	///
1661	/// This is not exported to bindings users as we cannot currently convert Vec references to/from C, though we should
1662	/// expose a less effecient version which creates a Vec of references in the future.
1663	pub fn htlcs(&self) -> &Vec<HTLCOutputInCommitment> {
1664		&self.htlcs
1665	}
1666
1667	/// Trust our pre-built transaction and derived transaction creation public keys.
1668	///
1669	/// Applies a wrapper which allows access to these fields.
1670	///
1671	/// This should only be used if you fully trust the builder of this object.  It should not
1672	/// be used by an external signer - instead use the verify function.
1673	pub fn trust(&self) -> TrustedCommitmentTransaction {
1674		TrustedCommitmentTransaction { inner: self }
1675	}
1676
1677	/// Verify our pre-built transaction and derived transaction creation public keys.
1678	///
1679	/// Applies a wrapper which allows access to these fields.
1680	///
1681	/// An external validating signer must call this method before signing
1682	/// or using the built transaction.
1683	pub fn verify<T: secp256k1::Signing + secp256k1::Verification>(&self, channel_parameters: &DirectedChannelTransactionParameters, broadcaster_keys: &ChannelPublicKeys, countersignatory_keys: &ChannelPublicKeys, secp_ctx: &Secp256k1<T>) -> Result<TrustedCommitmentTransaction, ()> {
1684		// This is the only field of the key cache that we trust
1685		let per_commitment_point = self.keys.per_commitment_point;
1686		let keys = TxCreationKeys::from_channel_static_keys(&per_commitment_point, broadcaster_keys, countersignatory_keys, secp_ctx);
1687		if keys != self.keys {
1688			return Err(());
1689		}
1690		let tx = self.internal_rebuild_transaction(&keys, channel_parameters, &broadcaster_keys.funding_pubkey, &countersignatory_keys.funding_pubkey)?;
1691		if self.built.transaction != tx.transaction || self.built.txid != tx.txid {
1692			return Err(());
1693		}
1694		Ok(TrustedCommitmentTransaction { inner: self })
1695	}
1696}
1697
1698/// A wrapper on CommitmentTransaction indicating that the derived fields (the built bitcoin
1699/// transaction and the transaction creation keys) are trusted.
1700///
1701/// See trust() and verify() functions on CommitmentTransaction.
1702///
1703/// This structure implements Deref.
1704pub struct TrustedCommitmentTransaction<'a> {
1705	inner: &'a CommitmentTransaction,
1706}
1707
1708impl<'a> Deref for TrustedCommitmentTransaction<'a> {
1709	type Target = CommitmentTransaction;
1710
1711	fn deref(&self) -> &Self::Target { self.inner }
1712}
1713
1714impl<'a> TrustedCommitmentTransaction<'a> {
1715	/// The transaction ID of the built Bitcoin transaction
1716	pub fn txid(&self) -> Txid {
1717		self.inner.built.txid
1718	}
1719
1720	/// The pre-built Bitcoin commitment transaction
1721	pub fn built_transaction(&self) -> &'a BuiltCommitmentTransaction {
1722		&self.inner.built
1723	}
1724
1725	/// The pre-calculated transaction creation public keys.
1726	pub fn keys(&self) -> &'a TxCreationKeys {
1727		&self.inner.keys
1728	}
1729
1730	/// Should anchors be used.
1731	pub fn channel_type_features(&self) -> &'a ChannelTypeFeatures {
1732		&self.inner.channel_type_features
1733	}
1734
1735	/// Get a signature for each HTLC which was included in the commitment transaction (ie for
1736	/// which HTLCOutputInCommitment::transaction_output_index.is_some()).
1737	///
1738	/// The returned Vec has one entry for each HTLC, and in the same order.
1739	///
1740	/// This function is only valid in the holder commitment context, it always uses EcdsaSighashType::All.
1741	pub fn get_htlc_sigs<T: secp256k1::Signing, ES: Deref>(
1742		&self, htlc_base_key: &SecretKey, channel_parameters: &DirectedChannelTransactionParameters,
1743		entropy_source: &ES, secp_ctx: &Secp256k1<T>,
1744	) -> Result<Vec<Signature>, ()> where ES::Target: EntropySource {
1745		let inner = self.inner;
1746		let keys = &inner.keys;
1747		let txid = inner.built.txid;
1748		let mut ret = Vec::with_capacity(inner.htlcs.len());
1749		let holder_htlc_key = derive_private_key(secp_ctx, &inner.keys.per_commitment_point, htlc_base_key);
1750
1751		for this_htlc in inner.htlcs.iter() {
1752			assert!(this_htlc.transaction_output_index.is_some());
1753			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);
1754
1755			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);
1756
1757			let sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).p2wsh_signature_hash(0, &htlc_redeemscript, this_htlc.to_bitcoin_amount(), EcdsaSighashType::All).unwrap()[..]);
1758			ret.push(sign_with_aux_rand(secp_ctx, &sighash, &holder_htlc_key, entropy_source));
1759		}
1760		Ok(ret)
1761	}
1762
1763	/// Builds the second-level holder HTLC transaction for the HTLC with index `htlc_index`.
1764	pub(crate) fn build_unsigned_htlc_tx(
1765		&self, channel_parameters: &DirectedChannelTransactionParameters, htlc_index: usize,
1766		preimage: &Option<PaymentPreimage>,
1767	) -> Transaction {
1768		let keys = &self.inner.keys;
1769		let this_htlc = &self.inner.htlcs[htlc_index];
1770		assert!(this_htlc.transaction_output_index.is_some());
1771		// if we don't have preimage for an HTLC-Success, we can't generate an HTLC transaction.
1772		if !this_htlc.offered && preimage.is_none() { unreachable!(); }
1773		// Further, we should never be provided the preimage for an HTLC-Timeout transaction.
1774		if  this_htlc.offered && preimage.is_some() { unreachable!(); }
1775
1776		build_htlc_transaction(
1777			&self.inner.built.txid, self.inner.feerate_per_kw, channel_parameters.contest_delay(), &this_htlc,
1778			&self.channel_type_features, &keys.broadcaster_delayed_payment_key, &keys.revocation_key
1779		)
1780	}
1781
1782
1783	/// Builds the witness required to spend the input for the HTLC with index `htlc_index` in a
1784	/// second-level holder HTLC transaction.
1785	pub(crate) fn build_htlc_input_witness(
1786		&self, htlc_index: usize, counterparty_signature: &Signature, signature: &Signature,
1787		preimage: &Option<PaymentPreimage>
1788	) -> Witness {
1789		let keys = &self.inner.keys;
1790		let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(
1791			&self.inner.htlcs[htlc_index], &self.channel_type_features, &keys.broadcaster_htlc_key,
1792			&keys.countersignatory_htlc_key, &keys.revocation_key
1793		);
1794		build_htlc_input_witness(
1795			signature, counterparty_signature, preimage, &htlc_redeemscript, &self.channel_type_features,
1796		)
1797	}
1798
1799	/// Returns the index of the revokeable output, i.e. the `to_local` output sending funds to
1800	/// the broadcaster, in the built transaction, if any exists.
1801	///
1802	/// There are two cases where this may return `None`:
1803	/// - The balance of the revokeable output is below the dust limit (only found on commitments
1804	/// early in the channel's lifetime, i.e. before the channel reserve is met).
1805	/// - This commitment was created before LDK 0.0.117. In this case, the
1806	/// commitment transaction previously didn't contain enough information to locate the
1807	/// revokeable output.
1808	pub fn revokeable_output_index(&self) -> Option<usize> {
1809		let revokeable_redeemscript = get_revokeable_redeemscript(
1810			&self.keys.revocation_key,
1811			self.to_broadcaster_delay?,
1812			&self.keys.broadcaster_delayed_payment_key,
1813		);
1814		let revokeable_p2wsh = revokeable_redeemscript.to_p2wsh();
1815		let outputs = &self.inner.built.transaction.output;
1816		outputs.iter().enumerate()
1817			.find(|(_, out)| out.script_pubkey == revokeable_p2wsh)
1818			.map(|(idx, _)| idx)
1819	}
1820
1821	/// Helper method to build an unsigned justice transaction spending the revokeable
1822	/// `to_local` output to a destination script. Fee estimation accounts for the expected
1823	/// revocation witness data that will be added when signed.
1824	///
1825	/// This method will error if the given fee rate results in a fee greater than the value
1826	/// of the output being spent, or if there exists no revokeable `to_local` output on this
1827	/// commitment transaction. See [`Self::revokeable_output_index`] for more details.
1828	///
1829	/// The built transaction will allow fee bumping with RBF, and this method takes
1830	/// `feerate_per_kw` as an input such that multiple copies of a justice transaction at different
1831	/// fee rates may be built.
1832	pub fn build_to_local_justice_tx(&self, feerate_per_kw: u64, destination_script: ScriptBuf)
1833	-> Result<Transaction, ()> {
1834		let output_idx = self.revokeable_output_index().ok_or(())?;
1835		let input = vec![TxIn {
1836			previous_output: OutPoint {
1837				txid: self.trust().txid(),
1838				vout: output_idx as u32,
1839			},
1840			script_sig: ScriptBuf::new(),
1841			sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
1842			witness: Witness::new(),
1843		}];
1844		let value = self.inner.built.transaction.output[output_idx].value;
1845		let output = vec![TxOut {
1846			script_pubkey: destination_script,
1847			value,
1848		}];
1849		let mut justice_tx = Transaction {
1850			version: Version::TWO,
1851			lock_time: LockTime::ZERO,
1852			input,
1853			output,
1854		};
1855		let weight = justice_tx.weight().to_wu() + WEIGHT_REVOKED_OUTPUT;
1856		let fee = Amount::from_sat(fee_for_weight(feerate_per_kw as u32, weight));
1857		justice_tx.output[0].value = value.checked_sub(fee).ok_or(())?;
1858		Ok(justice_tx)
1859	}
1860
1861}
1862
1863/// Commitment transaction numbers which appear in the transactions themselves are XOR'd with a
1864/// shared secret first. This prevents on-chain observers from discovering how many commitment
1865/// transactions occurred in a channel before it was closed.
1866///
1867/// This function gets the shared secret from relevant channel public keys and can be used to
1868/// "decrypt" the commitment transaction number given a commitment transaction on-chain.
1869pub fn get_commitment_transaction_number_obscure_factor(
1870	broadcaster_payment_basepoint: &PublicKey,
1871	countersignatory_payment_basepoint: &PublicKey,
1872	outbound_from_broadcaster: bool,
1873) -> u64 {
1874	let mut sha = Sha256::engine();
1875
1876	if outbound_from_broadcaster {
1877		sha.input(&broadcaster_payment_basepoint.serialize());
1878		sha.input(&countersignatory_payment_basepoint.serialize());
1879	} else {
1880		sha.input(&countersignatory_payment_basepoint.serialize());
1881		sha.input(&broadcaster_payment_basepoint.serialize());
1882	}
1883	let res = Sha256::from_engine(sha).to_byte_array();
1884
1885	((res[26] as u64) << 5 * 8)
1886		| ((res[27] as u64) << 4 * 8)
1887		| ((res[28] as u64) << 3 * 8)
1888		| ((res[29] as u64) << 2 * 8)
1889		| ((res[30] as u64) << 1 * 8)
1890		| ((res[31] as u64) << 0 * 8)
1891}
1892
1893#[cfg(test)]
1894mod tests {
1895	use super::{CounterpartyCommitmentSecrets, ChannelPublicKeys};
1896	use crate::chain;
1897	use crate::ln::chan_utils::{get_htlc_redeemscript, get_to_countersignatory_with_anchors_redeemscript, CommitmentTransaction, TxCreationKeys, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, HTLCOutputInCommitment};
1898	use bitcoin::secp256k1::{PublicKey, SecretKey, Secp256k1};
1899	use crate::util::test_utils;
1900	use crate::sign::{ChannelSigner, SignerProvider};
1901	use bitcoin::{Network, Txid, ScriptBuf, CompressedPublicKey};
1902	use bitcoin::hashes::Hash;
1903	use bitcoin::hex::FromHex;
1904	use crate::types::payment::PaymentHash;
1905	use bitcoin::PublicKey as BitcoinPublicKey;
1906	use crate::types::features::ChannelTypeFeatures;
1907
1908	#[allow(unused_imports)]
1909	use crate::prelude::*;
1910
1911	struct TestCommitmentTxBuilder {
1912		commitment_number: u64,
1913		holder_funding_pubkey: PublicKey,
1914		counterparty_funding_pubkey: PublicKey,
1915		keys: TxCreationKeys,
1916		feerate_per_kw: u32,
1917		htlcs_with_aux: Vec<(HTLCOutputInCommitment, ())>,
1918		channel_parameters: ChannelTransactionParameters,
1919		counterparty_pubkeys: ChannelPublicKeys,
1920	}
1921
1922	impl TestCommitmentTxBuilder {
1923		fn new() -> Self {
1924			let secp_ctx = Secp256k1::new();
1925			let seed = [42; 32];
1926			let network = Network::Testnet;
1927			let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
1928			let signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(false, 1_000_000, 0));
1929			let counterparty_signer = keys_provider.derive_channel_signer(3000, keys_provider.generate_channel_keys_id(true, 1_000_000, 1));
1930			let delayed_payment_base = &signer.pubkeys().delayed_payment_basepoint;
1931			let per_commitment_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
1932			let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
1933			let htlc_basepoint = &signer.pubkeys().htlc_basepoint;
1934			let holder_pubkeys = signer.pubkeys();
1935			let counterparty_pubkeys = counterparty_signer.pubkeys().clone();
1936			let keys = TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, delayed_payment_base, htlc_basepoint, &counterparty_pubkeys.revocation_basepoint, &counterparty_pubkeys.htlc_basepoint);
1937			let channel_parameters = ChannelTransactionParameters {
1938				holder_pubkeys: holder_pubkeys.clone(),
1939				holder_selected_contest_delay: 0,
1940				is_outbound_from_holder: false,
1941				counterparty_parameters: Some(CounterpartyChannelTransactionParameters { pubkeys: counterparty_pubkeys.clone(), selected_contest_delay: 0 }),
1942				funding_outpoint: Some(chain::transaction::OutPoint { txid: Txid::all_zeros(), index: 0 }),
1943				channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
1944			};
1945			let htlcs_with_aux = Vec::new();
1946
1947			Self {
1948				commitment_number: 0,
1949				holder_funding_pubkey: holder_pubkeys.funding_pubkey,
1950				counterparty_funding_pubkey: counterparty_pubkeys.funding_pubkey,
1951				keys,
1952				feerate_per_kw: 1,
1953				htlcs_with_aux,
1954				channel_parameters,
1955				counterparty_pubkeys,
1956			}
1957		}
1958
1959		fn build(&mut self, to_broadcaster_sats: u64, to_countersignatory_sats: u64) -> CommitmentTransaction {
1960			CommitmentTransaction::new_with_auxiliary_htlc_data(
1961				self.commitment_number, to_broadcaster_sats, to_countersignatory_sats,
1962				self.holder_funding_pubkey.clone(),
1963				self.counterparty_funding_pubkey.clone(),
1964				self.keys.clone(), self.feerate_per_kw,
1965				&mut self.htlcs_with_aux, &self.channel_parameters.as_holder_broadcastable()
1966			)
1967		}
1968	}
1969
1970	#[test]
1971	fn test_anchors() {
1972		let mut builder = TestCommitmentTxBuilder::new();
1973
1974		// Generate broadcaster and counterparty outputs
1975		let tx = builder.build(1000, 2000);
1976		assert_eq!(tx.built.transaction.output.len(), 2);
1977		assert_eq!(tx.built.transaction.output[1].script_pubkey, bitcoin::address::Address::p2wpkh(&CompressedPublicKey(builder.counterparty_pubkeys.payment_point), Network::Testnet).script_pubkey());
1978
1979		// Generate broadcaster and counterparty outputs as well as two anchors
1980		builder.channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
1981		let tx = builder.build(1000, 2000);
1982		assert_eq!(tx.built.transaction.output.len(), 4);
1983		assert_eq!(tx.built.transaction.output[3].script_pubkey, get_to_countersignatory_with_anchors_redeemscript(&builder.counterparty_pubkeys.payment_point).to_p2wsh());
1984
1985		// Generate broadcaster output and anchor
1986		let tx = builder.build(3000, 0);
1987		assert_eq!(tx.built.transaction.output.len(), 2);
1988
1989		// Generate counterparty output and anchor
1990		let tx = builder.build(0, 3000);
1991		assert_eq!(tx.built.transaction.output.len(), 2);
1992
1993		let received_htlc = HTLCOutputInCommitment {
1994			offered: false,
1995			amount_msat: 400000,
1996			cltv_expiry: 100,
1997			payment_hash: PaymentHash([42; 32]),
1998			transaction_output_index: None,
1999		};
2000
2001		let offered_htlc = HTLCOutputInCommitment {
2002			offered: true,
2003			amount_msat: 600000,
2004			cltv_expiry: 100,
2005			payment_hash: PaymentHash([43; 32]),
2006			transaction_output_index: None,
2007		};
2008
2009		// Generate broadcaster output and received and offered HTLC outputs,  w/o anchors
2010		builder.channel_parameters.channel_type_features = ChannelTypeFeatures::only_static_remote_key();
2011		builder.htlcs_with_aux = vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())];
2012		let tx = builder.build(3000, 0);
2013		let keys = &builder.keys.clone();
2014		assert_eq!(tx.built.transaction.output.len(), 3);
2015		assert_eq!(tx.built.transaction.output[0].script_pubkey, get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_p2wsh());
2016		assert_eq!(tx.built.transaction.output[1].script_pubkey, get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_p2wsh());
2017		assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_p2wsh().to_hex_string(),
2018				   "0020e43a7c068553003fe68fcae424fb7b28ec5ce48cd8b6744b3945631389bad2fb");
2019		assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::only_static_remote_key(), &keys).to_p2wsh().to_hex_string(),
2020				   "0020215d61bba56b19e9eadb6107f5a85d7f99c40f65992443f69229c290165bc00d");
2021
2022		// Generate broadcaster output and received and offered HTLC outputs,  with anchors
2023		builder.channel_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
2024		builder.htlcs_with_aux = vec![(received_htlc.clone(), ()), (offered_htlc.clone(), ())];
2025		let tx = builder.build(3000, 0);
2026		assert_eq!(tx.built.transaction.output.len(), 5);
2027		assert_eq!(tx.built.transaction.output[2].script_pubkey, get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_p2wsh());
2028		assert_eq!(tx.built.transaction.output[3].script_pubkey, get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_p2wsh());
2029		assert_eq!(get_htlc_redeemscript(&received_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_p2wsh().to_hex_string(),
2030				   "0020b70d0649c72b38756885c7a30908d912a7898dd5d79457a7280b8e9a20f3f2bc");
2031		assert_eq!(get_htlc_redeemscript(&offered_htlc, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), &keys).to_p2wsh().to_hex_string(),
2032				   "002087a3faeb1950a469c0e2db4a79b093a41b9526e5a6fc6ef5cb949bde3be379c7");
2033	}
2034
2035	#[test]
2036	fn test_finding_revokeable_output_index() {
2037		let mut builder = TestCommitmentTxBuilder::new();
2038
2039		// Revokeable output present
2040		let tx = builder.build(1000, 2000);
2041		assert_eq!(tx.built.transaction.output.len(), 2);
2042		assert_eq!(tx.trust().revokeable_output_index(), Some(0));
2043
2044		// Revokeable output present (but to_broadcaster_delay missing)
2045		let tx = CommitmentTransaction { to_broadcaster_delay: None, ..tx };
2046		assert_eq!(tx.built.transaction.output.len(), 2);
2047		assert_eq!(tx.trust().revokeable_output_index(), None);
2048
2049		// Revokeable output not present (our balance is dust)
2050		let tx = builder.build(0, 2000);
2051		assert_eq!(tx.built.transaction.output.len(), 1);
2052		assert_eq!(tx.trust().revokeable_output_index(), None);
2053	}
2054
2055	#[test]
2056	fn test_building_to_local_justice_tx() {
2057		let mut builder = TestCommitmentTxBuilder::new();
2058
2059		// Revokeable output not present (our balance is dust)
2060		let tx = builder.build(0, 2000);
2061		assert_eq!(tx.built.transaction.output.len(), 1);
2062		assert!(tx.trust().build_to_local_justice_tx(253, ScriptBuf::new()).is_err());
2063
2064		// Revokeable output present
2065		let tx = builder.build(1000, 2000);
2066		assert_eq!(tx.built.transaction.output.len(), 2);
2067
2068		// Too high feerate
2069		assert!(tx.trust().build_to_local_justice_tx(100_000, ScriptBuf::new()).is_err());
2070
2071		// Generate a random public key for destination script
2072		let secret_key = SecretKey::from_slice(
2073			&<Vec<u8>>::from_hex("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100")
2074			.unwrap()[..]).unwrap();
2075		let pubkey_hash = BitcoinPublicKey::new(
2076			PublicKey::from_secret_key(&Secp256k1::new(), &secret_key)).wpubkey_hash().unwrap();
2077		let destination_script = ScriptBuf::new_p2wpkh(&pubkey_hash);
2078
2079		let justice_tx = tx.trust().build_to_local_justice_tx(253, destination_script.clone()).unwrap();
2080		assert_eq!(justice_tx.input.len(), 1);
2081		assert_eq!(justice_tx.input[0].previous_output.txid, tx.built.transaction.compute_txid());
2082		assert_eq!(justice_tx.input[0].previous_output.vout, tx.trust().revokeable_output_index().unwrap() as u32);
2083		assert!(justice_tx.input[0].sequence.is_rbf());
2084
2085		assert_eq!(justice_tx.output.len(), 1);
2086		assert!(justice_tx.output[0].value.to_sat() < 1000);
2087		assert_eq!(justice_tx.output[0].script_pubkey, destination_script);
2088	}
2089
2090	#[test]
2091	fn test_per_commitment_storage() {
2092		// Test vectors from BOLT 3:
2093		let mut secrets: Vec<[u8; 32]> = Vec::new();
2094		let mut monitor;
2095
2096		macro_rules! test_secrets {
2097			() => {
2098				let mut idx = 281474976710655;
2099				for secret in secrets.iter() {
2100					assert_eq!(monitor.get_secret(idx).unwrap(), *secret);
2101					idx -= 1;
2102				}
2103				assert_eq!(monitor.get_min_seen_secret(), idx + 1);
2104				assert!(monitor.get_secret(idx).is_none());
2105			};
2106		}
2107
2108		{
2109			// insert_secret correct sequence
2110			monitor = CounterpartyCommitmentSecrets::new();
2111			secrets.clear();
2112
2113			secrets.push([0; 32]);
2114			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2115			monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2116			test_secrets!();
2117
2118			secrets.push([0; 32]);
2119			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2120			monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2121			test_secrets!();
2122
2123			secrets.push([0; 32]);
2124			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2125			monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2126			test_secrets!();
2127
2128			secrets.push([0; 32]);
2129			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2130			monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2131			test_secrets!();
2132
2133			secrets.push([0; 32]);
2134			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2135			monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2136			test_secrets!();
2137
2138			secrets.push([0; 32]);
2139			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2140			monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2141			test_secrets!();
2142
2143			secrets.push([0; 32]);
2144			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2145			monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2146			test_secrets!();
2147
2148			secrets.push([0; 32]);
2149			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2150			monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).unwrap();
2151			test_secrets!();
2152		}
2153
2154		{
2155			// insert_secret #1 incorrect
2156			monitor = CounterpartyCommitmentSecrets::new();
2157			secrets.clear();
2158
2159			secrets.push([0; 32]);
2160			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2161			monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2162			test_secrets!();
2163
2164			secrets.push([0; 32]);
2165			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2166			assert!(monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).is_err());
2167		}
2168
2169		{
2170			// insert_secret #2 incorrect (#1 derived from incorrect)
2171			monitor = CounterpartyCommitmentSecrets::new();
2172			secrets.clear();
2173
2174			secrets.push([0; 32]);
2175			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2176			monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2177			test_secrets!();
2178
2179			secrets.push([0; 32]);
2180			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2181			monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2182			test_secrets!();
2183
2184			secrets.push([0; 32]);
2185			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2186			monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2187			test_secrets!();
2188
2189			secrets.push([0; 32]);
2190			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2191			assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
2192		}
2193
2194		{
2195			// insert_secret #3 incorrect
2196			monitor = CounterpartyCommitmentSecrets::new();
2197			secrets.clear();
2198
2199			secrets.push([0; 32]);
2200			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2201			monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2202			test_secrets!();
2203
2204			secrets.push([0; 32]);
2205			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2206			monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2207			test_secrets!();
2208
2209			secrets.push([0; 32]);
2210			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2211			monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2212			test_secrets!();
2213
2214			secrets.push([0; 32]);
2215			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2216			assert!(monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).is_err());
2217		}
2218
2219		{
2220			// insert_secret #4 incorrect (1,2,3 derived from incorrect)
2221			monitor = CounterpartyCommitmentSecrets::new();
2222			secrets.clear();
2223
2224			secrets.push([0; 32]);
2225			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap());
2226			monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2227			test_secrets!();
2228
2229			secrets.push([0; 32]);
2230			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("dddc3a8d14fddf2b68fa8c7fbad2748274937479dd0f8930d5ebb4ab6bd866a3").unwrap());
2231			monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2232			test_secrets!();
2233
2234			secrets.push([0; 32]);
2235			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c51a18b13e8527e579ec56365482c62f180b7d5760b46e9477dae59e87ed423a").unwrap());
2236			monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2237			test_secrets!();
2238
2239			secrets.push([0; 32]);
2240			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("ba65d7b0ef55a3ba300d4e87af29868f394f8f138d78a7011669c79b37b936f4").unwrap());
2241			monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2242			test_secrets!();
2243
2244			secrets.push([0; 32]);
2245			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2246			monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2247			test_secrets!();
2248
2249			secrets.push([0; 32]);
2250			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2251			monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2252			test_secrets!();
2253
2254			secrets.push([0; 32]);
2255			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2256			monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2257			test_secrets!();
2258
2259			secrets.push([0; 32]);
2260			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2261			assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2262		}
2263
2264		{
2265			// insert_secret #5 incorrect
2266			monitor = CounterpartyCommitmentSecrets::new();
2267			secrets.clear();
2268
2269			secrets.push([0; 32]);
2270			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2271			monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2272			test_secrets!();
2273
2274			secrets.push([0; 32]);
2275			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2276			monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2277			test_secrets!();
2278
2279			secrets.push([0; 32]);
2280			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2281			monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2282			test_secrets!();
2283
2284			secrets.push([0; 32]);
2285			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2286			monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2287			test_secrets!();
2288
2289			secrets.push([0; 32]);
2290			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2291			monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2292			test_secrets!();
2293
2294			secrets.push([0; 32]);
2295			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2296			assert!(monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).is_err());
2297		}
2298
2299		{
2300			// insert_secret #6 incorrect (5 derived from incorrect)
2301			monitor = CounterpartyCommitmentSecrets::new();
2302			secrets.clear();
2303
2304			secrets.push([0; 32]);
2305			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2306			monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2307			test_secrets!();
2308
2309			secrets.push([0; 32]);
2310			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2311			monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2312			test_secrets!();
2313
2314			secrets.push([0; 32]);
2315			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2316			monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2317			test_secrets!();
2318
2319			secrets.push([0; 32]);
2320			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2321			monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2322			test_secrets!();
2323
2324			secrets.push([0; 32]);
2325			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("631373ad5f9ef654bb3dade742d09504c567edd24320d2fcd68e3cc47e2ff6a6").unwrap());
2326			monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2327			test_secrets!();
2328
2329			secrets.push([0; 32]);
2330			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("b7e76a83668bde38b373970155c868a653304308f9896692f904a23731224bb1").unwrap());
2331			monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2332			test_secrets!();
2333
2334			secrets.push([0; 32]);
2335			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2336			monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2337			test_secrets!();
2338
2339			secrets.push([0; 32]);
2340			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2341			assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2342		}
2343
2344		{
2345			// insert_secret #7 incorrect
2346			monitor = CounterpartyCommitmentSecrets::new();
2347			secrets.clear();
2348
2349			secrets.push([0; 32]);
2350			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2351			monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2352			test_secrets!();
2353
2354			secrets.push([0; 32]);
2355			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2356			monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2357			test_secrets!();
2358
2359			secrets.push([0; 32]);
2360			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2361			monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2362			test_secrets!();
2363
2364			secrets.push([0; 32]);
2365			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2366			monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2367			test_secrets!();
2368
2369			secrets.push([0; 32]);
2370			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2371			monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2372			test_secrets!();
2373
2374			secrets.push([0; 32]);
2375			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2376			monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2377			test_secrets!();
2378
2379			secrets.push([0; 32]);
2380			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("e7971de736e01da8ed58b94c2fc216cb1dca9e326f3a96e7194fe8ea8af6c0a3").unwrap());
2381			monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2382			test_secrets!();
2383
2384			secrets.push([0; 32]);
2385			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("05cde6323d949933f7f7b78776bcc1ea6d9b31447732e3802e1f7ac44b650e17").unwrap());
2386			assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2387		}
2388
2389		{
2390			// insert_secret #8 incorrect
2391			monitor = CounterpartyCommitmentSecrets::new();
2392			secrets.clear();
2393
2394			secrets.push([0; 32]);
2395			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
2396			monitor.provide_secret(281474976710655, secrets.last().unwrap().clone()).unwrap();
2397			test_secrets!();
2398
2399			secrets.push([0; 32]);
2400			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
2401			monitor.provide_secret(281474976710654, secrets.last().unwrap().clone()).unwrap();
2402			test_secrets!();
2403
2404			secrets.push([0; 32]);
2405			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
2406			monitor.provide_secret(281474976710653, secrets.last().unwrap().clone()).unwrap();
2407			test_secrets!();
2408
2409			secrets.push([0; 32]);
2410			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
2411			monitor.provide_secret(281474976710652, secrets.last().unwrap().clone()).unwrap();
2412			test_secrets!();
2413
2414			secrets.push([0; 32]);
2415			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c65716add7aa98ba7acb236352d665cab17345fe45b55fb879ff80e6bd0c41dd").unwrap());
2416			monitor.provide_secret(281474976710651, secrets.last().unwrap().clone()).unwrap();
2417			test_secrets!();
2418
2419			secrets.push([0; 32]);
2420			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("969660042a28f32d9be17344e09374b379962d03db1574df5a8a5a47e19ce3f2").unwrap());
2421			monitor.provide_secret(281474976710650, secrets.last().unwrap().clone()).unwrap();
2422			test_secrets!();
2423
2424			secrets.push([0; 32]);
2425			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a5a64476122ca0925fb344bdc1854c1c0a59fc614298e50a33e331980a220f32").unwrap());
2426			monitor.provide_secret(281474976710649, secrets.last().unwrap().clone()).unwrap();
2427			test_secrets!();
2428
2429			secrets.push([0; 32]);
2430			secrets.last_mut().unwrap()[0..32].clone_from_slice(&<Vec<u8>>::from_hex("a7efbc61aac46d34f77778bac22c8a20c6a46ca460addc49009bda875ec88fa4").unwrap());
2431			assert!(monitor.provide_secret(281474976710648, secrets.last().unwrap().clone()).is_err());
2432		}
2433	}
2434}