lightning/chain/
channelmonitor.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//! The logic to monitor for on-chain transactions and create the relevant claim responses lives
11//! here.
12//!
13//! ChannelMonitor objects are generated by ChannelManager in response to relevant
14//! messages/actions, and MUST be persisted to disk (and, preferably, remotely) before progress can
15//! be made in responding to certain messages, see [`chain::Watch`] for more.
16//!
17//! Note that ChannelMonitors are an important part of the lightning trust model and a copy of the
18//! latest ChannelMonitor must always be actively monitoring for chain updates (and no out-of-date
19//! ChannelMonitors should do so). Thus, if you're building rust-lightning into an HSM or other
20//! security-domain-separated system design, you should consider having multiple paths for
21//! ChannelMonitors to get out of the HSM and onto monitoring devices.
22
23use bitcoin::amount::Amount;
24use bitcoin::block::Header;
25use bitcoin::script::{Script, ScriptBuf};
26use bitcoin::transaction::{OutPoint as BitcoinOutPoint, Transaction, TxOut};
27
28use bitcoin::hash_types::{BlockHash, Txid};
29use bitcoin::hashes::sha256::Hash as Sha256;
30use bitcoin::hashes::Hash;
31
32use bitcoin::ecdsa::Signature as BitcoinSignature;
33use bitcoin::secp256k1::{self, ecdsa::Signature, PublicKey, Secp256k1, SecretKey};
34
35use crate::chain;
36use crate::chain::chaininterface::{
37	BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator,
38};
39use crate::chain::onchaintx::{ClaimEvent, FeerateStrategy, OnchainTxHandler};
40use crate::chain::package::{
41	CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderFundingOutput,
42	HolderHTLCOutput, PackageSolvingData, PackageTemplate, RevokedHTLCOutput, RevokedOutput,
43};
44use crate::chain::transaction::{OutPoint, TransactionData};
45use crate::chain::Filter;
46use crate::chain::{BestBlock, WatchedOutput};
47use crate::events::bump_transaction::{AnchorDescriptor, BumpTransactionEvent};
48use crate::events::{ClosureReason, Event, EventHandler, PaidBolt12Invoice, ReplayEvent};
49use crate::ln::chan_utils::{
50	self, ChannelTransactionParameters, CommitmentTransaction, CounterpartyCommitmentSecrets,
51	HTLCClaim, HTLCOutputInCommitment, HolderCommitmentTransaction,
52};
53use crate::ln::channel::INITIAL_COMMITMENT_NUMBER;
54use crate::ln::channel_keys::{
55	DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, HtlcKey, RevocationBasepoint,
56	RevocationKey,
57};
58use crate::ln::channelmanager::{HTLCSource, PaymentClaimDetails, SentHTLCId};
59use crate::ln::msgs::DecodeError;
60use crate::ln::types::ChannelId;
61use crate::sign::{
62	ecdsa::EcdsaChannelSigner, ChannelDerivationParameters, DelayedPaymentOutputDescriptor,
63	EntropySource, HTLCDescriptor, SignerProvider, SpendableOutputDescriptor,
64	StaticPaymentOutputDescriptor,
65};
66use crate::types::features::ChannelTypeFeatures;
67use crate::types::payment::{PaymentHash, PaymentPreimage};
68use crate::util::byte_utils;
69use crate::util::logger::{Logger, Record};
70use crate::util::persist::MonitorName;
71use crate::util::ser::{
72	MaybeReadable, Readable, ReadableArgs, RequiredWrapper, UpgradableRequired, Writeable, Writer,
73	U48,
74};
75
76#[allow(unused_imports)]
77use crate::prelude::*;
78
79use crate::io::{self, Error};
80use crate::sync::Mutex;
81use core::ops::Deref;
82use core::{cmp, mem};
83
84/// An update generated by the underlying channel itself which contains some new information the
85/// [`ChannelMonitor`] should be made aware of.
86///
87/// Because this represents only a small number of updates to the underlying state, it is generally
88/// much smaller than a full [`ChannelMonitor`]. However, for large single commitment transaction
89/// updates (e.g. ones during which there are hundreds of HTLCs pending on the commitment
90/// transaction), a single update may reach upwards of 1 MiB in serialized size.
91#[derive(Clone, Debug, PartialEq, Eq)]
92#[must_use]
93pub struct ChannelMonitorUpdate {
94	pub(crate) updates: Vec<ChannelMonitorUpdateStep>,
95	/// The sequence number of this update. Updates *must* be replayed in-order according to this
96	/// sequence number (and updates may panic if they are not). The update_id values are strictly
97	/// increasing and increase by one for each new update, with two exceptions specified below.
98	///
99	/// This sequence number is also used to track up to which points updates which returned
100	/// [`ChannelMonitorUpdateStatus::InProgress`] have been applied to all copies of a given
101	/// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
102	///
103	/// Note that for [`ChannelMonitorUpdate`]s generated on LDK versions prior to 0.1 after the
104	/// channel was closed, this value may be [`u64::MAX`]. In that case, multiple updates may
105	/// appear with the same ID, and all should be replayed.
106	///
107	/// [`ChannelMonitorUpdateStatus::InProgress`]: super::ChannelMonitorUpdateStatus::InProgress
108	pub update_id: u64,
109	/// The channel ID associated with these updates.
110	///
111	/// Will be `None` for `ChannelMonitorUpdate`s constructed on LDK versions prior to 0.0.121 and
112	/// always `Some` otherwise.
113	pub channel_id: Option<ChannelId>,
114}
115
116impl ChannelMonitorUpdate {
117	pub(crate) fn internal_renegotiated_funding_data(
118		&self,
119	) -> impl Iterator<Item = (OutPoint, ScriptBuf)> + '_ {
120		self.updates.iter().filter_map(|update| match update {
121			ChannelMonitorUpdateStep::RenegotiatedFunding { channel_parameters, .. } => {
122				let funding_outpoint = channel_parameters
123					.funding_outpoint
124					.expect("Renegotiated funding must always have known outpoint");
125				let funding_script = channel_parameters.make_funding_redeemscript().to_p2wsh();
126				Some((funding_outpoint, funding_script))
127			},
128			_ => None,
129		})
130	}
131
132	/// Returns a `Vec` of new (funding outpoint, funding script) to monitor the chain for as a
133	/// result of a renegotiated funding transaction.
134	#[cfg(c_bindings)]
135	pub fn renegotiated_funding_data(&self) -> Vec<(OutPoint, ScriptBuf)> {
136		self.internal_renegotiated_funding_data().collect()
137	}
138
139	/// Returns an iterator of new (funding outpoint, funding script) to monitor the chain for as a
140	/// result of a renegotiated funding transaction.
141	#[cfg(not(c_bindings))]
142	pub fn renegotiated_funding_data(&self) -> impl Iterator<Item = (OutPoint, ScriptBuf)> + '_ {
143		self.internal_renegotiated_funding_data()
144	}
145}
146
147/// LDK prior to 0.1 used this constant as the [`ChannelMonitorUpdate::update_id`] for any
148/// [`ChannelMonitorUpdate`]s which were generated after the channel was closed.
149const LEGACY_CLOSED_CHANNEL_UPDATE_ID: u64 = u64::MAX;
150
151impl Writeable for ChannelMonitorUpdate {
152	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
153		write_ver_prefix!(w, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
154		self.update_id.write(w)?;
155		(self.updates.len() as u64).write(w)?;
156		for update_step in self.updates.iter() {
157			update_step.write(w)?;
158		}
159		write_tlv_fields!(w, {
160			// 1 was previously used to store `counterparty_node_id`
161			(3, self.channel_id, option),
162		});
163		Ok(())
164	}
165}
166impl Readable for ChannelMonitorUpdate {
167	#[rustfmt::skip]
168	fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
169		let _ver = read_ver_prefix!(r, SERIALIZATION_VERSION);
170		let update_id: u64 = Readable::read(r)?;
171		let len: u64 = Readable::read(r)?;
172		let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::<ChannelMonitorUpdateStep>()));
173		for _ in 0..len {
174			if let Some(upd) = MaybeReadable::read(r)? {
175				updates.push(upd);
176			}
177		}
178		let mut channel_id = None;
179		read_tlv_fields!(r, {
180			// 1 was previously used to store `counterparty_node_id`
181			(3, channel_id, option),
182		});
183		Ok(Self { update_id, updates, channel_id })
184	}
185}
186
187/// An event to be processed by the ChannelManager.
188#[derive(Clone, PartialEq, Eq)]
189pub enum MonitorEvent {
190	/// A monitor event containing an HTLCUpdate.
191	HTLCEvent(HTLCUpdate),
192
193	/// Indicates we broadcasted the channel's latest commitment transaction and thus closed the
194	/// channel. Holds information about the channel and why it was closed.
195	HolderForceClosedWithInfo {
196		/// The reason the channel was closed.
197		reason: ClosureReason,
198		/// The funding outpoint of the channel.
199		outpoint: OutPoint,
200		/// The channel ID of the channel.
201		channel_id: ChannelId,
202	},
203
204	/// Indicates we broadcasted the channel's latest commitment transaction and thus closed the
205	/// channel.
206	HolderForceClosed(OutPoint),
207
208	/// Indicates that we've detected a commitment transaction (either holder's or counterparty's)
209	/// be included in a block and should consider the channel closed.
210	CommitmentTxConfirmed(()),
211
212	/// Indicates a [`ChannelMonitor`] update has completed. See
213	/// [`ChannelMonitorUpdateStatus::InProgress`] for more information on how this is used.
214	///
215	/// [`ChannelMonitorUpdateStatus::InProgress`]: super::ChannelMonitorUpdateStatus::InProgress
216	Completed {
217		/// The funding outpoint of the [`ChannelMonitor`] that was updated
218		funding_txo: OutPoint,
219		/// The channel ID of the channel associated with the [`ChannelMonitor`]
220		channel_id: ChannelId,
221		/// The Update ID from [`ChannelMonitorUpdate::update_id`] which was applied or
222		/// [`ChannelMonitor::get_latest_update_id`].
223		///
224		/// Note that this should only be set to a given update's ID if all previous updates for the
225		/// same [`ChannelMonitor`] have been applied and persisted.
226		monitor_update_id: u64,
227	},
228}
229impl_writeable_tlv_based_enum_upgradable_legacy!(MonitorEvent,
230	// Note that Completed is currently never serialized to disk as it is generated only in
231	// ChainMonitor.
232	(0, Completed) => {
233		(0, funding_txo, required),
234		(2, monitor_update_id, required),
235		(4, channel_id, required),
236	},
237	(5, HolderForceClosedWithInfo) => {
238		(0, reason, upgradable_required),
239		(2, outpoint, required),
240		(4, channel_id, required),
241	},
242;
243	(1, CommitmentTxConfirmed),
244	(2, HTLCEvent),
245	(4, HolderForceClosed),
246	// 6 was `UpdateFailed` until LDK 0.0.117
247);
248
249/// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
250/// chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
251/// preimage claim backward will lead to loss of funds.
252#[derive(Clone, PartialEq, Eq)]
253pub struct HTLCUpdate {
254	pub(crate) payment_hash: PaymentHash,
255	pub(crate) payment_preimage: Option<PaymentPreimage>,
256	pub(crate) source: HTLCSource,
257	pub(crate) htlc_value_satoshis: Option<u64>,
258}
259impl_writeable_tlv_based!(HTLCUpdate, {
260	(0, payment_hash, required),
261	(1, htlc_value_satoshis, option),
262	(2, source, required),
263	(4, payment_preimage, option),
264});
265
266/// If an output goes from claimable only by us to claimable by us or our counterparty within this
267/// many blocks, we consider it pinnable for the purposes of aggregating claims in a single
268/// transaction.
269pub(crate) const COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE: u32 = 12;
270
271/// When we go to force-close a channel because an HTLC is expiring, by the time we've gotten the
272/// commitment transaction confirmed, we should ensure that the HTLC(s) expiring are not considered
273/// pinnable, allowing us to aggregate them with other HTLC(s) expiring at the same time.
274const _: () = assert!(MAX_BLOCKS_FOR_CONF > COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE);
275
276/// The upper bound on how many blocks we think it can take for us to get a transaction confirmed.
277pub(crate) const MAX_BLOCKS_FOR_CONF: u32 = 18;
278
279/// If an HTLC expires within this many blocks, force-close the channel to broadcast the
280/// HTLC-Success transaction.
281///
282/// This is two times [`MAX_BLOCKS_FOR_CONF`] as we need to first get the commitment transaction
283/// confirmed, then get an HTLC transaction confirmed.
284pub(crate) const CLTV_CLAIM_BUFFER: u32 = MAX_BLOCKS_FOR_CONF * 2;
285/// Number of blocks by which point we expect our counterparty to have seen new blocks on the
286/// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
287/// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
288/// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
289/// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
290/// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
291/// due to expiration but increase the cost of funds being locked longuer in case of failure.
292/// This delay also cover a low-power peer being slow to process blocks and so being behind us on
293/// accurate block height.
294/// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
295/// with at worst this delay, so we are not only using this value as a mercy for them but also
296/// us as a safeguard to delay with enough time.
297pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
298/// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding
299/// inbound HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us
300/// losing money.
301///
302/// Note that this is a library-wide security assumption. If a reorg deeper than this number of
303/// blocks occurs, counterparties may be able to steal funds or claims made by and balances exposed
304/// by a  [`ChannelMonitor`] may be incorrect.
305// We also use this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
306// It may cause spurious generation of bumped claim txn but that's alright given the outpoint is already
307// solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
308// keep bumping another claim tx to solve the outpoint.
309pub const ANTI_REORG_DELAY: u32 = 6;
310/// Number of blocks we wait before assuming a [`ChannelMonitor`] to be fully resolved and
311/// considering it be safely archived.
312// 4032 blocks are roughly four weeks
313pub const ARCHIVAL_DELAY_BLOCKS: u32 = 4032;
314/// Number of blocks before confirmation at which we fail back an un-relayed HTLC or at which we
315/// refuse to accept a new HTLC.
316///
317/// This is used for a few separate purposes:
318/// 1) if we've received an MPP HTLC to us and it expires within this many blocks and we are
319///    waiting on additional parts (or waiting on the preimage for any HTLC from the user), we will
320///    fail this HTLC,
321/// 2) if we receive an HTLC within this many blocks of its expiry (plus one to avoid a race
322///    condition with the above), we will fail this HTLC without telling the user we received it,
323///
324/// (1) is all about protecting us - we need enough time to update the channel state before we hit
325/// CLTV_CLAIM_BUFFER, at which point we'd go on chain to claim the HTLC with the preimage.
326///
327/// (2) is the same, but with an additional buffer to avoid accepting an HTLC which is immediately
328/// in a race condition between the user connecting a block (which would fail it) and the user
329/// providing us the preimage (which would claim it).
330pub const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS;
331
332// Deprecated, use [`HolderCommitment`] or [`HolderCommitmentTransaction`].
333#[derive(Clone, PartialEq, Eq)]
334struct HolderSignedTx {
335	/// txid of the transaction in tx, just used to make comparison faster
336	txid: Txid,
337	revocation_key: RevocationKey,
338	a_htlc_key: HtlcKey,
339	b_htlc_key: HtlcKey,
340	delayed_payment_key: DelayedPaymentKey,
341	per_commitment_point: PublicKey,
342	htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
343	to_self_value_sat: u64,
344	feerate_per_kw: u32,
345}
346
347// Any changes made here must also reflect in `write_legacy_holder_commitment_data`.
348impl_writeable_tlv_based!(HolderSignedTx, {
349	(0, txid, required),
350	(1, to_self_value_sat, required), // Added in 0.0.100, required in 0.2.
351	(2, revocation_key, required),
352	(4, a_htlc_key, required),
353	(6, b_htlc_key, required),
354	(8, delayed_payment_key, required),
355	(10, per_commitment_point, required),
356	(12, feerate_per_kw, required),
357	(14, htlc_outputs, required_vec)
358});
359
360// Matches the serialization of `HolderSignedTx` for backwards compatibility reasons.
361#[rustfmt::skip]
362fn write_legacy_holder_commitment_data<W: Writer>(
363	writer: &mut W, commitment_tx: &HolderCommitmentTransaction, htlc_data: &CommitmentHTLCData,
364) -> Result<(), io::Error> {
365	let trusted_tx = commitment_tx.trust();
366	let tx_keys = trusted_tx.keys();
367
368	let txid = trusted_tx.txid();
369	let to_self_value_sat = commitment_tx.to_broadcaster_value_sat();
370	let feerate_per_kw = trusted_tx.negotiated_feerate_per_kw();
371	let revocation_key = &tx_keys.revocation_key;
372	let a_htlc_key = &tx_keys.broadcaster_htlc_key;
373	let b_htlc_key = &tx_keys.countersignatory_htlc_key;
374	let delayed_payment_key = &tx_keys.broadcaster_delayed_payment_key;
375	let per_commitment_point = &tx_keys.per_commitment_point;
376
377	let mut nondust_htlcs = commitment_tx.nondust_htlcs().iter()
378		.zip(commitment_tx.counterparty_htlc_sigs.iter());
379	let mut sources = htlc_data.nondust_htlc_sources.iter();
380
381	// Use an iterator to write `htlc_outputs` to avoid allocations.
382	let nondust_htlcs = core::iter::from_fn(move || {
383		let (htlc, counterparty_htlc_sig) = if let Some(nondust_htlc) = nondust_htlcs.next() {
384			nondust_htlc
385		} else {
386			assert!(sources.next().is_none());
387			return None;
388		};
389
390		let mut source = None;
391		if htlc.offered {
392			source = sources.next();
393			if source.is_none() {
394				panic!("Every offered non-dust HTLC should have a corresponding source");
395			}
396		}
397		Some((htlc, Some(counterparty_htlc_sig), source))
398	});
399
400	// Dust HTLCs go last.
401	let dust_htlcs = htlc_data.dust_htlcs.iter()
402		.map(|(htlc, source)| (htlc, None::<&Signature>, source.as_ref()));
403	let htlc_outputs = crate::util::ser::IterableOwned(nondust_htlcs.chain(dust_htlcs));
404
405	write_tlv_fields!(writer, {
406		(0, txid, required),
407		(1, to_self_value_sat, required),
408		(2, revocation_key, required),
409		(4, a_htlc_key, required),
410		(6, b_htlc_key, required),
411		(8, delayed_payment_key, required),
412		(10, per_commitment_point, required),
413		(12, feerate_per_kw, required),
414		(14, htlc_outputs, required),
415	});
416
417	Ok(())
418}
419
420/// We use this to track static counterparty commitment transaction data and to generate any
421/// justice or 2nd-stage preimage/timeout transactions.
422#[derive(Clone, PartialEq, Eq)]
423struct CounterpartyCommitmentParameters {
424	counterparty_delayed_payment_base_key: DelayedPaymentBasepoint,
425	counterparty_htlc_base_key: HtlcBasepoint,
426	on_counterparty_tx_csv: u16,
427}
428
429impl Writeable for CounterpartyCommitmentParameters {
430	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
431		w.write_all(&0u64.to_be_bytes())?;
432		write_tlv_fields!(w, {
433			(0, self.counterparty_delayed_payment_base_key, required),
434			(2, self.counterparty_htlc_base_key, required),
435			(4, self.on_counterparty_tx_csv, required),
436		});
437		Ok(())
438	}
439}
440impl Readable for CounterpartyCommitmentParameters {
441	#[rustfmt::skip]
442	fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
443		let counterparty_commitment_transaction = {
444			// Versions prior to 0.0.100 had some per-HTLC state stored here, which is no longer
445			// used. Read it for compatibility.
446			let per_htlc_len: u64 = Readable::read(r)?;
447			for _ in 0..per_htlc_len {
448				let _txid: Txid = Readable::read(r)?;
449				let htlcs_count: u64 = Readable::read(r)?;
450				for _ in 0..htlcs_count {
451					let _htlc: HTLCOutputInCommitment = Readable::read(r)?;
452				}
453			}
454
455			let mut counterparty_delayed_payment_base_key = RequiredWrapper(None);
456			let mut counterparty_htlc_base_key = RequiredWrapper(None);
457			let mut on_counterparty_tx_csv: u16 = 0;
458			read_tlv_fields!(r, {
459				(0, counterparty_delayed_payment_base_key, required),
460				(2, counterparty_htlc_base_key, required),
461				(4, on_counterparty_tx_csv, required),
462			});
463			CounterpartyCommitmentParameters {
464				counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(),
465				counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(),
466				on_counterparty_tx_csv,
467			}
468		};
469		Ok(counterparty_commitment_transaction)
470	}
471}
472
473/// An entry for an [`OnchainEvent`], stating the block height and hash when the event was
474/// observed, as well as the transaction causing it.
475///
476/// Used to determine when the on-chain event can be considered safe from a chain reorganization.
477#[derive(Clone, PartialEq, Eq)]
478struct OnchainEventEntry {
479	txid: Txid,
480	height: u32,
481	block_hash: Option<BlockHash>, // Added as optional, will be filled in for any entry generated on 0.0.113 or after
482	event: OnchainEvent,
483	transaction: Option<Transaction>, // Added as optional, but always filled in, in LDK 0.0.110
484}
485
486impl OnchainEventEntry {
487	#[rustfmt::skip]
488	fn confirmation_threshold(&self) -> u32 {
489		let mut conf_threshold = self.height + ANTI_REORG_DELAY - 1;
490		match self.event {
491			OnchainEvent::MaturingOutput {
492				descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor)
493			} => {
494				// A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
495				// it's broadcastable when we see the previous block.
496				conf_threshold = cmp::max(conf_threshold, self.height + descriptor.to_self_delay as u32 - 1);
497			},
498			OnchainEvent::FundingSpendConfirmation { on_local_output_csv: Some(csv), .. } |
499			OnchainEvent::HTLCSpendConfirmation { on_to_local_output_csv: Some(csv), .. } => {
500				// A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
501				// it's broadcastable when we see the previous block.
502				conf_threshold = cmp::max(conf_threshold, self.height + csv as u32 - 1);
503			},
504			_ => {},
505		}
506		conf_threshold
507	}
508
509	fn has_reached_confirmation_threshold(&self, best_block: &BestBlock) -> bool {
510		best_block.height >= self.confirmation_threshold()
511	}
512}
513
514/// The (output index, sats value) for the counterparty's output in a commitment transaction.
515///
516/// This was added as an `Option` in 0.0.110.
517type CommitmentTxCounterpartyOutputInfo = Option<(u32, Amount)>;
518
519/// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
520/// once they mature to enough confirmations (ANTI_REORG_DELAY)
521#[derive(Clone, PartialEq, Eq)]
522enum OnchainEvent {
523	/// An outbound HTLC failing after a transaction is confirmed. Used
524	///  * when an outbound HTLC output is spent by us after the HTLC timed out
525	///  * an outbound HTLC which was not present in the commitment transaction which appeared
526	///    on-chain (either because it was not fully committed to or it was dust).
527	/// Note that this is *not* used for preimage claims, as those are passed upstream immediately,
528	/// appearing only as an `HTLCSpendConfirmation`, below.
529	HTLCUpdate {
530		source: HTLCSource,
531		payment_hash: PaymentHash,
532		htlc_value_satoshis: Option<u64>,
533		/// None in the second case, above, ie when there is no relevant output in the commitment
534		/// transaction which appeared on chain.
535		commitment_tx_output_idx: Option<u32>,
536	},
537	/// An output waiting on [`ANTI_REORG_DELAY`] confirmations before we hand the user the
538	/// [`SpendableOutputDescriptor`].
539	MaturingOutput { descriptor: SpendableOutputDescriptor },
540	/// A spend of the funding output, either a commitment transaction or a cooperative closing
541	/// transaction.
542	FundingSpendConfirmation {
543		/// The CSV delay for the output of the funding spend transaction (implying it is a local
544		/// commitment transaction, and this is the delay on the to_self output).
545		on_local_output_csv: Option<u16>,
546		/// If the funding spend transaction was a known remote commitment transaction, we track
547		/// the output index and amount of the counterparty's `to_self` output here.
548		///
549		/// This allows us to generate a [`Balance::CounterpartyRevokedOutputClaimable`] for the
550		/// counterparty output.
551		commitment_tx_to_counterparty_output: CommitmentTxCounterpartyOutputInfo,
552	},
553	/// A spend of a commitment transaction HTLC output, set in the cases where *no* `HTLCUpdate`
554	/// is constructed. This is used when
555	///  * an outbound HTLC is claimed by our counterparty with a preimage, causing us to
556	///    immediately claim the HTLC on the inbound edge and track the resolution here,
557	///  * an inbound HTLC is claimed by our counterparty (with a timeout),
558	///  * an inbound HTLC is claimed by us (with a preimage).
559	///  * a revoked-state HTLC transaction was broadcasted, which was claimed by the revocation
560	///    signature.
561	///  * a revoked-state HTLC transaction was broadcasted, which was claimed by an
562	///    HTLC-Success/HTLC-Failure transaction (and is still claimable with a revocation
563	///    signature).
564	HTLCSpendConfirmation {
565		commitment_tx_output_idx: u32,
566		/// If the claim was made by either party with a preimage, this is filled in
567		preimage: Option<PaymentPreimage>,
568		/// If the claim was made by us on an inbound HTLC against a local commitment transaction,
569		/// we set this to the output CSV value which we will have to wait until to spend the
570		/// output (and generate a SpendableOutput event).
571		on_to_local_output_csv: Option<u16>,
572	},
573	/// An alternative funding transaction (due to a splice/RBF) has confirmed but can no longer be
574	/// locked now as the monitor is no longer allowing updates. Note that we wait to promote the
575	/// corresponding `FundingScope` until we see a
576	/// [`ChannelMonitorUpdateStep::RenegotiatedFundingLocked`], but this event is only applicable
577	/// once [`ChannelMonitor::no_further_updates_allowed`] returns true. We promote the
578	/// `FundingScope` once the funding transaction is irrevocably confirmed.
579	AlternativeFundingConfirmation {},
580}
581
582impl Writeable for OnchainEventEntry {
583	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
584		write_tlv_fields!(writer, {
585			(0, self.txid, required),
586			(1, self.transaction, option),
587			(2, self.height, required),
588			(3, self.block_hash, option),
589			(4, self.event, required),
590		});
591		Ok(())
592	}
593}
594
595impl MaybeReadable for OnchainEventEntry {
596	#[rustfmt::skip]
597	fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
598		let mut txid = Txid::all_zeros();
599		let mut transaction = None;
600		let mut block_hash = None;
601		let mut height = 0;
602		let mut event = UpgradableRequired(None);
603		read_tlv_fields!(reader, {
604			(0, txid, required),
605			(1, transaction, option),
606			(2, height, required),
607			(3, block_hash, option),
608			(4, event, upgradable_required),
609		});
610		Ok(Some(Self { txid, transaction, height, block_hash, event: _init_tlv_based_struct_field!(event, upgradable_required) }))
611	}
612}
613
614impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
615	(0, HTLCUpdate) => {
616		(0, source, required),
617		(1, htlc_value_satoshis, option),
618		(2, payment_hash, required),
619		(3, commitment_tx_output_idx, option),
620	},
621	(1, MaturingOutput) => {
622		(0, descriptor, required),
623	},
624	(2, AlternativeFundingConfirmation) => {},
625	(3, FundingSpendConfirmation) => {
626		(0, on_local_output_csv, option),
627		(1, commitment_tx_to_counterparty_output, option),
628	},
629	(5, HTLCSpendConfirmation) => {
630		(0, commitment_tx_output_idx, required),
631		(2, preimage, option),
632		(4, on_to_local_output_csv, option),
633	},
634);
635
636#[derive(Clone, Debug, PartialEq, Eq)]
637pub(crate) enum ChannelMonitorUpdateStep {
638	LatestHolderCommitmentTXInfo {
639		commitment_tx: HolderCommitmentTransaction,
640		/// Note that LDK after 0.0.115 supports this only containing dust HTLCs (implying the
641		/// `Signature` field is never filled in). At that point, non-dust HTLCs are implied by the
642		/// HTLC fields in `commitment_tx` and the sources passed via `nondust_htlc_sources`.
643		/// Starting with 0.2, the non-dust HTLC sources will always be provided separately, and
644		/// `htlc_outputs` will only include dust HTLCs. We still have to track the
645		/// `Option<Signature>` for backwards compatibility.
646		htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
647		claimed_htlcs: Vec<(SentHTLCId, PaymentPreimage)>,
648		nondust_htlc_sources: Vec<HTLCSource>,
649	},
650	LatestHolderCommitment {
651		commitment_txs: Vec<HolderCommitmentTransaction>,
652		htlc_data: CommitmentHTLCData,
653		claimed_htlcs: Vec<(SentHTLCId, PaymentPreimage)>,
654	},
655	LatestCounterpartyCommitmentTXInfo {
656		commitment_txid: Txid,
657		htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
658		commitment_number: u64,
659		their_per_commitment_point: PublicKey,
660		feerate_per_kw: Option<u32>,
661		to_broadcaster_value_sat: Option<u64>,
662		to_countersignatory_value_sat: Option<u64>,
663	},
664	LatestCounterpartyCommitment {
665		commitment_txs: Vec<CommitmentTransaction>,
666		htlc_data: CommitmentHTLCData,
667	},
668	PaymentPreimage {
669		payment_preimage: PaymentPreimage,
670		/// If this preimage was from an inbound payment claim, information about the claim should
671		/// be included here to enable claim replay on startup.
672		payment_info: Option<PaymentClaimDetails>,
673	},
674	CommitmentSecret {
675		idx: u64,
676		secret: [u8; 32],
677	},
678	/// Used to indicate that the no future updates will occur, and likely that the latest holder
679	/// commitment transaction(s) should be broadcast, as the channel has been force-closed.
680	ChannelForceClosed {
681		/// If set to false, we shouldn't broadcast the latest holder commitment transaction as we
682		/// think we've fallen behind!
683		should_broadcast: bool,
684	},
685	ShutdownScript {
686		scriptpubkey: ScriptBuf,
687	},
688	RenegotiatedFunding {
689		channel_parameters: ChannelTransactionParameters,
690		holder_commitment_tx: HolderCommitmentTransaction,
691		counterparty_commitment_tx: CommitmentTransaction,
692	},
693	RenegotiatedFundingLocked {
694		funding_txid: Txid,
695	},
696	/// When a payment is finally resolved by the user handling an [`Event::PaymentSent`] or
697	/// [`Event::PaymentFailed`] event, the `ChannelManager` no longer needs to hear about it on
698	/// startup (which would cause it to re-hydrate the payment information even though the user
699	/// already learned about the payment's result).
700	///
701	/// This will remove the HTLC from [`ChannelMonitor::get_all_current_outbound_htlcs`] and
702	/// [`ChannelMonitor::get_onchain_failed_outbound_htlcs`].
703	///
704	/// Note that this is only generated for closed channels as this is implicit in the
705	/// [`Self::CommitmentSecret`] update which clears the payment information from all un-revoked
706	/// counterparty commitment transactions.
707	ReleasePaymentComplete {
708		htlc: SentHTLCId,
709	},
710}
711
712impl ChannelMonitorUpdateStep {
713	#[rustfmt::skip]
714	fn variant_name(&self) -> &'static str {
715		match self {
716			ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. } => "LatestHolderCommitmentTXInfo",
717			ChannelMonitorUpdateStep::LatestHolderCommitment { .. } => "LatestHolderCommitment",
718			ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } => "LatestCounterpartyCommitmentTXInfo",
719			ChannelMonitorUpdateStep::LatestCounterpartyCommitment { .. } => "LatestCounterpartyCommitment",
720			ChannelMonitorUpdateStep::PaymentPreimage { .. } => "PaymentPreimage",
721			ChannelMonitorUpdateStep::CommitmentSecret { .. } => "CommitmentSecret",
722			ChannelMonitorUpdateStep::ChannelForceClosed { .. } => "ChannelForceClosed",
723			ChannelMonitorUpdateStep::ShutdownScript { .. } => "ShutdownScript",
724			ChannelMonitorUpdateStep::RenegotiatedFunding { .. } => "RenegotiatedFunding",
725			ChannelMonitorUpdateStep::RenegotiatedFundingLocked { .. } => "RenegotiatedFundingLocked",
726			ChannelMonitorUpdateStep::ReleasePaymentComplete { .. } => "ReleasePaymentComplete",
727		}
728	}
729}
730
731impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep,
732	(0, LatestHolderCommitmentTXInfo) => {
733		(0, commitment_tx, required),
734		(1, claimed_htlcs, optional_vec),
735		(2, htlc_outputs, required_vec),
736		(4, nondust_htlc_sources, optional_vec),
737	},
738	(1, LatestCounterpartyCommitmentTXInfo) => {
739		(0, commitment_txid, required),
740		(1, feerate_per_kw, option),
741		(2, commitment_number, required),
742		(3, to_broadcaster_value_sat, option),
743		(4, their_per_commitment_point, required),
744		(5, to_countersignatory_value_sat, option),
745		(6, htlc_outputs, required_vec),
746	},
747	(2, PaymentPreimage) => {
748		(0, payment_preimage, required),
749		(1, payment_info, option),
750	},
751	(3, CommitmentSecret) => {
752		(0, idx, required),
753		(2, secret, required),
754	},
755	(4, ChannelForceClosed) => {
756		(0, should_broadcast, required),
757	},
758	(5, ShutdownScript) => {
759		(0, scriptpubkey, required),
760	},
761	(6, LatestCounterpartyCommitment) => {
762		(1, commitment_txs, required_vec),
763		(3, htlc_data, required),
764	},
765	(7, ReleasePaymentComplete) => {
766		(1, htlc, required),
767	},
768	(8, LatestHolderCommitment) => {
769		(1, commitment_txs, required_vec),
770		(3, htlc_data, required),
771		(5, claimed_htlcs, required_vec),
772	},
773	(10, RenegotiatedFunding) => {
774		(1, channel_parameters, (required: ReadableArgs, None)),
775		(3, holder_commitment_tx, required),
776		(5, counterparty_commitment_tx, required),
777	},
778	(12, RenegotiatedFundingLocked) => {
779		(1, funding_txid, required),
780	},
781);
782
783/// Indicates whether the balance is derived from a cooperative close, a force-close
784/// (for holder or counterparty), or whether it is for an HTLC.
785#[derive(Clone, Debug, PartialEq, Eq)]
786#[cfg_attr(test, derive(PartialOrd, Ord))]
787pub enum BalanceSource {
788	/// The channel was force closed by the holder.
789	HolderForceClosed,
790	/// The channel was force closed by the counterparty.
791	CounterpartyForceClosed,
792	/// The channel was cooperatively closed.
793	CoopClose,
794	/// This balance is the result of an HTLC.
795	Htlc,
796}
797
798/// The claimable balance of a holder commitment transaction that has yet to be broadcast.
799#[derive(Clone, Debug, PartialEq, Eq)]
800#[cfg_attr(test, derive(PartialOrd, Ord))]
801pub struct HolderCommitmentTransactionBalance {
802	/// The amount available to claim, in satoshis, excluding the on-chain fees which will be
803	/// required to do so.
804	pub amount_satoshis: u64,
805	/// The transaction fee we pay for the closing commitment transaction. This amount is not
806	/// included in the [`HolderCommitmentTransactionBalance::amount_satoshis`] value.
807	/// This amount includes the sum of dust HTLCs on the commitment transaction, any elided anchors,
808	/// as well as the sum of msat amounts rounded down from non-dust HTLCs.
809	///
810	/// Note that if this channel is inbound (and thus our counterparty pays the commitment
811	/// transaction fee) this value will be zero. For [`ChannelMonitor`]s created prior to LDK
812	/// 0.0.124, the channel is always treated as outbound (and thus this value is never zero).
813	pub transaction_fee_satoshis: u64,
814}
815
816/// Details about the balance(s) available for spending once the channel appears on chain.
817///
818/// See [`ChannelMonitor::get_claimable_balances`] for more details on when these will or will not
819/// be provided.
820#[derive(Clone, Debug, PartialEq, Eq)]
821#[cfg_attr(test, derive(PartialOrd, Ord))]
822pub enum Balance {
823	/// The channel is not yet closed (or the commitment or closing transaction has not yet
824	/// appeared in a block).
825	ClaimableOnChannelClose {
826		/// A list of balance candidates based on the latest set of valid holder commitment
827		/// transactions that can hit the chain. Typically, a channel only has one valid holder
828		/// commitment transaction that spends the current funding output. As soon as a channel is
829		/// spliced, an alternative holder commitment transaction exists spending the new funding
830		/// output. More alternative holder commitment transactions can exist as the splice remains
831		/// pending and RBF attempts are made.
832		///
833		/// The candidates are sorted by the order in which the holder commitment transactions were
834		/// negotiated. When only one candidate exists, the channel does not have a splice pending.
835		/// When multiple candidates exist, the last one reflects the balance of the
836		/// latest splice/RBF attempt, while the first reflects the balance prior to the splice
837		/// occurring.
838		///
839		/// Entries remain in this vec until the pending splice has reached [`ANTI_REORG_DELAY`]
840		/// confirmations, at which point any conflicts will be removed. Once a splice confirms
841		/// [`Self::ClaimableOnChannelClose::confirmed_balance_candidate_index`] will point to the
842		/// confirmed entry, even if it has fewer than [`ANTI_REORG_DELAY`] confirmations.
843		balance_candidates: Vec<HolderCommitmentTransactionBalance>,
844		/// The index within [`Balance::ClaimableOnChannelClose::balance_candidates`] for the
845		/// balance according to the current onchain state of the channel. This can be helpful when
846		/// wanting to determine the claimable amount when the holder commitment transaction for the
847		/// current funding transaction is broadcast and/or confirms.
848		confirmed_balance_candidate_index: usize,
849		/// The amount of millisatoshis which has been burned to fees from HTLCs which are outbound
850		/// from us and are related to a payment which was sent by us. This is the sum of the
851		/// millisatoshis part of all HTLCs which are otherwise represented by
852		/// [`Balance::MaybeTimeoutClaimableHTLC`] with their
853		/// [`Balance::MaybeTimeoutClaimableHTLC::outbound_payment`] flag set, as well as any dust
854		/// HTLCs which would otherwise be represented the same.
855		///
856		/// This amount (rounded up to a whole satoshi value) will not be included in `amount_satoshis`.
857		outbound_payment_htlc_rounded_msat: u64,
858		/// The amount of millisatoshis which has been burned to fees from HTLCs which are outbound
859		/// from us and are related to a forwarded HTLC. This is the sum of the millisatoshis part
860		/// of all HTLCs which are otherwise represented by [`Balance::MaybeTimeoutClaimableHTLC`]
861		/// with their [`Balance::MaybeTimeoutClaimableHTLC::outbound_payment`] flag *not* set, as
862		/// well as any dust HTLCs which would otherwise be represented the same.
863		///
864		/// This amount (rounded up to a whole satoshi value) will not be included in `amount_satoshis`.
865		outbound_forwarded_htlc_rounded_msat: u64,
866		/// The amount of millisatoshis which has been burned to fees from HTLCs which are inbound
867		/// to us and for which we know the preimage. This is the sum of the millisatoshis part of
868		/// all HTLCs which would be represented by [`Balance::ContentiousClaimable`] on channel
869		/// close, but whose current value is included in
870		/// [`HolderCommitmentTransactionBalance::amount_satoshis`], as well as any dust HTLCs which
871		/// would otherwise be represented the same.
872		///
873		/// This amount (rounded up to a whole satoshi value) will not be included in the counterparty's
874		/// `amount_satoshis`.
875		inbound_claiming_htlc_rounded_msat: u64,
876		/// The amount of millisatoshis which has been burned to fees from HTLCs which are inbound
877		/// to us and for which we do not know the preimage. This is the sum of the millisatoshis
878		/// part of all HTLCs which would be represented by [`Balance::MaybePreimageClaimableHTLC`]
879		/// on channel close, as well as any dust HTLCs which would otherwise be represented the
880		/// same.
881		///
882		/// This amount (rounded up to a whole satoshi value) will not be included in the counterparty's
883		/// `amount_satoshis`.
884		inbound_htlc_rounded_msat: u64,
885	},
886	/// The channel has been closed, and the given balance is ours but awaiting confirmations until
887	/// we consider it spendable.
888	ClaimableAwaitingConfirmations {
889		/// The amount available to claim, in satoshis, possibly excluding the on-chain fees which
890		/// were spent in broadcasting the transaction.
891		amount_satoshis: u64,
892		/// The height at which an [`Event::SpendableOutputs`] event will be generated for this
893		/// amount.
894		confirmation_height: u32,
895		/// Whether this balance is a result of cooperative close, a force-close, or an HTLC.
896		source: BalanceSource,
897	},
898	/// The channel has been closed, and the given balance should be ours but awaiting spending
899	/// transaction confirmation. If the spending transaction does not confirm in time, it is
900	/// possible our counterparty can take the funds by broadcasting an HTLC timeout on-chain.
901	///
902	/// Once the spending transaction confirms, before it has reached enough confirmations to be
903	/// considered safe from chain reorganizations, the balance will instead be provided via
904	/// [`Balance::ClaimableAwaitingConfirmations`].
905	ContentiousClaimable {
906		/// The amount available to claim, in satoshis, excluding the on-chain fees which will be
907		/// required to do so.
908		amount_satoshis: u64,
909		/// The height at which the counterparty may be able to claim the balance if we have not
910		/// done so.
911		timeout_height: u32,
912		/// The payment hash that locks this HTLC.
913		payment_hash: PaymentHash,
914		/// The preimage that can be used to claim this HTLC.
915		payment_preimage: PaymentPreimage,
916	},
917	/// HTLCs which we sent to our counterparty which are claimable after a timeout (less on-chain
918	/// fees) if the counterparty does not know the preimage for the HTLCs. These are somewhat
919	/// likely to be claimed by our counterparty before we do.
920	MaybeTimeoutClaimableHTLC {
921		/// The amount potentially available to claim, in satoshis, excluding the on-chain fees
922		/// which will be required to do so.
923		amount_satoshis: u64,
924		/// The height at which we will be able to claim the balance if our counterparty has not
925		/// done so.
926		claimable_height: u32,
927		/// The payment hash whose preimage our counterparty needs to claim this HTLC.
928		payment_hash: PaymentHash,
929		/// Whether this HTLC represents a payment which was sent outbound from us. Otherwise it
930		/// represents an HTLC which was forwarded (and should, thus, have a corresponding inbound
931		/// edge on another channel).
932		outbound_payment: bool,
933	},
934	/// HTLCs which we received from our counterparty which are claimable with a preimage which we
935	/// do not currently have. This will only be claimable if we receive the preimage from the node
936	/// to which we forwarded this HTLC before the timeout.
937	MaybePreimageClaimableHTLC {
938		/// The amount potentially available to claim, in satoshis, excluding the on-chain fees
939		/// which will be required to do so.
940		amount_satoshis: u64,
941		/// The height at which our counterparty will be able to claim the balance if we have not
942		/// yet received the preimage and claimed it ourselves.
943		expiry_height: u32,
944		/// The payment hash whose preimage we need to claim this HTLC.
945		payment_hash: PaymentHash,
946	},
947	/// The channel has been closed, and our counterparty broadcasted a revoked commitment
948	/// transaction.
949	///
950	/// Thus, we're able to claim all outputs in the commitment transaction, one of which has the
951	/// following amount.
952	CounterpartyRevokedOutputClaimable {
953		/// The amount, in satoshis, of the output which we can claim.
954		///
955		/// Note that for outputs from HTLC balances this may be excluding some on-chain fees that
956		/// were already spent.
957		amount_satoshis: u64,
958	},
959}
960
961impl Balance {
962	/// The amount claimable, in satoshis.
963	///
964	/// When the channel has yet to close, this returns the balance we expect to claim from the
965	/// channel. This may change throughout the lifetime of the channel due to payments, but also
966	/// due to splicing. If there's a pending splice, this will return the balance we expect to have
967	/// assuming the latest negotiated splice confirms. However, if one of the negotiated splice
968	/// transactions has already confirmed but is not yet locked, this reports the corresponding
969	/// balance for said splice transaction instead.
970	///
971	/// For outbound payments, this excludes the balance from the possible HTLC timeout.
972	///
973	/// For forwarded payments, this includes the balance from the possible HTLC timeout as
974	/// (to be conservative) that balance does not include routing fees we'd earn if we'd claim
975	/// the balance from a preimage in a successful forward.
976	///
977	/// For more information on these balances see [`Balance::MaybeTimeoutClaimableHTLC`] and
978	/// [`Balance::MaybePreimageClaimableHTLC`].
979	///
980	/// On-chain fees required to claim the balance are not included in this amount.
981	#[rustfmt::skip]
982	pub fn claimable_amount_satoshis(&self) -> u64 {
983		match self {
984			Balance::ClaimableOnChannelClose {
985				balance_candidates, confirmed_balance_candidate_index, ..
986			} => {
987				if *confirmed_balance_candidate_index != 0 {
988					balance_candidates[*confirmed_balance_candidate_index].amount_satoshis
989				} else {
990					balance_candidates.last().map(|balance| balance.amount_satoshis).unwrap_or(0)
991				}
992			},
993			Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. }|
994			Balance::ContentiousClaimable { amount_satoshis, .. }|
995			Balance::CounterpartyRevokedOutputClaimable { amount_satoshis, .. }
996				=> *amount_satoshis,
997			Balance::MaybeTimeoutClaimableHTLC { amount_satoshis, outbound_payment, .. }
998				=> if *outbound_payment { 0 } else { *amount_satoshis },
999			Balance::MaybePreimageClaimableHTLC { .. } => 0,
1000		}
1001	}
1002}
1003
1004/// An HTLC which has been irrevocably resolved on-chain, and has reached ANTI_REORG_DELAY.
1005#[derive(Clone, PartialEq, Eq)]
1006struct IrrevocablyResolvedHTLC {
1007	commitment_tx_output_idx: Option<u32>,
1008	/// The txid of the transaction which resolved the HTLC, this may be a commitment (if the HTLC
1009	/// was not present in the confirmed commitment transaction), HTLC-Success, or HTLC-Timeout
1010	/// transaction.
1011	resolving_txid: Option<Txid>, // Added as optional, but always filled in, in 0.0.110
1012	resolving_tx: Option<Transaction>,
1013	/// Only set if the HTLC claim was ours using a payment preimage
1014	payment_preimage: Option<PaymentPreimage>,
1015}
1016
1017/// In LDK versions prior to 0.0.111 commitment_tx_output_idx was not Option-al and
1018/// IrrevocablyResolvedHTLC objects only existed for non-dust HTLCs. This was a bug, but to maintain
1019/// backwards compatibility we must ensure we always write out a commitment_tx_output_idx field,
1020/// using [`u32::MAX`] as a sentinal to indicate the HTLC was dust.
1021impl Writeable for IrrevocablyResolvedHTLC {
1022	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1023		let mapped_commitment_tx_output_idx = self.commitment_tx_output_idx.unwrap_or(u32::MAX);
1024		write_tlv_fields!(writer, {
1025			(0, mapped_commitment_tx_output_idx, required),
1026			(1, self.resolving_txid, option),
1027			(2, self.payment_preimage, option),
1028			(3, self.resolving_tx, option),
1029		});
1030		Ok(())
1031	}
1032}
1033
1034impl Readable for IrrevocablyResolvedHTLC {
1035	#[rustfmt::skip]
1036	fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1037		let mut mapped_commitment_tx_output_idx = 0;
1038		let mut resolving_txid = None;
1039		let mut payment_preimage = None;
1040		let mut resolving_tx = None;
1041		read_tlv_fields!(reader, {
1042			(0, mapped_commitment_tx_output_idx, required),
1043			(1, resolving_txid, option),
1044			(2, payment_preimage, option),
1045			(3, resolving_tx, option),
1046		});
1047		Ok(Self {
1048			commitment_tx_output_idx: if mapped_commitment_tx_output_idx == u32::MAX { None } else { Some(mapped_commitment_tx_output_idx) },
1049			resolving_txid,
1050			payment_preimage,
1051			resolving_tx,
1052		})
1053	}
1054}
1055
1056/// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
1057/// on-chain transactions to ensure no loss of funds occurs.
1058///
1059/// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
1060/// information and are actively monitoring the chain.
1061///
1062/// Like the [`ChannelManager`], deserialization is implemented for `(BlockHash, ChannelMonitor)`,
1063/// providing you with the last block hash which was connected before shutting down. You must begin
1064/// syncing the chain from that point, disconnecting and connecting blocks as required to get to
1065/// the best chain on startup. Note that all [`ChannelMonitor`]s passed to a [`ChainMonitor`] must
1066/// by synced as of the same block, so syncing must happen prior to [`ChainMonitor`]
1067/// initialization.
1068///
1069/// For those loading potentially-ancient [`ChannelMonitor`]s, deserialization is also implemented
1070/// for `Option<(BlockHash, ChannelMonitor)>`. LDK can no longer deserialize a [`ChannelMonitor`]
1071/// that was first created in LDK prior to 0.0.110 and last updated prior to LDK 0.0.119. In such
1072/// cases, the `Option<(..)>` deserialization option may return `Ok(None)` rather than failing to
1073/// deserialize, allowing you to differentiate between the two cases.
1074///
1075/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1076/// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
1077pub struct ChannelMonitor<Signer: EcdsaChannelSigner> {
1078	pub(crate) inner: Mutex<ChannelMonitorImpl<Signer>>,
1079}
1080
1081impl<Signer: EcdsaChannelSigner> Clone for ChannelMonitor<Signer>
1082where
1083	Signer: Clone,
1084{
1085	fn clone(&self) -> Self {
1086		let inner = self.inner.lock().unwrap().clone();
1087		ChannelMonitor::from_impl(inner)
1088	}
1089}
1090
1091#[derive(Clone, Debug, PartialEq, Eq)]
1092pub(crate) struct CommitmentHTLCData {
1093	// These must be sorted in increasing output index order to match the expected order of the
1094	// HTLCs in the `CommitmentTransaction`.
1095	pub nondust_htlc_sources: Vec<HTLCSource>,
1096	pub dust_htlcs: Vec<(HTLCOutputInCommitment, Option<HTLCSource>)>,
1097}
1098
1099impl CommitmentHTLCData {
1100	fn new() -> Self {
1101		Self { nondust_htlc_sources: Vec::new(), dust_htlcs: Vec::new() }
1102	}
1103}
1104
1105impl_writeable_tlv_based!(CommitmentHTLCData, {
1106	(1, nondust_htlc_sources, required_vec),
1107	(3, dust_htlcs, required_vec),
1108});
1109
1110impl TryFrom<HolderSignedTx> for CommitmentHTLCData {
1111	type Error = ();
1112	#[rustfmt::skip]
1113	fn try_from(value: HolderSignedTx) -> Result<Self, Self::Error> {
1114		// HolderSignedTx tracks all HTLCs included in the commitment (dust included). For
1115		// `HolderCommitment`, we'll need to extract the dust HTLCs and their sources, and non-dust
1116		// HTLC sources, separately. All offered, non-dust HTLCs must have a source available.
1117		let mut missing_nondust_source = false;
1118		let mut nondust_htlc_sources = Vec::with_capacity(value.htlc_outputs.len());
1119		let dust_htlcs = value.htlc_outputs.into_iter().filter_map(|(htlc, _, source)| {
1120			// Filter our non-dust HTLCs, while at the same time pushing their sources into
1121			// `nondust_htlc_sources`.
1122			if htlc.transaction_output_index.is_none() {
1123				return Some((htlc, source))
1124			}
1125			if htlc.offered {
1126				if let Some(source) = source {
1127					nondust_htlc_sources.push(source);
1128				} else {
1129					missing_nondust_source = true;
1130				}
1131			}
1132			None
1133		}).collect();
1134		if missing_nondust_source {
1135			return Err(());
1136		}
1137
1138		Ok(Self {
1139			nondust_htlc_sources,
1140			dust_htlcs,
1141		})
1142	}
1143}
1144
1145#[derive(Clone, PartialEq)]
1146struct FundingScope {
1147	channel_parameters: ChannelTransactionParameters,
1148
1149	current_counterparty_commitment_txid: Option<Txid>,
1150	prev_counterparty_commitment_txid: Option<Txid>,
1151
1152	/// The set of outpoints in each counterparty commitment transaction. We always need at least
1153	/// the payment hash from `HTLCOutputInCommitment` to claim even a revoked commitment
1154	/// transaction broadcast as we need to be able to construct the witness script in all cases.
1155	//
1156	// TODO(splicing): We shouldn't have to track these duplicatively per `FundingScope`. Ideally,
1157	// we have a global map to track the HTLCs, along with their source, as they should be
1158	// consistent across all commitments. Unfortunately, doing so requires that our HTLCs are not
1159	// tied to their respective commitment transaction via `transaction_output_index`, as those may
1160	// not be consistent across all commitments.
1161	counterparty_claimable_outpoints:
1162		HashMap<Txid, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
1163
1164	// We store two holder commitment transactions to avoid any race conditions where we may update
1165	// some monitors (potentially on watchtowers) but then fail to update others, resulting in the
1166	// various monitors for one channel being out of sync, and us broadcasting a holder
1167	// transaction for which we have deleted claim information on some watchtowers.
1168	current_holder_commitment_tx: HolderCommitmentTransaction,
1169	prev_holder_commitment_tx: Option<HolderCommitmentTransaction>,
1170}
1171
1172impl FundingScope {
1173	fn funding_outpoint(&self) -> OutPoint {
1174		let funding_outpoint = self.channel_parameters.funding_outpoint.as_ref();
1175		*funding_outpoint.expect("Funding outpoint must be set for active monitor")
1176	}
1177
1178	fn funding_txid(&self) -> Txid {
1179		self.funding_outpoint().txid
1180	}
1181
1182	fn is_splice(&self) -> bool {
1183		self.channel_parameters.splice_parent_funding_txid.is_some()
1184	}
1185
1186	fn channel_type_features(&self) -> &ChannelTypeFeatures {
1187		&self.channel_parameters.channel_type_features
1188	}
1189}
1190
1191impl_writeable_tlv_based!(FundingScope, {
1192	(1, channel_parameters, (required: ReadableArgs, None)),
1193	(3, current_counterparty_commitment_txid, required),
1194	(5, prev_counterparty_commitment_txid, option),
1195	(7, current_holder_commitment_tx, required),
1196	(9, prev_holder_commitment_tx, option),
1197	(11, counterparty_claimable_outpoints, required),
1198});
1199
1200#[derive(Clone, PartialEq)]
1201pub(crate) struct ChannelMonitorImpl<Signer: EcdsaChannelSigner> {
1202	funding: FundingScope,
1203	pending_funding: Vec<FundingScope>,
1204
1205	/// True if this channel was configured for manual funding broadcasts. Monitors written by
1206	/// versions prior to LDK 0.2 load with `false` until a new update persists it.
1207	is_manual_broadcast: bool,
1208	/// True once we've observed either funding transaction on-chain. Older monitors prior to LDK 0.2
1209	/// assume this is `true` when absent during upgrade so holder broadcasts aren't gated unexpectedly.
1210	/// In manual-broadcast channels we also use this to trigger deferred holder
1211	/// broadcasts once the funding transaction finally appears on-chain.
1212	///
1213	/// Note: This tracks whether the funding transaction was ever broadcast, not whether it is
1214	/// currently confirmed. It is never reset, even if the funding transaction is unconfirmed due
1215	/// to a reorg.
1216	funding_seen_onchain: bool,
1217
1218	latest_update_id: u64,
1219	commitment_transaction_number_obscure_factor: u64,
1220
1221	destination_script: ScriptBuf,
1222	broadcasted_holder_revokable_script: Option<(ScriptBuf, PublicKey, RevocationKey)>,
1223	counterparty_payment_script: ScriptBuf,
1224	shutdown_script: Option<ScriptBuf>,
1225
1226	channel_keys_id: [u8; 32],
1227	holder_revocation_basepoint: RevocationBasepoint,
1228	channel_id: ChannelId,
1229	first_negotiated_funding_txo: OutPoint,
1230
1231	counterparty_commitment_params: CounterpartyCommitmentParameters,
1232
1233	// first is the idx of the first of the two per-commitment points
1234	their_cur_per_commitment_points: Option<(u64, PublicKey, Option<PublicKey>)>,
1235
1236	on_holder_tx_csv: u16,
1237
1238	commitment_secrets: CounterpartyCommitmentSecrets,
1239	/// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
1240	/// Nor can we figure out their commitment numbers without the commitment transaction they are
1241	/// spending. Thus, in order to claim them via revocation key, we track all the counterparty
1242	/// commitment transactions which we find on-chain, mapping them to the commitment number which
1243	/// can be used to derive the revocation key and claim the transactions.
1244	counterparty_commitment_txn_on_chain: HashMap<Txid, u64>,
1245	/// Cache used to make pruning of payment_preimages faster.
1246	/// Maps payment_hash values to commitment numbers for counterparty transactions for non-revoked
1247	/// counterparty transactions (ie should remain pretty small).
1248	/// Serialized to disk but should generally not be sent to Watchtowers.
1249	counterparty_hash_commitment_number: HashMap<PaymentHash, u64>,
1250
1251	counterparty_fulfilled_htlcs: HashMap<SentHTLCId, PaymentPreimage>,
1252
1253	// Used just for ChannelManager to make sure it has the latest channel data during
1254	// deserialization
1255	current_counterparty_commitment_number: u64,
1256	// Used just for ChannelManager to make sure it has the latest channel data during
1257	// deserialization
1258	current_holder_commitment_number: u64,
1259
1260	/// The set of payment hashes from inbound payments for which we know the preimage. Payment
1261	/// preimages that are not included in any unrevoked local commitment transaction or unrevoked
1262	/// remote commitment transactions are automatically removed when commitment transactions are
1263	/// revoked. Note that this happens one revocation after it theoretically could, leaving
1264	/// preimages present here for the previous state even when the channel is "at rest". This is a
1265	/// good safety buffer, but also is important as it ensures we retain payment preimages for the
1266	/// previous local commitment transaction, which may have been broadcast already when we see
1267	/// the revocation (in setups with redundant monitors).
1268	///
1269	/// We also store [`PaymentClaimDetails`] here, tracking the payment information(s) for this
1270	/// preimage for inbound payments. This allows us to rebuild the inbound payment information on
1271	/// startup even if we lost our `ChannelManager`.
1272	payment_preimages: HashMap<PaymentHash, (PaymentPreimage, Vec<PaymentClaimDetails>)>,
1273
1274	// Note that `MonitorEvent`s MUST NOT be generated during update processing, only generated
1275	// during chain data processing. This prevents a race in `ChainMonitor::update_channel` (and
1276	// presumably user implementations thereof as well) where we update the in-memory channel
1277	// object, then before the persistence finishes (as it's all under a read-lock), we return
1278	// pending events to the user or to the relevant `ChannelManager`. Then, on reload, we'll have
1279	// the pre-event state here, but have processed the event in the `ChannelManager`.
1280	// Note that because the `event_lock` in `ChainMonitor` is only taken in
1281	// block/transaction-connected events and *not* during block/transaction-disconnected events,
1282	// we further MUST NOT generate events during block/transaction-disconnection.
1283	pending_monitor_events: Vec<MonitorEvent>,
1284
1285	pub(super) pending_events: Vec<Event>,
1286	pub(super) is_processing_pending_events: bool,
1287
1288	// Used to track on-chain events (i.e., transactions part of channels confirmed on chain) on
1289	// which to take actions once they reach enough confirmations. Each entry includes the
1290	// transaction's id and the height when the transaction was confirmed on chain.
1291	onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
1292
1293	// If we get serialized out and re-read, we need to make sure that the chain monitoring
1294	// interface knows about the TXOs that we want to be notified of spends of. We could probably
1295	// be smart and derive them from the above storage fields, but its much simpler and more
1296	// Obviously Correct (tm) if we just keep track of them explicitly.
1297	outputs_to_watch: HashMap<Txid, Vec<(u32, ScriptBuf)>>,
1298
1299	#[cfg(any(test, feature = "_test_utils"))]
1300	pub onchain_tx_handler: OnchainTxHandler<Signer>,
1301	#[cfg(not(any(test, feature = "_test_utils")))]
1302	onchain_tx_handler: OnchainTxHandler<Signer>,
1303
1304	// This is set when the Channel[Manager] generated a ChannelMonitorUpdate which indicated the
1305	// channel has been force-closed. After this is set, no further holder commitment transaction
1306	// updates may occur, and we panic!() if one is provided.
1307	lockdown_from_offchain: bool,
1308
1309	// Set once we've signed a holder commitment transaction and handed it over to our
1310	// OnchainTxHandler. After this is set, no future updates to our holder commitment transactions
1311	// may occur, and we fail any such monitor updates.
1312	//
1313	// In case of update rejection due to a locally already signed commitment transaction, we
1314	// nevertheless store update content to track in case of concurrent broadcast by another
1315	// remote monitor out-of-order with regards to the block view.
1316	holder_tx_signed: bool,
1317
1318	// If a spend of the funding output is seen, we set this to true and reject any further
1319	// updates. This prevents any further changes in the offchain state no matter the order
1320	// of block connection between ChannelMonitors and the ChannelManager.
1321	funding_spend_seen: bool,
1322
1323	/// True if the commitment transaction fee is paid by us.
1324	/// Added in 0.0.124.
1325	holder_pays_commitment_tx_fee: Option<bool>,
1326
1327	/// Set to `Some` of the confirmed transaction spending the funding input of the channel after
1328	/// reaching `ANTI_REORG_DELAY` confirmations.
1329	funding_spend_confirmed: Option<Txid>,
1330
1331	confirmed_commitment_tx_counterparty_output: CommitmentTxCounterpartyOutputInfo,
1332	/// The set of HTLCs which have been either claimed or failed on chain and have reached
1333	/// the requisite confirmations on the claim/fail transaction (either ANTI_REORG_DELAY or the
1334	/// spending CSV for revocable outputs).
1335	htlcs_resolved_on_chain: Vec<IrrevocablyResolvedHTLC>,
1336
1337	/// When a payment is resolved through an on-chain transaction, we tell the `ChannelManager`
1338	/// about this via [`ChannelMonitor::get_onchain_failed_outbound_htlcs`] and
1339	/// [`ChannelMonitor::get_all_current_outbound_htlcs`] at startup. We'll keep repeating the
1340	/// same payments until they're eventually fully resolved by the user processing a
1341	/// `PaymentSent` or `PaymentFailed` event, at which point the `ChannelManager` will inform of
1342	/// this and we'll store the set of fully resolved payments here.
1343	htlcs_resolved_to_user: HashSet<SentHTLCId>,
1344
1345	/// The set of `SpendableOutput` events which we have already passed upstream to be claimed.
1346	/// These are tracked explicitly to ensure that we don't generate the same events redundantly
1347	/// if users duplicatively confirm old transactions. Specifically for transactions claiming a
1348	/// revoked remote outpoint we otherwise have no tracking at all once they've reached
1349	/// [`ANTI_REORG_DELAY`], so we have to track them here.
1350	spendable_txids_confirmed: Vec<Txid>,
1351
1352	// We simply modify best_block in Channel's block_connected so that serialization is
1353	// consistent but hopefully the users' copy handles block_connected in a consistent way.
1354	// (we do *not*, however, update them in update_monitor to ensure any local user copies keep
1355	// their best_block from its state and not based on updated copies that didn't run through
1356	// the full block_connected).
1357	best_block: BestBlock,
1358
1359	/// The node_id of our counterparty
1360	counterparty_node_id: PublicKey,
1361
1362	/// Initial counterparty commmitment data needed to recreate the commitment tx
1363	/// in the persistence pipeline for third-party watchtowers. This will only be present on
1364	/// monitors created after 0.0.117.
1365	///
1366	/// Ordering of tuple data: (their_per_commitment_point, feerate_per_kw, to_broadcaster_sats,
1367	/// to_countersignatory_sats)
1368	initial_counterparty_commitment_info: Option<(PublicKey, u32, u64, u64)>,
1369	/// Initial counterparty commitment transaction
1370	///
1371	/// We previously used the field above to re-build the counterparty commitment transaction,
1372	/// we now provide the transaction outright.
1373	initial_counterparty_commitment_tx: Option<CommitmentTransaction>,
1374
1375	/// The first block height at which we had no remaining claimable balances.
1376	balances_empty_height: Option<u32>,
1377
1378	/// In-memory only HTLC ids used to track upstream HTLCs that have been failed backwards due to
1379	/// a downstream channel force-close remaining unconfirmed by the time the upstream timeout
1380	/// expires. This is used to tell us we already generated an event to fail this HTLC back
1381	/// during a previous block scan.
1382	failed_back_htlc_ids: HashSet<SentHTLCId>,
1383
1384	// The auxiliary HTLC data associated with a holder commitment transaction. This includes
1385	// non-dust HTLC sources, along with dust HTLCs and their sources. Note that this assumes any
1386	// alternative holder commitment transactions, like in the case of splicing, must maintain the
1387	// same set of non-dust and dust HTLCs. Also, while non-dust HTLC indices might change across
1388	// commitment transactions, their ordering with respect to each other must remain the same.
1389	current_holder_htlc_data: CommitmentHTLCData,
1390	prev_holder_htlc_data: Option<CommitmentHTLCData>,
1391
1392	// Upon confirmation, tracks the txid and confirmation height of a renegotiated funding
1393	// transaction found in `Self::pending_funding`. Used to determine which commitment we should
1394	// broadcast when necessary.
1395	//
1396	// "Alternative" in this context means a `FundingScope` other than the currently locked one
1397	// found at `Self::funding`. We don't use the term "renegotiated", as the currently locked
1398	// `FundingScope` could be one that was renegotiated.
1399	alternative_funding_confirmed: Option<(Txid, u32)>,
1400
1401	/// [`ChannelMonitor`]s written by LDK prior to 0.1 need to be re-persisted after startup. To
1402	/// make deciding whether to do so simple, here we track whether this monitor was last written
1403	/// prior to 0.1.
1404	written_by_0_1_or_later: bool,
1405}
1406
1407// Returns a `&FundingScope` for the one we are currently observing/handling commitment transactions
1408// for on the chain.
1409macro_rules! get_confirmed_funding_scope {
1410	($self: expr) => {
1411		$self
1412			.alternative_funding_confirmed
1413			.map(|(alternative_funding_txid, _)| {
1414				$self
1415					.pending_funding
1416					.iter()
1417					.find(|funding| funding.funding_txid() == alternative_funding_txid)
1418					.expect("FundingScope for confirmed alternative funding must exist")
1419			})
1420			.unwrap_or(&$self.funding)
1421	};
1422}
1423
1424// Macro helper to access holder commitment HTLC data (including both non-dust and dust) while
1425// holding mutable references to `self`. Unfortunately, if these were turned into helper functions,
1426// we'd be unable to mutate `self` while holding an immutable iterator (specifically, returned from
1427// a function) over `self`.
1428#[rustfmt::skip]
1429macro_rules! holder_commitment_htlcs {
1430	($self: expr, CURRENT) => {{
1431		let funding = get_confirmed_funding_scope!($self);
1432		funding.current_holder_commitment_tx.nondust_htlcs().iter()
1433			.chain($self.current_holder_htlc_data.dust_htlcs.iter().map(|(htlc, _)| htlc))
1434	}};
1435	($self: expr, CURRENT_WITH_SOURCES) => {{
1436		let funding = get_confirmed_funding_scope!($self);
1437		holder_commitment_htlcs!(
1438			&funding.current_holder_commitment_tx, &$self.current_holder_htlc_data
1439		)
1440	}};
1441	($self: expr, PREV) => {{
1442		let funding = get_confirmed_funding_scope!($self);
1443		funding.prev_holder_commitment_tx.as_ref().map(|tx| {
1444			let dust_htlcs = $self.prev_holder_htlc_data.as_ref().unwrap().dust_htlcs.iter()
1445				.map(|(htlc, _)| htlc);
1446			tx.nondust_htlcs().iter().chain(dust_htlcs)
1447		})
1448	}};
1449	($self: expr, PREV_WITH_SOURCES) => {{
1450		let funding = get_confirmed_funding_scope!($self);
1451		funding.prev_holder_commitment_tx.as_ref().map(|tx| {
1452			holder_commitment_htlcs!(tx, $self.prev_holder_htlc_data.as_ref().unwrap())
1453		})
1454	}};
1455	($commitment_tx: expr, $htlc_data: expr) => {{
1456		let mut sources = $htlc_data.nondust_htlc_sources.iter();
1457		let nondust_htlcs = $commitment_tx.nondust_htlcs().iter().map(move |htlc| {
1458			let mut source = None;
1459			if htlc.offered {
1460				debug_assert!(htlc.transaction_output_index.is_some());
1461				source = sources.next();
1462				if source.is_none() {
1463					panic!("Every offered non-dust HTLC should have a corresponding source");
1464				}
1465			}
1466			(htlc, source)
1467		});
1468		let dust_htlcs = $htlc_data.dust_htlcs.iter().map(|(htlc, source)| (htlc, source.as_ref()));
1469		nondust_htlcs.chain(dust_htlcs)
1470	}};
1471}
1472
1473/// Transaction outputs to watch for on-chain spends.
1474pub type TransactionOutputs = (Txid, Vec<(u32, TxOut)>);
1475
1476// Because we have weird workarounds for `ChannelMonitor` equality checks in `OnchainTxHandler` and
1477// `PackageTemplate` the equality implementation isn't really fit for public consumption. Instead,
1478// we only expose it during tests.
1479#[cfg(any(feature = "_test_utils", test))]
1480impl<Signer: EcdsaChannelSigner> PartialEq for ChannelMonitor<Signer>
1481where
1482	Signer: PartialEq,
1483{
1484	fn eq(&self, other: &Self) -> bool {
1485		use crate::sync::LockTestExt;
1486		// We need some kind of total lockorder. Absent a better idea, we sort by position in
1487		// memory and take locks in that order (assuming that we can't move within memory while a
1488		// lock is held).
1489		let ord = ((self as *const _) as usize) < ((other as *const _) as usize);
1490		let a = if ord {
1491			self.inner.unsafe_well_ordered_double_lock_self()
1492		} else {
1493			other.inner.unsafe_well_ordered_double_lock_self()
1494		};
1495		let b = if ord {
1496			other.inner.unsafe_well_ordered_double_lock_self()
1497		} else {
1498			self.inner.unsafe_well_ordered_double_lock_self()
1499		};
1500		a.eq(&b)
1501	}
1502}
1503
1504impl<Signer: EcdsaChannelSigner> Writeable for ChannelMonitor<Signer> {
1505	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
1506		self.inner.lock().unwrap().write(writer)
1507	}
1508}
1509
1510// These are also used for ChannelMonitorUpdate, above.
1511const SERIALIZATION_VERSION: u8 = 1;
1512const MIN_SERIALIZATION_VERSION: u8 = 1;
1513
1514/// Utility function for writing [`ChannelMonitor`] to prevent code duplication in [`ChainMonitor`] while sending Peer Storage.
1515///
1516/// NOTE: `is_stub` is true only when we are using this to serialise for Peer Storage.
1517///
1518/// TODO: Determine which fields of each `ChannelMonitor` should be included in Peer Storage, and which should be omitted.
1519///
1520/// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
1521pub(crate) fn write_chanmon_internal<Signer: EcdsaChannelSigner, W: Writer>(
1522	channel_monitor: &ChannelMonitorImpl<Signer>, _is_stub: bool, writer: &mut W,
1523) -> Result<(), Error> {
1524	write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
1525
1526	channel_monitor.latest_update_id.write(writer)?;
1527
1528	// Set in initial Channel-object creation, so should always be set by now:
1529	U48(channel_monitor.commitment_transaction_number_obscure_factor).write(writer)?;
1530
1531	channel_monitor.destination_script.write(writer)?;
1532	if let Some(ref broadcasted_holder_revokable_script) =
1533		channel_monitor.broadcasted_holder_revokable_script
1534	{
1535		writer.write_all(&[0; 1])?;
1536		broadcasted_holder_revokable_script.0.write(writer)?;
1537		broadcasted_holder_revokable_script.1.write(writer)?;
1538		broadcasted_holder_revokable_script.2.write(writer)?;
1539	} else {
1540		writer.write_all(&[1; 1])?;
1541	}
1542
1543	channel_monitor.counterparty_payment_script.write(writer)?;
1544	match &channel_monitor.shutdown_script {
1545		Some(script) => script.write(writer)?,
1546		None => ScriptBuf::new().write(writer)?,
1547	}
1548
1549	channel_monitor.channel_keys_id.write(writer)?;
1550	channel_monitor.holder_revocation_basepoint.write(writer)?;
1551	let funding_outpoint = channel_monitor.get_funding_txo();
1552	writer.write_all(&funding_outpoint.txid[..])?;
1553	writer.write_all(&funding_outpoint.index.to_be_bytes())?;
1554	let redeem_script = channel_monitor.funding.channel_parameters.make_funding_redeemscript();
1555	let script_pubkey = redeem_script.to_p2wsh();
1556	script_pubkey.write(writer)?;
1557	channel_monitor.funding.current_counterparty_commitment_txid.write(writer)?;
1558	channel_monitor.funding.prev_counterparty_commitment_txid.write(writer)?;
1559
1560	channel_monitor.counterparty_commitment_params.write(writer)?;
1561	redeem_script.write(writer)?;
1562	channel_monitor.funding.channel_parameters.channel_value_satoshis.write(writer)?;
1563
1564	match channel_monitor.their_cur_per_commitment_points {
1565		Some((idx, pubkey, second_option)) => {
1566			writer.write_all(&byte_utils::be48_to_array(idx))?;
1567			writer.write_all(&pubkey.serialize())?;
1568			match second_option {
1569				Some(second_pubkey) => {
1570					writer.write_all(&second_pubkey.serialize())?;
1571				},
1572				None => {
1573					writer.write_all(&[0; 33])?;
1574				},
1575			}
1576		},
1577		None => {
1578			writer.write_all(&byte_utils::be48_to_array(0))?;
1579		},
1580	}
1581
1582	writer.write_all(&channel_monitor.on_holder_tx_csv.to_be_bytes())?;
1583
1584	channel_monitor.commitment_secrets.write(writer)?;
1585
1586	#[rustfmt::skip]
1587	macro_rules! serialize_htlc_in_commitment {
1588		($htlc_output: expr) => {
1589			writer.write_all(&[$htlc_output.offered as u8; 1])?;
1590			writer.write_all(&$htlc_output.amount_msat.to_be_bytes())?;
1591			writer.write_all(&$htlc_output.cltv_expiry.to_be_bytes())?;
1592			writer.write_all(&$htlc_output.payment_hash.0[..])?;
1593			$htlc_output.transaction_output_index.write(writer)?;
1594		}
1595	}
1596
1597	writer.write_all(
1598		&(channel_monitor.funding.counterparty_claimable_outpoints.len() as u64).to_be_bytes(),
1599	)?;
1600	for (ref txid, ref htlc_infos) in
1601		channel_monitor.funding.counterparty_claimable_outpoints.iter()
1602	{
1603		writer.write_all(&txid[..])?;
1604		writer.write_all(&(htlc_infos.len() as u64).to_be_bytes())?;
1605		for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
1606			debug_assert!(
1607				htlc_source.is_none()
1608					|| Some(**txid) == channel_monitor.funding.current_counterparty_commitment_txid
1609					|| Some(**txid) == channel_monitor.funding.prev_counterparty_commitment_txid,
1610				"HTLC Sources for all revoked commitment transactions should be none!"
1611			);
1612			serialize_htlc_in_commitment!(htlc_output);
1613			htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
1614		}
1615	}
1616
1617	writer.write_all(
1618		&(channel_monitor.counterparty_commitment_txn_on_chain.len() as u64).to_be_bytes(),
1619	)?;
1620	for (ref txid, commitment_number) in channel_monitor.counterparty_commitment_txn_on_chain.iter()
1621	{
1622		writer.write_all(&txid[..])?;
1623		writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1624	}
1625
1626	writer.write_all(
1627		&(channel_monitor.counterparty_hash_commitment_number.len() as u64).to_be_bytes(),
1628	)?;
1629	for (ref payment_hash, commitment_number) in
1630		channel_monitor.counterparty_hash_commitment_number.iter()
1631	{
1632		writer.write_all(&payment_hash.0[..])?;
1633		writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1634	}
1635
1636	if let Some(holder_commitment_tx) = &channel_monitor.funding.prev_holder_commitment_tx {
1637		writer.write_all(&[1; 1])?;
1638		write_legacy_holder_commitment_data(
1639			writer,
1640			holder_commitment_tx,
1641			&channel_monitor.prev_holder_htlc_data.as_ref().unwrap(),
1642		)?;
1643	} else {
1644		writer.write_all(&[0; 1])?;
1645	}
1646
1647	write_legacy_holder_commitment_data(
1648		writer,
1649		&channel_monitor.funding.current_holder_commitment_tx,
1650		&channel_monitor.current_holder_htlc_data,
1651	)?;
1652
1653	writer.write_all(&byte_utils::be48_to_array(
1654		channel_monitor.current_counterparty_commitment_number,
1655	))?;
1656	writer
1657		.write_all(&byte_utils::be48_to_array(channel_monitor.current_holder_commitment_number))?;
1658
1659	writer.write_all(&(channel_monitor.payment_preimages.len() as u64).to_be_bytes())?;
1660	for (payment_preimage, _) in channel_monitor.payment_preimages.values() {
1661		writer.write_all(&payment_preimage.0[..])?;
1662	}
1663
1664	writer.write_all(
1665		&(channel_monitor
1666			.pending_monitor_events
1667			.iter()
1668			.filter(|ev| match ev {
1669				MonitorEvent::HTLCEvent(_) => true,
1670				MonitorEvent::HolderForceClosed(_) => true,
1671				MonitorEvent::HolderForceClosedWithInfo { .. } => true,
1672				_ => false,
1673			})
1674			.count() as u64)
1675			.to_be_bytes(),
1676	)?;
1677	for event in channel_monitor.pending_monitor_events.iter() {
1678		match event {
1679			MonitorEvent::HTLCEvent(upd) => {
1680				0u8.write(writer)?;
1681				upd.write(writer)?;
1682			},
1683			MonitorEvent::HolderForceClosed(_) => 1u8.write(writer)?,
1684			// `HolderForceClosedWithInfo` replaced `HolderForceClosed` in v0.0.122. To keep
1685			// backwards compatibility, we write a `HolderForceClosed` event along with the
1686			// `HolderForceClosedWithInfo` event. This is deduplicated in the reader.
1687			MonitorEvent::HolderForceClosedWithInfo { .. } => 1u8.write(writer)?,
1688			_ => {}, // Covered in the TLV writes below
1689		}
1690	}
1691
1692	writer.write_all(&(channel_monitor.pending_events.len() as u64).to_be_bytes())?;
1693	for event in channel_monitor.pending_events.iter() {
1694		event.write(writer)?;
1695	}
1696
1697	channel_monitor.best_block.block_hash.write(writer)?;
1698	writer.write_all(&channel_monitor.best_block.height.to_be_bytes())?;
1699
1700	writer.write_all(
1701		&(channel_monitor.onchain_events_awaiting_threshold_conf.len() as u64).to_be_bytes(),
1702	)?;
1703	for ref entry in channel_monitor.onchain_events_awaiting_threshold_conf.iter() {
1704		entry.write(writer)?;
1705	}
1706
1707	(channel_monitor.outputs_to_watch.len() as u64).write(writer)?;
1708	for (txid, idx_scripts) in channel_monitor.outputs_to_watch.iter() {
1709		txid.write(writer)?;
1710		(idx_scripts.len() as u64).write(writer)?;
1711		for (idx, script) in idx_scripts.iter() {
1712			idx.write(writer)?;
1713			script.write(writer)?;
1714		}
1715	}
1716
1717	channel_monitor.onchain_tx_handler.write(writer)?;
1718
1719	channel_monitor.lockdown_from_offchain.write(writer)?;
1720	channel_monitor.holder_tx_signed.write(writer)?;
1721
1722	// If we have a `HolderForceClosedWithInfo` event, we need to write the `HolderForceClosed` for backwards compatibility.
1723	let pending_monitor_events =
1724		match channel_monitor.pending_monitor_events.iter().find(|ev| match ev {
1725			MonitorEvent::HolderForceClosedWithInfo { .. } => true,
1726			_ => false,
1727		}) {
1728			Some(MonitorEvent::HolderForceClosedWithInfo { outpoint, .. }) => {
1729				let mut pending_monitor_events = channel_monitor.pending_monitor_events.clone();
1730				pending_monitor_events.push(MonitorEvent::HolderForceClosed(*outpoint));
1731				pending_monitor_events
1732			},
1733			_ => channel_monitor.pending_monitor_events.clone(),
1734		};
1735
1736	write_tlv_fields!(writer, {
1737		(1, channel_monitor.funding_spend_confirmed, option),
1738		(3, channel_monitor.htlcs_resolved_on_chain, required_vec),
1739		(5, pending_monitor_events, required_vec),
1740		(7, channel_monitor.funding_spend_seen, required),
1741		(9, channel_monitor.counterparty_node_id, required),
1742		(11, channel_monitor.confirmed_commitment_tx_counterparty_output, option),
1743		(13, channel_monitor.spendable_txids_confirmed, required_vec),
1744		(15, channel_monitor.counterparty_fulfilled_htlcs, required),
1745		(17, channel_monitor.initial_counterparty_commitment_info, option),
1746		(19, channel_monitor.channel_id, required),
1747		(21, channel_monitor.balances_empty_height, option),
1748		(23, channel_monitor.holder_pays_commitment_tx_fee, option),
1749		(25, channel_monitor.payment_preimages, required),
1750		(27, channel_monitor.first_negotiated_funding_txo, required),
1751		(29, channel_monitor.initial_counterparty_commitment_tx, option),
1752		(31, channel_monitor.funding.channel_parameters, required),
1753		(32, channel_monitor.pending_funding, optional_vec),
1754		(33, channel_monitor.htlcs_resolved_to_user, required),
1755		(34, channel_monitor.alternative_funding_confirmed, option),
1756		(35, channel_monitor.is_manual_broadcast, required),
1757		(37, channel_monitor.funding_seen_onchain, required),
1758	});
1759
1760	Ok(())
1761}
1762
1763impl<Signer: EcdsaChannelSigner> Writeable for ChannelMonitorImpl<Signer> {
1764	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
1765		write_chanmon_internal(self, false, writer)
1766	}
1767}
1768
1769#[rustfmt::skip]
1770macro_rules! _process_events_body {
1771	($self_opt: expr, $logger: expr, $event_to_handle: expr, $handle_event: expr) => {
1772		loop {
1773			let mut handling_res = Ok(());
1774			let (pending_events, repeated_events);
1775			if let Some(us) = $self_opt {
1776				let mut inner = us.inner.lock().unwrap();
1777				if inner.is_processing_pending_events {
1778					break handling_res;
1779				}
1780				inner.is_processing_pending_events = true;
1781
1782				pending_events = inner.pending_events.clone();
1783				repeated_events = inner.get_repeated_events();
1784			} else { break handling_res; }
1785
1786			let mut num_handled_events = 0;
1787			for event in pending_events {
1788				log_trace!($logger, "Handling event {:?}...", event);
1789				$event_to_handle = event;
1790				let event_handling_result = $handle_event;
1791				log_trace!($logger, "Done handling event, result: {:?}", event_handling_result);
1792				match event_handling_result {
1793					Ok(()) => num_handled_events += 1,
1794					Err(e) => {
1795						// If we encounter an error we stop handling events and make sure to replay
1796						// any unhandled events on the next invocation.
1797						handling_res = Err(e);
1798						break;
1799					}
1800				}
1801			}
1802
1803			if handling_res.is_ok() {
1804				for event in repeated_events {
1805					// For repeated events we ignore any errors as they will be replayed eventually
1806					// anyways.
1807					$event_to_handle = event;
1808					let _ = $handle_event;
1809				}
1810			}
1811
1812			if let Some(us) = $self_opt {
1813				let mut inner = us.inner.lock().unwrap();
1814				inner.pending_events.drain(..num_handled_events);
1815				inner.is_processing_pending_events = false;
1816				if handling_res.is_ok() && !inner.pending_events.is_empty() {
1817					// If there's more events to process and we didn't fail so far, go ahead and do
1818					// so.
1819					continue;
1820				}
1821			}
1822			break handling_res;
1823		}
1824	}
1825}
1826pub(super) use _process_events_body as process_events_body;
1827
1828pub(crate) struct WithChannelMonitor<'a, L: Deref>
1829where
1830	L::Target: Logger,
1831{
1832	logger: &'a L,
1833	peer_id: Option<PublicKey>,
1834	channel_id: Option<ChannelId>,
1835	payment_hash: Option<PaymentHash>,
1836}
1837
1838impl<'a, L: Deref> Logger for WithChannelMonitor<'a, L>
1839where
1840	L::Target: Logger,
1841{
1842	fn log(&self, mut record: Record) {
1843		record.peer_id = self.peer_id;
1844		record.channel_id = self.channel_id;
1845		record.payment_hash = self.payment_hash;
1846		self.logger.log(record)
1847	}
1848}
1849
1850impl<'a, L: Deref> WithChannelMonitor<'a, L>
1851where
1852	L::Target: Logger,
1853{
1854	pub(crate) fn from<S: EcdsaChannelSigner>(
1855		logger: &'a L, monitor: &ChannelMonitor<S>, payment_hash: Option<PaymentHash>,
1856	) -> Self {
1857		Self::from_impl(logger, &*monitor.inner.lock().unwrap(), payment_hash)
1858	}
1859
1860	#[rustfmt::skip]
1861	pub(crate) fn from_impl<S: EcdsaChannelSigner>(logger: &'a L, monitor_impl: &ChannelMonitorImpl<S>, payment_hash: Option<PaymentHash>) -> Self {
1862		let peer_id = Some(monitor_impl.counterparty_node_id);
1863		let channel_id = Some(monitor_impl.channel_id());
1864		WithChannelMonitor {
1865			logger, peer_id, channel_id, payment_hash,
1866		}
1867	}
1868}
1869
1870impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
1871	/// For lockorder enforcement purposes, we need to have a single site which constructs the
1872	/// `inner` mutex, otherwise cases where we lock two monitors at the same time (eg in our
1873	/// PartialEq implementation) we may decide a lockorder violation has occurred.
1874	fn from_impl(imp: ChannelMonitorImpl<Signer>) -> Self {
1875		ChannelMonitor { inner: Mutex::new(imp) }
1876	}
1877
1878	#[rustfmt::skip]
1879	pub(crate) fn new(
1880		secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_script: Option<ScriptBuf>,
1881		on_counterparty_tx_csv: u16, destination_script: &Script,
1882		channel_parameters: &ChannelTransactionParameters, holder_pays_commitment_tx_fee: bool,
1883		commitment_transaction_number_obscure_factor: u64,
1884		initial_holder_commitment_tx: HolderCommitmentTransaction, best_block: BestBlock,
1885		counterparty_node_id: PublicKey, channel_id: ChannelId,
1886		is_manual_broadcast: bool,
1887	) -> ChannelMonitor<Signer> {
1888
1889		assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
1890		let holder_pubkeys = &channel_parameters.holder_pubkeys;
1891		let counterparty_payment_script = chan_utils::get_countersigner_payment_script(
1892			&channel_parameters.channel_type_features, &holder_pubkeys.payment_point
1893		);
1894
1895		let counterparty_channel_parameters = channel_parameters.counterparty_parameters.as_ref().unwrap();
1896		let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
1897		let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
1898		let counterparty_commitment_params = CounterpartyCommitmentParameters { counterparty_delayed_payment_base_key, counterparty_htlc_base_key, on_counterparty_tx_csv };
1899
1900		let channel_keys_id = keys.channel_keys_id();
1901		let holder_revocation_basepoint = holder_pubkeys.revocation_basepoint;
1902
1903		let current_holder_commitment_number =
1904			initial_holder_commitment_tx.trust().commitment_number();
1905
1906		let onchain_tx_handler = OnchainTxHandler::new(
1907			channel_parameters.channel_value_satoshis, channel_keys_id, destination_script.into(),
1908			keys, channel_parameters.clone(), initial_holder_commitment_tx.clone(), secp_ctx
1909		);
1910
1911		let funding_outpoint = channel_parameters.funding_outpoint
1912			.expect("Funding outpoint must be known during initialization");
1913		let funding_redeem_script = channel_parameters.make_funding_redeemscript();
1914		let funding_script = funding_redeem_script.to_p2wsh();
1915		let mut outputs_to_watch = new_hash_map();
1916		outputs_to_watch.insert(
1917			funding_outpoint.txid, vec![(funding_outpoint.index as u32, funding_script.clone())],
1918		);
1919
1920		Self::from_impl(ChannelMonitorImpl {
1921			funding: FundingScope {
1922				channel_parameters: channel_parameters.clone(),
1923
1924				current_counterparty_commitment_txid: None,
1925				prev_counterparty_commitment_txid: None,
1926				counterparty_claimable_outpoints: new_hash_map(),
1927
1928				current_holder_commitment_tx: initial_holder_commitment_tx,
1929				prev_holder_commitment_tx: None,
1930			},
1931			pending_funding: vec![],
1932
1933			is_manual_broadcast,
1934			funding_seen_onchain: false,
1935
1936			latest_update_id: 0,
1937			commitment_transaction_number_obscure_factor,
1938
1939			destination_script: destination_script.into(),
1940			broadcasted_holder_revokable_script: None,
1941			counterparty_payment_script,
1942			shutdown_script,
1943
1944			channel_keys_id,
1945			holder_revocation_basepoint,
1946			channel_id,
1947			first_negotiated_funding_txo: funding_outpoint,
1948
1949			counterparty_commitment_params,
1950			their_cur_per_commitment_points: None,
1951
1952			on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
1953
1954			commitment_secrets: CounterpartyCommitmentSecrets::new(),
1955			counterparty_commitment_txn_on_chain: new_hash_map(),
1956			counterparty_hash_commitment_number: new_hash_map(),
1957			counterparty_fulfilled_htlcs: new_hash_map(),
1958
1959			current_counterparty_commitment_number: 1 << 48,
1960			current_holder_commitment_number,
1961
1962			payment_preimages: new_hash_map(),
1963			pending_monitor_events: Vec::new(),
1964			pending_events: Vec::new(),
1965			is_processing_pending_events: false,
1966
1967			onchain_events_awaiting_threshold_conf: Vec::new(),
1968			outputs_to_watch,
1969
1970			onchain_tx_handler,
1971
1972			holder_pays_commitment_tx_fee: Some(holder_pays_commitment_tx_fee),
1973			lockdown_from_offchain: false,
1974			holder_tx_signed: false,
1975			funding_spend_seen: false,
1976			funding_spend_confirmed: None,
1977			confirmed_commitment_tx_counterparty_output: None,
1978			htlcs_resolved_on_chain: Vec::new(),
1979			htlcs_resolved_to_user: new_hash_set(),
1980			spendable_txids_confirmed: Vec::new(),
1981
1982			best_block,
1983			counterparty_node_id: counterparty_node_id,
1984			initial_counterparty_commitment_info: None,
1985			initial_counterparty_commitment_tx: None,
1986			balances_empty_height: None,
1987
1988			failed_back_htlc_ids: new_hash_set(),
1989
1990			// There are never any HTLCs in the initial commitment transaction
1991			current_holder_htlc_data: CommitmentHTLCData::new(),
1992			prev_holder_htlc_data: None,
1993
1994			alternative_funding_confirmed: None,
1995
1996			written_by_0_1_or_later: true,
1997		})
1998	}
1999
2000	/// Returns a unique id for persisting the [`ChannelMonitor`], which is used as a key in a
2001	/// key-value store.
2002	///
2003	/// Note: Previously, the funding outpoint was used in the [`Persist`] trait. However, since the
2004	/// outpoint may change during splicing, this method is used to obtain a unique key instead. For
2005	/// v1 channels, the funding outpoint is still used for backwards compatibility, whereas v2
2006	/// channels use the channel id since it is fixed.
2007	///
2008	/// [`Persist`]: crate::chain::chainmonitor::Persist
2009	pub fn persistence_key(&self) -> MonitorName {
2010		let inner = self.inner.lock().unwrap();
2011		let funding_outpoint = inner.first_negotiated_funding_txo;
2012		let channel_id = inner.channel_id;
2013		if ChannelId::v1_from_funding_outpoint(funding_outpoint) == channel_id {
2014			MonitorName::V1Channel(funding_outpoint)
2015		} else {
2016			MonitorName::V2Channel(channel_id)
2017		}
2018	}
2019
2020	#[cfg(test)]
2021	fn provide_secret(&self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
2022		self.inner.lock().unwrap().provide_secret(idx, secret)
2023	}
2024
2025	/// A variant of `Self::provide_latest_counterparty_commitment_tx` used to provide
2026	/// the counterparty commitment transaction to the monitor so that the transaction
2027	/// can be retrieved during the initial persistence of the monitor (mainly for use in
2028	/// third-party watchtowers).
2029	///
2030	/// This is used to provide the counterparty commitment transaction directly to the monitor
2031	/// before the initial persistence of a new channel.
2032	pub(crate) fn provide_initial_counterparty_commitment_tx(
2033		&self, commitment_tx: CommitmentTransaction,
2034	) {
2035		let mut inner = self.inner.lock().unwrap();
2036		inner.provide_initial_counterparty_commitment_tx(commitment_tx);
2037	}
2038
2039	/// Informs this monitor of the latest counterparty (ie non-broadcastable) commitment transaction.
2040	/// The monitor watches for it to be broadcasted and then uses the HTLC information (and
2041	/// possibly future revocation/preimage information) to claim outputs where possible.
2042	/// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
2043	#[cfg(test)]
2044	fn provide_latest_counterparty_commitment_tx(
2045		&self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
2046		commitment_number: u64, their_per_commitment_point: PublicKey,
2047	) {
2048		let mut inner = self.inner.lock().unwrap();
2049		inner.provide_latest_counterparty_commitment_tx(
2050			txid,
2051			htlc_outputs,
2052			commitment_number,
2053			their_per_commitment_point,
2054		)
2055	}
2056
2057	#[cfg(test)]
2058	#[rustfmt::skip]
2059	fn provide_latest_holder_commitment_tx(
2060		&self, holder_commitment_tx: HolderCommitmentTransaction,
2061		htlc_outputs: &[(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)],
2062	) {
2063		self.inner.lock().unwrap().provide_latest_holder_commitment_tx(
2064			holder_commitment_tx, htlc_outputs, &Vec::new(), Vec::new(),
2065		).unwrap()
2066	}
2067
2068	/// This is used to provide payment preimage(s) out-of-band during startup without updating the
2069	/// off-chain state with a new commitment transaction.
2070	///
2071	/// It is used only for legacy (created prior to LDK 0.1) pending payments on upgrade, and the
2072	/// flow that uses it assumes that this [`ChannelMonitor`] is persisted prior to the
2073	/// [`ChannelManager`] being persisted (as the state necessary to call this method again is
2074	/// removed from the [`ChannelManager`] and thus a persistence inversion would imply we do not
2075	/// get the preimage back into this [`ChannelMonitor`] on startup).
2076	///
2077	/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
2078	#[rustfmt::skip]
2079	pub(crate) fn provide_payment_preimage_unsafe_legacy<B: Deref, F: Deref, L: Deref>(
2080		&self,
2081		payment_hash: &PaymentHash,
2082		payment_preimage: &PaymentPreimage,
2083		broadcaster: &B,
2084		fee_estimator: &LowerBoundedFeeEstimator<F>,
2085		logger: &L,
2086	) where
2087		B::Target: BroadcasterInterface,
2088		F::Target: FeeEstimator,
2089		L::Target: Logger,
2090	{
2091		let mut inner = self.inner.lock().unwrap();
2092		let logger = WithChannelMonitor::from_impl(logger, &*inner, Some(*payment_hash));
2093		// Note that we don't pass any MPP claim parts here. This is generally not okay but in this
2094		// case is acceptable as we only call this method from `ChannelManager` deserialization in
2095		// cases where we are replaying a claim started on a previous version of LDK.
2096		inner.provide_payment_preimage(
2097			payment_hash, payment_preimage, &None, broadcaster, fee_estimator, &logger)
2098	}
2099
2100	/// Updates a ChannelMonitor on the basis of some new information provided by the Channel
2101	/// itself.
2102	///
2103	/// panics if the given update is not the next update by update_id.
2104	pub fn update_monitor<B: Deref, F: Deref, L: Deref>(
2105		&self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &L,
2106	) -> Result<(), ()>
2107	where
2108		B::Target: BroadcasterInterface,
2109		F::Target: FeeEstimator,
2110		L::Target: Logger,
2111	{
2112		let mut inner = self.inner.lock().unwrap();
2113		let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2114		inner.update_monitor(updates, broadcaster, fee_estimator, &logger)
2115	}
2116
2117	/// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
2118	/// ChannelMonitor.
2119	///
2120	/// Note that for channels closed prior to LDK 0.1, this may return [`u64::MAX`].
2121	pub fn get_latest_update_id(&self) -> u64 {
2122		self.inner.lock().unwrap().get_latest_update_id()
2123	}
2124
2125	/// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
2126	pub fn get_funding_txo(&self) -> OutPoint {
2127		self.inner.lock().unwrap().get_funding_txo()
2128	}
2129
2130	pub(crate) fn written_by_0_1_or_later(&self) -> bool {
2131		self.inner.lock().unwrap().written_by_0_1_or_later
2132	}
2133
2134	/// Gets the funding script of the channel this ChannelMonitor is monitoring for.
2135	pub fn get_funding_script(&self) -> ScriptBuf {
2136		self.inner.lock().unwrap().get_funding_script()
2137	}
2138
2139	/// Gets the channel_id of the channel this ChannelMonitor is monitoring for.
2140	pub fn channel_id(&self) -> ChannelId {
2141		self.inner.lock().unwrap().channel_id()
2142	}
2143
2144	/// Gets the channel type of the corresponding channel.
2145	pub fn channel_type_features(&self) -> ChannelTypeFeatures {
2146		self.inner.lock().unwrap().channel_type_features().clone()
2147	}
2148
2149	/// Gets a list of txids, with their output scripts (in the order they appear in the
2150	/// transaction), which we must learn about spends of via block_connected().
2151	#[rustfmt::skip]
2152	pub fn get_outputs_to_watch(&self) -> Vec<(Txid, Vec<(u32, ScriptBuf)>)> {
2153		self.inner.lock().unwrap().get_outputs_to_watch()
2154			.iter().map(|(txid, outputs)| (*txid, outputs.clone())).collect()
2155	}
2156
2157	/// Loads the funding txo and outputs to watch into the given `chain::Filter` by repeatedly
2158	/// calling `chain::Filter::register_output` and `chain::Filter::register_tx` until all outputs
2159	/// have been registered.
2160	#[rustfmt::skip]
2161	pub fn load_outputs_to_watch<F: Deref, L: Deref>(&self, filter: &F, logger: &L)
2162	where
2163		F::Target: chain::Filter, L::Target: Logger,
2164	{
2165		let lock = self.inner.lock().unwrap();
2166		let logger = WithChannelMonitor::from_impl(logger, &*lock, None);
2167		for funding in core::iter::once(&lock.funding).chain(&lock.pending_funding) {
2168			let funding_outpoint = funding.funding_outpoint();
2169			log_trace!(&logger, "Registering funding outpoint {} with the filter to monitor confirmations", &funding_outpoint);
2170			let script_pubkey = funding.channel_parameters.make_funding_redeemscript().to_p2wsh();
2171			filter.register_tx(&funding_outpoint.txid, &script_pubkey);
2172		}
2173		for (txid, outputs) in lock.get_outputs_to_watch().iter() {
2174			for (index, script_pubkey) in outputs.iter() {
2175				assert!(*index <= u16::MAX as u32);
2176				let outpoint = OutPoint { txid: *txid, index: *index as u16 };
2177				log_trace!(logger, "Registering outpoint {} with the filter to monitor spend", outpoint);
2178				filter.register_output(WatchedOutput {
2179					block_hash: None,
2180					outpoint,
2181					script_pubkey: script_pubkey.clone(),
2182				});
2183			}
2184		}
2185	}
2186
2187	/// Get the list of HTLCs who's status has been updated on chain. This should be called by
2188	/// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
2189	pub fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
2190		self.inner.lock().unwrap().get_and_clear_pending_monitor_events()
2191	}
2192
2193	/// Processes [`SpendableOutputs`] events produced from each [`ChannelMonitor`] upon maturity.
2194	///
2195	/// For channels featuring anchor outputs, this method will also process [`BumpTransaction`]
2196	/// events produced from each [`ChannelMonitor`] while there is a balance to claim onchain
2197	/// within each channel. As the confirmation of a commitment transaction may be critical to the
2198	/// safety of funds, we recommend invoking this every 30 seconds, or lower if running in an
2199	/// environment with spotty connections, like on mobile.
2200	///
2201	/// An [`EventHandler`] may safely call back to the provider, though this shouldn't be needed in
2202	/// order to handle these events.
2203	///
2204	/// Will return a [`ReplayEvent`] error if event handling failed and should eventually be retried.
2205	///
2206	/// [`SpendableOutputs`]: crate::events::Event::SpendableOutputs
2207	/// [`BumpTransaction`]: crate::events::Event::BumpTransaction
2208	pub fn process_pending_events<H: Deref, L: Deref>(
2209		&self, handler: &H, logger: &L,
2210	) -> Result<(), ReplayEvent>
2211	where
2212		H::Target: EventHandler,
2213		L::Target: Logger,
2214	{
2215		let mut ev;
2216		process_events_body!(Some(self), logger, ev, handler.handle_event(ev))
2217	}
2218
2219	/// Processes any events asynchronously.
2220	///
2221	/// See [`Self::process_pending_events`] for more information.
2222	pub async fn process_pending_events_async<
2223		Future: core::future::Future<Output = Result<(), ReplayEvent>>,
2224		H: Fn(Event) -> Future,
2225		L: Deref,
2226	>(
2227		&self, handler: &H, logger: &L,
2228	) -> Result<(), ReplayEvent>
2229	where
2230		L::Target: Logger,
2231	{
2232		let mut ev;
2233		process_events_body!(Some(self), logger, ev, { handler(ev).await })
2234	}
2235
2236	#[cfg(test)]
2237	pub fn get_and_clear_pending_events(&self) -> Vec<Event> {
2238		let mut ret = Vec::new();
2239		let mut lck = self.inner.lock().unwrap();
2240		mem::swap(&mut ret, &mut lck.pending_events);
2241		ret.append(&mut lck.get_repeated_events());
2242		ret
2243	}
2244
2245	/// Gets the counterparty's initial commitment transaction. The returned commitment
2246	/// transaction is unsigned. This is intended to be called during the initial persistence of
2247	/// the monitor (inside an implementation of [`Persist::persist_new_channel`]), to allow for
2248	/// watchtowers in the persistence pipeline to have enough data to form justice transactions.
2249	///
2250	/// This is similar to [`Self::counterparty_commitment_txs_from_update`], except
2251	/// that for the initial commitment transaction, we don't have a corresponding update.
2252	///
2253	/// This will only return `Some` for channel monitors that have been created after upgrading
2254	/// to LDK 0.0.117+.
2255	///
2256	/// [`Persist::persist_new_channel`]: crate::chain::chainmonitor::Persist::persist_new_channel
2257	pub fn initial_counterparty_commitment_tx(&self) -> Option<CommitmentTransaction> {
2258		self.inner.lock().unwrap().initial_counterparty_commitment_tx()
2259	}
2260
2261	/// Gets all of the counterparty commitment transactions provided by the given update. This
2262	/// may be empty if the update doesn't include any new counterparty commitments. Returned
2263	/// commitment transactions are unsigned.
2264	///
2265	/// This is provided so that watchtower clients in the persistence pipeline are able to build
2266	/// justice transactions for each counterparty commitment upon each update. It's intended to be
2267	/// used within an implementation of [`Persist::update_persisted_channel`], which is provided
2268	/// with a monitor and an update. Once revoked, signing a justice transaction can be done using
2269	/// [`Self::sign_to_local_justice_tx`].
2270	///
2271	/// It is expected that a watchtower client may use this method to retrieve the latest counterparty
2272	/// commitment transaction(s), and then hold the necessary data until a later update in which
2273	/// the monitor has been updated with the corresponding revocation data, at which point the
2274	/// monitor can sign the justice transaction.
2275	///
2276	/// This will only return a non-empty list for monitor updates that have been created after
2277	/// upgrading to LDK 0.0.117+. Note that no restriction lies on the monitors themselves, which
2278	/// may have been created prior to upgrading.
2279	///
2280	/// [`Persist::update_persisted_channel`]: crate::chain::chainmonitor::Persist::update_persisted_channel
2281	pub fn counterparty_commitment_txs_from_update(
2282		&self, update: &ChannelMonitorUpdate,
2283	) -> Vec<CommitmentTransaction> {
2284		self.inner.lock().unwrap().counterparty_commitment_txs_from_update(update)
2285	}
2286
2287	/// Wrapper around [`EcdsaChannelSigner::sign_justice_revoked_output`] to make
2288	/// signing the justice transaction easier for implementors of
2289	/// [`chain::chainmonitor::Persist`]. On success this method returns the provided transaction
2290	/// signing the input at `input_idx`. This method will only produce a valid signature for
2291	/// a transaction spending the `to_local` output of a commitment transaction, i.e. this cannot
2292	/// be used for revoked HTLC outputs.
2293	///
2294	/// `Value` is the value of the output being spent by the input at `input_idx`, committed
2295	/// in the BIP 143 signature.
2296	///
2297	/// This method will only succeed if this monitor has received the revocation secret for the
2298	/// provided `commitment_number`. If a commitment number is provided that does not correspond
2299	/// to the commitment transaction being revoked, this will return a signed transaction, but
2300	/// the signature will not be valid.
2301	///
2302	/// Note that due to splicing, this can also return an `Err` when the counterparty commitment
2303	/// this transaction is attempting to claim is no longer valid because the corresponding funding
2304	/// transaction was spliced.
2305	///
2306	/// [`EcdsaChannelSigner::sign_justice_revoked_output`]: crate::sign::ecdsa::EcdsaChannelSigner::sign_justice_revoked_output
2307	/// [`Persist`]: crate::chain::chainmonitor::Persist
2308	#[rustfmt::skip]
2309	pub fn sign_to_local_justice_tx(&self, justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64) -> Result<Transaction, ()> {
2310		self.inner.lock().unwrap().sign_to_local_justice_tx(justice_tx, input_idx, value, commitment_number)
2311	}
2312
2313	pub(crate) fn get_min_seen_secret(&self) -> u64 {
2314		self.inner.lock().unwrap().get_min_seen_secret()
2315	}
2316
2317	pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
2318		self.inner.lock().unwrap().get_cur_counterparty_commitment_number()
2319	}
2320
2321	pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
2322		self.inner.lock().unwrap().get_cur_holder_commitment_number()
2323	}
2324
2325	/// Fetches whether this monitor has marked the channel as closed and will refuse any further
2326	/// updates to the commitment transactions.
2327	///
2328	/// It can be marked closed in a few different ways, including via a
2329	/// [`ChannelMonitorUpdateStep::ChannelForceClosed`] or if the channel has been closed
2330	/// on-chain.
2331	pub(crate) fn no_further_updates_allowed(&self) -> bool {
2332		self.inner.lock().unwrap().no_further_updates_allowed()
2333	}
2334
2335	/// Gets the `node_id` of the counterparty for this channel.
2336	pub fn get_counterparty_node_id(&self) -> PublicKey {
2337		self.inner.lock().unwrap().counterparty_node_id
2338	}
2339
2340	/// You may use this to broadcast the latest local commitment transaction, either because
2341	/// a monitor update failed or because we've fallen behind (i.e. we've received proof that our
2342	/// counterparty side knows a revocation secret we gave them that they shouldn't know).
2343	///
2344	/// Broadcasting these transactions in this manner is UNSAFE, as they allow counterparty
2345	/// side to punish you. Nevertheless you may want to broadcast them if counterparty doesn't
2346	/// close channel with their commitment transaction after a substantial amount of time. Best
2347	/// may be to contact the other node operator out-of-band to coordinate other options available
2348	/// to you.
2349	///
2350	/// Note: For channels using manual funding broadcast (see
2351	/// [`crate::ln::channelmanager::ChannelManager::funding_transaction_generated_manual_broadcast`]),
2352	/// automatic broadcasts are suppressed until the funding transaction has been observed on-chain.
2353	/// Calling this method overrides that suppression and queues the latest holder commitment
2354	/// transaction for broadcast even if the funding has not yet been seen on-chain. This may result
2355	/// in unconfirmable transactions being broadcast or [`Event::BumpTransaction`] notifications for
2356	/// transactions that cannot be confirmed until the funding transaction is visible.
2357	///
2358	/// [`Event::BumpTransaction`]: crate::events::Event::BumpTransaction
2359	pub fn broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
2360		&self, broadcaster: &B, fee_estimator: &F, logger: &L,
2361	) where
2362		B::Target: BroadcasterInterface,
2363		F::Target: FeeEstimator,
2364		L::Target: Logger,
2365	{
2366		let mut inner = self.inner.lock().unwrap();
2367		let fee_estimator = LowerBoundedFeeEstimator::new(&**fee_estimator);
2368		let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2369
2370		inner.queue_latest_holder_commitment_txn_for_broadcast(
2371			broadcaster,
2372			&fee_estimator,
2373			&logger,
2374			false,
2375		);
2376	}
2377
2378	/// Unsafe test-only version of `broadcast_latest_holder_commitment_txn` used by our test framework
2379	/// to bypass HolderCommitmentTransaction state update lockdown after signature and generate
2380	/// revoked commitment transaction.
2381	#[cfg(any(test, feature = "_test_utils", feature = "unsafe_revoked_tx_signing"))]
2382	pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
2383	where
2384		L::Target: Logger,
2385	{
2386		let mut inner = self.inner.lock().unwrap();
2387		let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2388		inner.unsafe_get_latest_holder_commitment_txn(&logger)
2389	}
2390
2391	/// Processes transactions in a newly connected block, which may result in any of the following:
2392	/// - update the monitor's state against resolved HTLCs
2393	/// - punish the counterparty in the case of seeing a revoked commitment transaction
2394	/// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
2395	/// - detect settled outputs for later spending
2396	/// - schedule and bump any in-flight claims
2397	///
2398	/// Returns any new outputs to watch from `txdata`; after called, these are also included in
2399	/// [`get_outputs_to_watch`].
2400	///
2401	/// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
2402	#[rustfmt::skip]
2403	pub fn block_connected<B: Deref, F: Deref, L: Deref>(
2404		&self,
2405		header: &Header,
2406		txdata: &TransactionData,
2407		height: u32,
2408		broadcaster: B,
2409		fee_estimator: F,
2410		logger: &L,
2411	) -> Vec<TransactionOutputs>
2412	where
2413		B::Target: BroadcasterInterface,
2414		F::Target: FeeEstimator,
2415		L::Target: Logger,
2416	{
2417		let mut inner = self.inner.lock().unwrap();
2418		let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2419		inner.block_connected(
2420			header, txdata, height, broadcaster, fee_estimator, &logger)
2421	}
2422
2423	/// Determines if the disconnected block contained any transactions of interest and updates
2424	/// appropriately.
2425	pub fn blocks_disconnected<B: Deref, F: Deref, L: Deref>(
2426		&self, fork_point: BestBlock, broadcaster: B, fee_estimator: F, logger: &L,
2427	) where
2428		B::Target: BroadcasterInterface,
2429		F::Target: FeeEstimator,
2430		L::Target: Logger,
2431	{
2432		let mut inner = self.inner.lock().unwrap();
2433		let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2434		inner.blocks_disconnected(fork_point, broadcaster, fee_estimator, &logger)
2435	}
2436
2437	/// Processes transactions confirmed in a block with the given header and height, returning new
2438	/// outputs to watch. See [`block_connected`] for details.
2439	///
2440	/// Used instead of [`block_connected`] by clients that are notified of transactions rather than
2441	/// blocks. See [`chain::Confirm`] for calling expectations.
2442	///
2443	/// [`block_connected`]: Self::block_connected
2444	#[rustfmt::skip]
2445	pub fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
2446		&self,
2447		header: &Header,
2448		txdata: &TransactionData,
2449		height: u32,
2450		broadcaster: B,
2451		fee_estimator: F,
2452		logger: &L,
2453	) -> Vec<TransactionOutputs>
2454	where
2455		B::Target: BroadcasterInterface,
2456		F::Target: FeeEstimator,
2457		L::Target: Logger,
2458	{
2459		let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2460		let mut inner = self.inner.lock().unwrap();
2461		let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2462		inner.transactions_confirmed(
2463			header, txdata, height, broadcaster, &bounded_fee_estimator, &logger)
2464	}
2465
2466	/// Processes a transaction that was reorganized out of the chain.
2467	///
2468	/// Used instead of [`blocks_disconnected`] by clients that are notified of transactions rather
2469	/// than blocks. See [`chain::Confirm`] for calling expectations.
2470	///
2471	/// [`blocks_disconnected`]: Self::blocks_disconnected
2472	#[rustfmt::skip]
2473	pub fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
2474		&self,
2475		txid: &Txid,
2476		broadcaster: B,
2477		fee_estimator: F,
2478		logger: &L,
2479	) where
2480		B::Target: BroadcasterInterface,
2481		F::Target: FeeEstimator,
2482		L::Target: Logger,
2483	{
2484		let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2485		let mut inner = self.inner.lock().unwrap();
2486		let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2487		inner.transaction_unconfirmed(
2488			txid, broadcaster, &bounded_fee_estimator, &logger
2489		);
2490	}
2491
2492	/// Updates the monitor with the current best chain tip, returning new outputs to watch. See
2493	/// [`block_connected`] for details.
2494	///
2495	/// Used instead of [`block_connected`] by clients that are notified of transactions rather than
2496	/// blocks. See [`chain::Confirm`] for calling expectations.
2497	///
2498	/// [`block_connected`]: Self::block_connected
2499	#[rustfmt::skip]
2500	pub fn best_block_updated<B: Deref, F: Deref, L: Deref>(
2501		&self,
2502		header: &Header,
2503		height: u32,
2504		broadcaster: B,
2505		fee_estimator: F,
2506		logger: &L,
2507	) -> Vec<TransactionOutputs>
2508	where
2509		B::Target: BroadcasterInterface,
2510		F::Target: FeeEstimator,
2511		L::Target: Logger,
2512	{
2513		let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2514		let mut inner = self.inner.lock().unwrap();
2515		let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2516		inner.best_block_updated(
2517			header, height, broadcaster, &bounded_fee_estimator, &logger
2518		)
2519	}
2520
2521	/// Returns the set of txids that should be monitored for re-organization out of the chain.
2522	#[rustfmt::skip]
2523	pub fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
2524		let inner = self.inner.lock().unwrap();
2525		let mut txids: Vec<(Txid, u32, Option<BlockHash>)> = inner.onchain_events_awaiting_threshold_conf
2526			.iter()
2527			.map(|entry| (entry.txid, entry.height, entry.block_hash))
2528			.chain(inner.onchain_tx_handler.get_relevant_txids().into_iter())
2529			.collect();
2530		txids.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));
2531		txids.dedup_by_key(|(txid, _, _)| *txid);
2532		txids
2533	}
2534
2535	/// Gets the latest best block which was connected either via the [`chain::Listen`] or
2536	/// [`chain::Confirm`] interfaces.
2537	pub fn current_best_block(&self) -> BestBlock {
2538		self.inner.lock().unwrap().best_block.clone()
2539	}
2540
2541	/// Triggers rebroadcasts/fee-bumps of pending claims from a force-closed channel. This is
2542	/// crucial in preventing certain classes of pinning attacks, detecting substantial mempool
2543	/// feerate changes between blocks, and ensuring reliability if broadcasting fails. We recommend
2544	/// invoking this every 30 seconds, or lower if running in an environment with spotty
2545	/// connections, like on mobile.
2546	#[rustfmt::skip]
2547	pub fn rebroadcast_pending_claims<B: Deref, F: Deref, L: Deref>(
2548		&self, broadcaster: B, fee_estimator: F, logger: &L,
2549	)
2550	where
2551		B::Target: BroadcasterInterface,
2552		F::Target: FeeEstimator,
2553		L::Target: Logger,
2554	{
2555		let fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2556		let mut lock = self.inner.lock().unwrap();
2557		let inner = &mut *lock;
2558		let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2559		let current_height = inner.best_block.height;
2560		let conf_target = inner.closure_conf_target();
2561		inner.onchain_tx_handler.rebroadcast_pending_claims(
2562			current_height, FeerateStrategy::HighestOfPreviousOrNew, &broadcaster, conf_target,
2563			&inner.destination_script, &fee_estimator, &logger,
2564		);
2565	}
2566
2567	/// Returns true if the monitor has pending claim requests that are not fully confirmed yet.
2568	pub fn has_pending_claims(&self) -> bool {
2569		self.inner.lock().unwrap().onchain_tx_handler.has_pending_claims()
2570	}
2571
2572	/// Triggers rebroadcasts of pending claims from a force-closed channel after a transaction
2573	/// signature generation failure.
2574	#[rustfmt::skip]
2575	pub fn signer_unblocked<B: Deref, F: Deref, L: Deref>(
2576		&self, broadcaster: B, fee_estimator: F, logger: &L,
2577	)
2578	where
2579		B::Target: BroadcasterInterface,
2580		F::Target: FeeEstimator,
2581		L::Target: Logger,
2582	{
2583		let fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2584		let mut lock = self.inner.lock().unwrap();
2585		let inner = &mut *lock;
2586		let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2587		let current_height = inner.best_block.height;
2588		let conf_target = inner.closure_conf_target();
2589		inner.onchain_tx_handler.rebroadcast_pending_claims(
2590			current_height, FeerateStrategy::RetryPrevious, &broadcaster, conf_target,
2591			&inner.destination_script, &fee_estimator, &logger,
2592		);
2593	}
2594
2595	/// Returns the descriptors for relevant outputs (i.e., those that we can spend) within the
2596	/// transaction if they exist and the transaction has at least [`ANTI_REORG_DELAY`]
2597	/// confirmations. For [`SpendableOutputDescriptor::DelayedPaymentOutput`] descriptors to be
2598	/// returned, the transaction must have at least `max(ANTI_REORG_DELAY, to_self_delay)`
2599	/// confirmations.
2600	///
2601	/// Descriptors returned by this method are primarily exposed via [`Event::SpendableOutputs`]
2602	/// once they are no longer under reorg risk. This method serves as a way to retrieve these
2603	/// descriptors at a later time, either for historical purposes, or to replay any
2604	/// missed/unhandled descriptors. For the purpose of gathering historical records, if the
2605	/// channel close has fully resolved (i.e., [`ChannelMonitor::get_claimable_balances`] returns
2606	/// an empty set), you can retrieve all spendable outputs by providing all descendant spending
2607	/// transactions starting from the channel's funding transaction and going down three levels.
2608	///
2609	/// `tx` is a transaction we'll scan the outputs of. Any transaction can be provided. If any
2610	/// outputs which can be spent by us are found, at least one descriptor is returned.
2611	///
2612	/// `confirmation_height` must be the height of the block in which `tx` was included in.
2613	#[rustfmt::skip]
2614	pub fn get_spendable_outputs(&self, tx: &Transaction, confirmation_height: u32) -> Vec<SpendableOutputDescriptor> {
2615		let inner = self.inner.lock().unwrap();
2616		let current_height = inner.best_block.height;
2617		let funding = get_confirmed_funding_scope!(inner);
2618		let mut spendable_outputs = inner.get_spendable_outputs(&funding, tx);
2619		spendable_outputs.retain(|descriptor| {
2620			let mut conf_threshold = current_height.saturating_sub(ANTI_REORG_DELAY) + 1;
2621			if let SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) = descriptor {
2622				conf_threshold = cmp::min(conf_threshold,
2623					current_height.saturating_sub(descriptor.to_self_delay as u32) + 1);
2624			}
2625			conf_threshold >= confirmation_height
2626		});
2627		spendable_outputs
2628	}
2629
2630	/// Checks if the monitor is fully resolved. Resolved monitor is one that has claimed all of
2631	/// its outputs and balances (i.e. [`Self::get_claimable_balances`] returns an empty set) and
2632	/// which does not have any payment preimages for HTLCs which are still pending on other
2633	/// channels.
2634	///
2635	/// Additionally may update state to track when the balances set became empty.
2636	///
2637	/// This function returns a tuple of two booleans, the first indicating whether the monitor is
2638	/// fully resolved, and the second whether the monitor needs persistence to ensure it is
2639	/// reliably marked as resolved within [`ARCHIVAL_DELAY_BLOCKS`] blocks.
2640	///
2641	/// The first boolean is true only if [`Self::get_claimable_balances`] has been empty for at
2642	/// least [`ARCHIVAL_DELAY_BLOCKS`] blocks as an additional protection against any bugs
2643	/// resulting in spuriously empty balance sets.
2644	#[rustfmt::skip]
2645	pub fn check_and_update_full_resolution_status<L: Logger>(&self, logger: &L) -> (bool, bool) {
2646		let mut is_all_funds_claimed = self.get_claimable_balances().is_empty();
2647		let current_height = self.current_best_block().height;
2648		let mut inner = self.inner.lock().unwrap();
2649
2650		if inner.is_closed_without_updates()
2651			&& is_all_funds_claimed
2652			&& !inner.funding_spend_seen
2653		{
2654			// We closed the channel without ever advancing it and didn't have any funds in it.
2655			// We should immediately archive this monitor as there's nothing for us to ever do with
2656			// it.
2657			return (true, false);
2658		}
2659
2660		if is_all_funds_claimed && !inner.funding_spend_seen {
2661			debug_assert!(false, "We should see funding spend by the time a monitor clears out");
2662			is_all_funds_claimed = false;
2663		}
2664
2665		// As long as HTLCs remain unresolved, they'll be present as a `Balance`. After that point,
2666		// if they contained a preimage, an event will appear in `pending_monitor_events` which,
2667		// once processed, implies the preimage exists in the corresponding inbound channel.
2668		let preimages_not_needed_elsewhere = inner.pending_monitor_events.is_empty();
2669
2670		match (inner.balances_empty_height, is_all_funds_claimed, preimages_not_needed_elsewhere) {
2671			(Some(balances_empty_height), true, true) => {
2672				// Claimed all funds, check if reached the blocks threshold.
2673				(current_height >= balances_empty_height + ARCHIVAL_DELAY_BLOCKS, false)
2674			},
2675			(Some(_), false, _)|(Some(_), _, false) => {
2676				// previously assumed we claimed all funds, but we have new funds to claim or
2677				// preimages are suddenly needed (because of a duplicate-hash HTLC).
2678				// This should never happen as once the `Balance`s and preimages are clear, we
2679				// should never create new ones.
2680				debug_assert!(false,
2681					"Thought we were done claiming funds, but claimable_balances now has entries");
2682				log_error!(logger,
2683					"WARNING: LDK thought it was done claiming all the available funds in the ChannelMonitor for channel {}, but later decided it had more to claim. This is potentially an important bug in LDK, please report it at https://github.com/lightningdevkit/rust-lightning/issues/new",
2684					inner.get_funding_txo());
2685				inner.balances_empty_height = None;
2686				(false, true)
2687			},
2688			(None, true, true) => {
2689				// Claimed all funds and preimages can be deleted, but `balances_empty_height` is
2690				// None. It is set to the current block height.
2691				log_debug!(logger,
2692					"ChannelMonitor funded at {} is now fully resolved. It will become archivable in {} blocks",
2693					inner.get_funding_txo(), ARCHIVAL_DELAY_BLOCKS);
2694				inner.balances_empty_height = Some(current_height);
2695				(false, true)
2696			},
2697			(None, false, _)|(None, _, false) => {
2698				// Have funds to claim or our preimages are still needed.
2699				(false, false)
2700			},
2701		}
2702	}
2703
2704	#[cfg(test)]
2705	pub fn get_counterparty_payment_script(&self) -> ScriptBuf {
2706		self.inner.lock().unwrap().counterparty_payment_script.clone()
2707	}
2708
2709	#[cfg(test)]
2710	pub fn set_counterparty_payment_script(&self, script: ScriptBuf) {
2711		self.inner.lock().unwrap().counterparty_payment_script = script;
2712	}
2713
2714	#[cfg(any(test, feature = "_test_utils"))]
2715	pub fn do_mut_signer_call<F: FnMut(&mut Signer) -> ()>(&self, mut f: F) {
2716		let mut inner = self.inner.lock().unwrap();
2717		f(&mut inner.onchain_tx_handler.signer);
2718	}
2719}
2720
2721impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
2722	/// Helper for get_claimable_balances which does the work for an individual HTLC, generating up
2723	/// to one `Balance` for the HTLC.
2724	#[rustfmt::skip]
2725	fn get_htlc_balance(&self, htlc: &HTLCOutputInCommitment, source: Option<&HTLCSource>,
2726		holder_commitment: bool, counterparty_revoked_commitment: bool,
2727		confirmed_txid: Option<Txid>
2728	) -> Option<Balance> {
2729		let htlc_commitment_tx_output_idx = htlc.transaction_output_index?;
2730
2731		let mut htlc_spend_txid_opt = None;
2732		let mut htlc_spend_tx_opt = None;
2733		let mut holder_timeout_spend_pending = None;
2734		let mut htlc_spend_pending = None;
2735		let mut holder_delayed_output_pending = None;
2736		for event in self.onchain_events_awaiting_threshold_conf.iter() {
2737			match event.event {
2738				OnchainEvent::HTLCUpdate { commitment_tx_output_idx, htlc_value_satoshis, .. }
2739				if commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) => {
2740					debug_assert!(htlc_spend_txid_opt.is_none());
2741					htlc_spend_txid_opt = Some(&event.txid);
2742					debug_assert!(htlc_spend_tx_opt.is_none());
2743					htlc_spend_tx_opt = event.transaction.as_ref();
2744					debug_assert!(holder_timeout_spend_pending.is_none());
2745					debug_assert_eq!(htlc_value_satoshis.unwrap(), htlc.amount_msat / 1000);
2746					holder_timeout_spend_pending = Some(event.confirmation_threshold());
2747				},
2748				OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. }
2749				if commitment_tx_output_idx == htlc_commitment_tx_output_idx => {
2750					debug_assert!(htlc_spend_txid_opt.is_none());
2751					htlc_spend_txid_opt = Some(&event.txid);
2752					debug_assert!(htlc_spend_tx_opt.is_none());
2753					htlc_spend_tx_opt = event.transaction.as_ref();
2754					debug_assert!(htlc_spend_pending.is_none());
2755					htlc_spend_pending = Some((event.confirmation_threshold(), preimage.is_some()));
2756				},
2757				OnchainEvent::MaturingOutput {
2758					descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor) }
2759				if event.transaction.as_ref().map(|tx| tx.input.iter().enumerate()
2760					.any(|(input_idx, inp)|
2761						 Some(inp.previous_output.txid) == confirmed_txid &&
2762							inp.previous_output.vout == htlc_commitment_tx_output_idx &&
2763								// A maturing output for an HTLC claim will always be at the same
2764								// index as the HTLC input. This is true pre-anchors, as there's
2765								// only 1 input and 1 output. This is also true post-anchors,
2766								// because we have a SIGHASH_SINGLE|ANYONECANPAY signature from our
2767								// channel counterparty.
2768								descriptor.outpoint.index as usize == input_idx
2769					))
2770					.unwrap_or(false)
2771				=> {
2772					debug_assert!(holder_delayed_output_pending.is_none());
2773					holder_delayed_output_pending = Some(event.confirmation_threshold());
2774				},
2775				_ => {},
2776			}
2777		}
2778		let htlc_resolved = self.htlcs_resolved_on_chain.iter()
2779			.any(|v| if v.commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) {
2780				debug_assert!(htlc_spend_txid_opt.is_none());
2781				htlc_spend_txid_opt = v.resolving_txid.as_ref();
2782				debug_assert!(htlc_spend_tx_opt.is_none());
2783				htlc_spend_tx_opt = v.resolving_tx.as_ref();
2784				true
2785			} else { false });
2786		debug_assert!(holder_timeout_spend_pending.is_some() as u8 + htlc_spend_pending.is_some() as u8 + htlc_resolved as u8 <= 1);
2787
2788		let htlc_commitment_outpoint = BitcoinOutPoint::new(confirmed_txid.unwrap(), htlc_commitment_tx_output_idx);
2789		let htlc_output_to_spend =
2790			if let Some(txid) = htlc_spend_txid_opt {
2791				// Because HTLC transactions either only have 1 input and 1 output (pre-anchors) or
2792				// are signed with SIGHASH_SINGLE|ANYONECANPAY under BIP-0143 (post-anchors), we can
2793				// locate the correct output by ensuring its adjacent input spends the HTLC output
2794				// in the commitment.
2795				if let Some(ref tx) = htlc_spend_tx_opt {
2796					let htlc_input_idx_opt = tx.input.iter().enumerate()
2797						.find(|(_, input)| input.previous_output == htlc_commitment_outpoint)
2798						.map(|(idx, _)| idx as u32);
2799					debug_assert!(htlc_input_idx_opt.is_some());
2800					BitcoinOutPoint::new(*txid, htlc_input_idx_opt.unwrap_or(0))
2801				} else {
2802					let funding = get_confirmed_funding_scope!(self);
2803					debug_assert!(!funding.channel_type_features().supports_anchors_zero_fee_htlc_tx());
2804					debug_assert!(!funding.channel_type_features().supports_anchor_zero_fee_commitments());
2805					BitcoinOutPoint::new(*txid, 0)
2806				}
2807			} else {
2808				htlc_commitment_outpoint
2809			};
2810		let htlc_output_spend_pending = self.onchain_tx_handler.is_output_spend_pending(&htlc_output_to_spend);
2811
2812		if let Some(conf_thresh) = holder_delayed_output_pending {
2813			debug_assert!(holder_commitment);
2814			return Some(Balance::ClaimableAwaitingConfirmations {
2815				amount_satoshis: htlc.amount_msat / 1000,
2816				confirmation_height: conf_thresh,
2817				source: BalanceSource::Htlc,
2818			});
2819		} else if htlc_resolved && !htlc_output_spend_pending {
2820			// Funding transaction spends should be fully confirmed by the time any
2821			// HTLC transactions are resolved, unless we're talking about a holder
2822			// commitment tx, whose resolution is delayed until the CSV timeout is
2823			// reached, even though HTLCs may be resolved after only
2824			// ANTI_REORG_DELAY confirmations.
2825			debug_assert!(holder_commitment || self.funding_spend_confirmed.is_some());
2826		} else if counterparty_revoked_commitment {
2827			let htlc_output_claim_pending = self.onchain_events_awaiting_threshold_conf.iter().any(|event| {
2828				if let OnchainEvent::MaturingOutput {
2829					descriptor: SpendableOutputDescriptor::StaticOutput { .. }
2830				} = &event.event {
2831					event.transaction.as_ref().map(|tx| tx.input.iter().any(|inp| {
2832						if let Some(htlc_spend_txid) = htlc_spend_txid_opt {
2833							tx.compute_txid() == *htlc_spend_txid || inp.previous_output.txid == *htlc_spend_txid
2834						} else {
2835							Some(inp.previous_output.txid) == confirmed_txid &&
2836								inp.previous_output.vout == htlc_commitment_tx_output_idx
2837						}
2838					})).unwrap_or(false)
2839				} else {
2840					false
2841				}
2842			});
2843			if htlc_output_claim_pending {
2844				// We already push `Balance`s onto the `res` list for every
2845				// `StaticOutput` in a `MaturingOutput` in the revoked
2846				// counterparty commitment transaction case generally, so don't
2847				// need to do so again here.
2848			} else {
2849				debug_assert!(holder_timeout_spend_pending.is_none(),
2850					"HTLCUpdate OnchainEvents should never appear for preimage claims");
2851				debug_assert!(!htlc.offered || htlc_spend_pending.is_none() || !htlc_spend_pending.unwrap().1,
2852					"We don't (currently) generate preimage claims against revoked outputs, where did you get one?!");
2853				return Some(Balance::CounterpartyRevokedOutputClaimable {
2854					amount_satoshis: htlc.amount_msat / 1000,
2855				});
2856			}
2857		} else if htlc.offered == holder_commitment {
2858			// If the payment was outbound, check if there's an HTLCUpdate
2859			// indicating we have spent this HTLC with a timeout, claiming it back
2860			// and awaiting confirmations on it.
2861			if let Some(conf_thresh) = holder_timeout_spend_pending {
2862				return Some(Balance::ClaimableAwaitingConfirmations {
2863					amount_satoshis: htlc.amount_msat / 1000,
2864					confirmation_height: conf_thresh,
2865					source: BalanceSource::Htlc,
2866				});
2867			} else {
2868				let outbound_payment = match source {
2869					None => panic!("Outbound HTLCs should have a source"),
2870					Some(&HTLCSource::PreviousHopData(_)) => false,
2871					Some(&HTLCSource::OutboundRoute { .. }) => true,
2872				};
2873				return Some(Balance::MaybeTimeoutClaimableHTLC {
2874					amount_satoshis: htlc.amount_msat / 1000,
2875					claimable_height: htlc.cltv_expiry,
2876					payment_hash: htlc.payment_hash,
2877					outbound_payment,
2878				});
2879			}
2880		} else if let Some((payment_preimage, _)) = self.payment_preimages.get(&htlc.payment_hash) {
2881			// Otherwise (the payment was inbound), only expose it as claimable if
2882			// we know the preimage.
2883			// Note that if there is a pending claim, but it did not use the
2884			// preimage, we lost funds to our counterparty! We will then continue
2885			// to show it as ContentiousClaimable until ANTI_REORG_DELAY.
2886			debug_assert!(holder_timeout_spend_pending.is_none());
2887			if let Some((conf_thresh, true)) = htlc_spend_pending {
2888				return Some(Balance::ClaimableAwaitingConfirmations {
2889					amount_satoshis: htlc.amount_msat / 1000,
2890					confirmation_height: conf_thresh,
2891					source: BalanceSource::Htlc,
2892				});
2893			} else {
2894				return Some(Balance::ContentiousClaimable {
2895					amount_satoshis: htlc.amount_msat / 1000,
2896					timeout_height: htlc.cltv_expiry,
2897					payment_hash: htlc.payment_hash,
2898					payment_preimage: *payment_preimage,
2899				});
2900			}
2901		} else if !htlc_resolved {
2902			return Some(Balance::MaybePreimageClaimableHTLC {
2903				amount_satoshis: htlc.amount_msat / 1000,
2904				expiry_height: htlc.cltv_expiry,
2905				payment_hash: htlc.payment_hash,
2906			});
2907		}
2908		None
2909	}
2910}
2911
2912impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
2913	/// Gets the balances in this channel which are either claimable by us if we were to
2914	/// force-close the channel now or which are claimable on-chain (possibly awaiting
2915	/// confirmation).
2916	///
2917	/// Any balances in the channel which are available on-chain (excluding on-chain fees) are
2918	/// included here until an [`Event::SpendableOutputs`] event has been generated for the
2919	/// balance, or until our counterparty has claimed the balance and accrued several
2920	/// confirmations on the claim transaction.
2921	///
2922	/// Note that for `ChannelMonitors` which track a channel which went on-chain with versions of
2923	/// LDK prior to 0.0.111, not all or excess balances may be included.
2924	///
2925	/// See [`Balance`] for additional details on the types of claimable balances which
2926	/// may be returned here and their meanings.
2927	#[rustfmt::skip]
2928	pub fn get_claimable_balances(&self) -> Vec<Balance> {
2929		let mut res = Vec::new();
2930		let us = self.inner.lock().unwrap();
2931
2932		let mut confirmed_txid = us.funding_spend_confirmed;
2933		let mut confirmed_counterparty_output = us.confirmed_commitment_tx_counterparty_output;
2934		let mut pending_commitment_tx_conf_thresh = None;
2935		let funding_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2936			if let OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } =
2937				event.event
2938			{
2939				confirmed_counterparty_output = commitment_tx_to_counterparty_output;
2940				Some((event.txid, event.confirmation_threshold()))
2941			} else { None }
2942		});
2943		if let Some((txid, conf_thresh)) = funding_spend_pending {
2944			debug_assert!(us.funding_spend_confirmed.is_none(),
2945				"We have a pending funding spend awaiting anti-reorg confirmation, we can't have confirmed it already!");
2946			confirmed_txid = Some(txid);
2947			pending_commitment_tx_conf_thresh = Some(conf_thresh);
2948		}
2949
2950		macro_rules! walk_htlcs {
2951			($holder_commitment: expr, $counterparty_revoked_commitment: expr, $htlc_iter: expr) => {
2952				for (htlc, source) in $htlc_iter {
2953					if htlc.transaction_output_index.is_some() {
2954
2955						if let Some(bal) = us.get_htlc_balance(
2956							htlc, source, $holder_commitment, $counterparty_revoked_commitment, confirmed_txid
2957						) {
2958							res.push(bal);
2959						}
2960					}
2961				}
2962			}
2963		}
2964
2965		if let Some(txid) = confirmed_txid {
2966			let funding_spent = get_confirmed_funding_scope!(us);
2967			let mut found_commitment_tx = false;
2968			if let Some(counterparty_tx_htlcs) = funding_spent.counterparty_claimable_outpoints.get(&txid) {
2969				// First look for the to_remote output back to us.
2970				if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2971					if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2972						if let OnchainEvent::MaturingOutput {
2973							descriptor: SpendableOutputDescriptor::StaticPaymentOutput(descriptor)
2974						} = &event.event {
2975							Some(descriptor.output.value)
2976						} else { None }
2977					}) {
2978						res.push(Balance::ClaimableAwaitingConfirmations {
2979							amount_satoshis: value.to_sat(),
2980							confirmation_height: conf_thresh,
2981							source: BalanceSource::CounterpartyForceClosed,
2982						});
2983					} else {
2984						// If a counterparty commitment transaction is awaiting confirmation, we
2985						// should either have a StaticPaymentOutput MaturingOutput event awaiting
2986						// confirmation with the same height or have never met our dust amount.
2987					}
2988				}
2989				if Some(txid) == funding_spent.current_counterparty_commitment_txid || Some(txid) == funding_spent.prev_counterparty_commitment_txid {
2990					walk_htlcs!(false, false, counterparty_tx_htlcs.iter().map(|(a, b)| (a, b.as_ref().map(|b| &**b))));
2991				} else {
2992					walk_htlcs!(false, true, counterparty_tx_htlcs.iter().map(|(a, b)| (a, b.as_ref().map(|b| &**b))));
2993					// The counterparty broadcasted a revoked state!
2994					// Look for any StaticOutputs first, generating claimable balances for those.
2995					// If any match the confirmed counterparty revoked to_self output, skip
2996					// generating a CounterpartyRevokedOutputClaimable.
2997					let mut spent_counterparty_output = false;
2998					for event in us.onchain_events_awaiting_threshold_conf.iter() {
2999						if let OnchainEvent::MaturingOutput {
3000							descriptor: SpendableOutputDescriptor::StaticOutput { output, .. }
3001						} = &event.event {
3002							res.push(Balance::ClaimableAwaitingConfirmations {
3003								amount_satoshis: output.value.to_sat(),
3004								confirmation_height: event.confirmation_threshold(),
3005								source: BalanceSource::CounterpartyForceClosed,
3006							});
3007							if let Some(confirmed_to_self_idx) = confirmed_counterparty_output.map(|(idx, _)| idx) {
3008								if event.transaction.as_ref().map(|tx|
3009									tx.input.iter().any(|inp| inp.previous_output.vout == confirmed_to_self_idx)
3010								).unwrap_or(false) {
3011									spent_counterparty_output = true;
3012								}
3013							}
3014						}
3015					}
3016
3017					if spent_counterparty_output {
3018					} else if let Some((confirmed_to_self_idx, amt)) = confirmed_counterparty_output {
3019						let output_spendable = us.onchain_tx_handler
3020							.is_output_spend_pending(&BitcoinOutPoint::new(txid, confirmed_to_self_idx));
3021						if output_spendable {
3022							res.push(Balance::CounterpartyRevokedOutputClaimable {
3023								amount_satoshis: amt.to_sat(),
3024							});
3025						}
3026					} else {
3027						// Counterparty output is missing, either it was broadcasted on a
3028						// previous version of LDK or the counterparty hadn't met dust.
3029					}
3030				}
3031				found_commitment_tx = true;
3032			} else if txid == funding_spent.current_holder_commitment_tx.trust().txid() {
3033				walk_htlcs!(true, false, holder_commitment_htlcs!(us, CURRENT_WITH_SOURCES));
3034				if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
3035					res.push(Balance::ClaimableAwaitingConfirmations {
3036						amount_satoshis: funding_spent.current_holder_commitment_tx.to_broadcaster_value_sat(),
3037						confirmation_height: conf_thresh,
3038						source: BalanceSource::HolderForceClosed,
3039					});
3040				}
3041				found_commitment_tx = true;
3042			} else if let Some(prev_holder_commitment_tx) = &funding_spent.prev_holder_commitment_tx {
3043				if txid == prev_holder_commitment_tx.trust().txid() {
3044					walk_htlcs!(true, false, holder_commitment_htlcs!(us, PREV_WITH_SOURCES).unwrap());
3045					if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
3046						res.push(Balance::ClaimableAwaitingConfirmations {
3047							amount_satoshis: prev_holder_commitment_tx.to_broadcaster_value_sat(),
3048							confirmation_height: conf_thresh,
3049							source: BalanceSource::HolderForceClosed,
3050						});
3051					}
3052					found_commitment_tx = true;
3053				}
3054			}
3055			if !found_commitment_tx {
3056				if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
3057					// We blindly assume this is a cooperative close transaction here, and that
3058					// neither us nor our counterparty misbehaved. At worst we've under-estimated
3059					// the amount we can claim as we'll punish a misbehaving counterparty.
3060					res.push(Balance::ClaimableAwaitingConfirmations {
3061						amount_satoshis: funding_spent.current_holder_commitment_tx.to_broadcaster_value_sat(),
3062						confirmation_height: conf_thresh,
3063						source: BalanceSource::CoopClose,
3064					});
3065				}
3066			}
3067		} else {
3068			let mut claimable_inbound_htlc_value_sat = 0;
3069			let mut outbound_payment_htlc_rounded_msat = 0;
3070			let mut outbound_forwarded_htlc_rounded_msat = 0;
3071			let mut inbound_claiming_htlc_rounded_msat = 0;
3072			let mut inbound_htlc_rounded_msat = 0;
3073			// We share the same set of HTLCs across all scopes, so we don't need to check the other
3074			// scopes as it'd be redundant.
3075			for (htlc, source) in holder_commitment_htlcs!(us, CURRENT_WITH_SOURCES) {
3076				let rounded_value_msat = if htlc.transaction_output_index.is_none() {
3077					htlc.amount_msat
3078				} else { htlc.amount_msat % 1000 };
3079				if htlc.offered {
3080					let outbound_payment = match source {
3081						None => panic!("Outbound HTLCs should have a source"),
3082						Some(HTLCSource::PreviousHopData(_)) => false,
3083						Some(HTLCSource::OutboundRoute { .. }) => true,
3084					};
3085					if outbound_payment {
3086						outbound_payment_htlc_rounded_msat += rounded_value_msat;
3087					} else {
3088						outbound_forwarded_htlc_rounded_msat += rounded_value_msat;
3089					}
3090					if htlc.transaction_output_index.is_some() {
3091						res.push(Balance::MaybeTimeoutClaimableHTLC {
3092							amount_satoshis: htlc.amount_msat / 1000,
3093							claimable_height: htlc.cltv_expiry,
3094							payment_hash: htlc.payment_hash,
3095							outbound_payment,
3096						});
3097					}
3098				} else if us.payment_preimages.contains_key(&htlc.payment_hash) {
3099					inbound_claiming_htlc_rounded_msat += rounded_value_msat;
3100					if htlc.transaction_output_index.is_some() {
3101						claimable_inbound_htlc_value_sat += htlc.amount_msat / 1000;
3102					}
3103				} else {
3104					inbound_htlc_rounded_msat += rounded_value_msat;
3105					if htlc.transaction_output_index.is_some() {
3106						// As long as the HTLC is still in our latest commitment state, treat
3107						// it as potentially claimable, even if it has long-since expired.
3108						res.push(Balance::MaybePreimageClaimableHTLC {
3109							amount_satoshis: htlc.amount_msat / 1000,
3110							expiry_height: htlc.cltv_expiry,
3111							payment_hash: htlc.payment_hash,
3112						});
3113					}
3114				}
3115			}
3116			let balance_candidates = core::iter::once(&us.funding)
3117				.chain(us.pending_funding.iter())
3118				.map(|funding| {
3119					let to_self_value_sat = funding.current_holder_commitment_tx.to_broadcaster_value_sat();
3120					// In addition to `commit_tx_fee_sat`, this can also include dust HTLCs, any
3121					// elided anchors, and the total msat amount rounded down from non-dust HTLCs.
3122					let transaction_fee_satoshis = if us.holder_pays_commitment_tx_fee.unwrap_or(true) {
3123						let transaction = &funding.current_holder_commitment_tx.trust().built_transaction().transaction;
3124						let output_value_sat: u64 = transaction.output.iter().map(|txout| txout.value.to_sat()).sum();
3125						funding.channel_parameters.channel_value_satoshis - output_value_sat
3126					} else {
3127						0
3128					};
3129					HolderCommitmentTransactionBalance {
3130						amount_satoshis: to_self_value_sat + claimable_inbound_htlc_value_sat,
3131						transaction_fee_satoshis,
3132					}
3133				})
3134				.collect::<Vec<_>>();
3135			let confirmed_balance_candidate_index = core::iter::once(&us.funding)
3136				.chain(us.pending_funding.iter())
3137				.enumerate()
3138				.find(|(_, funding)| {
3139					us.alternative_funding_confirmed
3140						.map(|(funding_txid_confirmed, _)| funding.funding_txid() == funding_txid_confirmed)
3141						// If `alternative_funding_confirmed` is not set, we can assume the current
3142						// funding is confirmed.
3143						.unwrap_or(true)
3144				})
3145				.map(|(idx, _)| idx)
3146				.expect("We must have one FundingScope that is confirmed");
3147
3148			// Only push a primary balance if either the channel isn't closed or we've advanced the
3149			// channel state machine at least once (implying there are multiple previous commitment
3150			// transactions) or we actually have a balance.
3151			// Avoiding including a `Balance` if none of these are true allows us to prune monitors
3152			// for chanels that were opened inbound to us but where the funding transaction never
3153			// confirmed at all.
3154			if !us.is_closed_without_updates()
3155				|| balance_candidates.iter().any(|bal| bal.amount_satoshis != 0)
3156			{
3157				res.push(Balance::ClaimableOnChannelClose {
3158					balance_candidates,
3159					confirmed_balance_candidate_index,
3160					outbound_payment_htlc_rounded_msat,
3161					outbound_forwarded_htlc_rounded_msat,
3162					inbound_claiming_htlc_rounded_msat,
3163					inbound_htlc_rounded_msat,
3164				});
3165			}
3166		}
3167
3168		res
3169	}
3170
3171	/// Gets the set of outbound HTLCs which can be (or have been) resolved by this
3172	/// `ChannelMonitor`. This is used to determine if an HTLC was removed from the channel prior
3173	/// to the `ChannelManager` having been persisted.
3174	pub(crate) fn get_all_current_outbound_htlcs(
3175		&self,
3176	) -> HashMap<HTLCSource, (HTLCOutputInCommitment, Option<PaymentPreimage>)> {
3177		let mut res = new_hash_map();
3178		// Just examine the available counterparty commitment transactions. See docs on
3179		// `fail_unbroadcast_htlcs`, below, for justification.
3180		let us = self.inner.lock().unwrap();
3181		let mut walk_counterparty_commitment = |txid| {
3182			if let Some(latest_outpoints) = us.funding.counterparty_claimable_outpoints.get(txid) {
3183				for &(ref htlc, ref source_option) in latest_outpoints.iter() {
3184					if let &Some(ref source) = source_option {
3185						let htlc_id = SentHTLCId::from_source(source);
3186						if !us.htlcs_resolved_to_user.contains(&htlc_id) {
3187							let preimage_opt =
3188								us.counterparty_fulfilled_htlcs.get(&htlc_id).cloned();
3189							res.insert((**source).clone(), (htlc.clone(), preimage_opt));
3190						}
3191					}
3192				}
3193			}
3194		};
3195		if let Some(ref txid) = us.funding.current_counterparty_commitment_txid {
3196			walk_counterparty_commitment(txid);
3197		}
3198		if let Some(ref txid) = us.funding.prev_counterparty_commitment_txid {
3199			walk_counterparty_commitment(txid);
3200		}
3201		res
3202	}
3203
3204	/// Gets the set of outbound HTLCs which hit the chain and ultimately were claimed by us via
3205	/// the timeout path and reached [`ANTI_REORG_DELAY`] confirmations. This is used to determine
3206	/// if an HTLC has failed without the `ChannelManager` having seen it prior to being persisted.
3207	pub(crate) fn get_onchain_failed_outbound_htlcs(&self) -> HashMap<HTLCSource, PaymentHash> {
3208		let mut res = new_hash_map();
3209		let us = self.inner.lock().unwrap();
3210
3211		// We only want HTLCs with ANTI_REORG_DELAY confirmations, which implies the commitment
3212		// transaction has least ANTI_REORG_DELAY confirmations for any dependent HTLC transactions
3213		// to have been confirmed.
3214		let confirmed_txid = us.funding_spend_confirmed.or_else(|| {
3215			us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
3216				if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
3217					if event.height + ANTI_REORG_DELAY - 1 <= us.best_block.height {
3218						Some(event.txid)
3219					} else {
3220						None
3221					}
3222				} else {
3223					None
3224				}
3225			})
3226		});
3227
3228		let confirmed_txid = if let Some(txid) = confirmed_txid {
3229			txid
3230		} else {
3231			return res;
3232		};
3233
3234		macro_rules! walk_htlcs {
3235			($htlc_iter: expr) => {
3236				let mut walk_candidate_htlcs = |htlcs| {
3237					for &(ref candidate_htlc, ref candidate_source) in htlcs {
3238						let candidate_htlc: &HTLCOutputInCommitment = &candidate_htlc;
3239						let candidate_source: &Option<Box<HTLCSource>> = &candidate_source;
3240
3241						let source: &HTLCSource = if let Some(source) = candidate_source {
3242							source
3243						} else {
3244							continue;
3245						};
3246						let htlc_id = SentHTLCId::from_source(source);
3247						if us.htlcs_resolved_to_user.contains(&htlc_id) {
3248							continue;
3249						}
3250
3251						let confirmed = $htlc_iter.find(|(_, conf_src)| Some(source) == *conf_src);
3252						if let Some((confirmed_htlc, _)) = confirmed {
3253							let filter = |v: &&IrrevocablyResolvedHTLC| {
3254								v.commitment_tx_output_idx
3255									== confirmed_htlc.transaction_output_index
3256							};
3257
3258							// The HTLC was included in the confirmed commitment transaction, so we
3259							// need to see if it has been irrevocably failed yet.
3260							if confirmed_htlc.transaction_output_index.is_none() {
3261								// Dust HTLCs are always implicitly failed once the commitment
3262								// transaction reaches ANTI_REORG_DELAY confirmations.
3263								res.insert(source.clone(), confirmed_htlc.payment_hash);
3264							} else if let Some(state) =
3265								us.htlcs_resolved_on_chain.iter().filter(filter).next()
3266							{
3267								if state.payment_preimage.is_none() {
3268									res.insert(source.clone(), confirmed_htlc.payment_hash);
3269								}
3270							}
3271						} else {
3272							// The HTLC was not included in the confirmed commitment transaction,
3273							// which has now reached ANTI_REORG_DELAY confirmations and thus the
3274							// HTLC has been failed.
3275							res.insert(source.clone(), candidate_htlc.payment_hash);
3276						}
3277					}
3278				};
3279
3280				// We walk the set of HTLCs in the unrevoked counterparty commitment transactions (see
3281				// `fail_unbroadcast_htlcs` for a description of why).
3282				if let Some(ref txid) = us.funding.current_counterparty_commitment_txid {
3283					let htlcs = us.funding.counterparty_claimable_outpoints.get(txid);
3284					walk_candidate_htlcs(htlcs.expect("Missing tx info for latest tx"));
3285				}
3286				if let Some(ref txid) = us.funding.prev_counterparty_commitment_txid {
3287					let htlcs = us.funding.counterparty_claimable_outpoints.get(txid);
3288					walk_candidate_htlcs(htlcs.expect("Missing tx info for previous tx"));
3289				}
3290			};
3291		}
3292
3293		let funding = get_confirmed_funding_scope!(us);
3294
3295		if Some(confirmed_txid) == funding.current_counterparty_commitment_txid
3296			|| Some(confirmed_txid) == funding.prev_counterparty_commitment_txid
3297		{
3298			let htlcs = funding.counterparty_claimable_outpoints.get(&confirmed_txid).unwrap();
3299			walk_htlcs!(htlcs.iter().filter_map(|(a, b)| {
3300				if let &Some(ref source) = b {
3301					Some((a, Some(&**source)))
3302				} else {
3303					None
3304				}
3305			}));
3306		} else if confirmed_txid == funding.current_holder_commitment_tx.trust().txid() {
3307			walk_htlcs!(holder_commitment_htlcs!(us, CURRENT_WITH_SOURCES));
3308		} else if let Some(prev_commitment_tx) = &funding.prev_holder_commitment_tx {
3309			if confirmed_txid == prev_commitment_tx.trust().txid() {
3310				walk_htlcs!(holder_commitment_htlcs!(us, PREV_WITH_SOURCES).unwrap());
3311			} else {
3312				let htlcs_confirmed: &[(&HTLCOutputInCommitment, _)] = &[];
3313				walk_htlcs!(htlcs_confirmed.iter());
3314			}
3315		} else {
3316			let htlcs_confirmed: &[(&HTLCOutputInCommitment, _)] = &[];
3317			walk_htlcs!(htlcs_confirmed.iter());
3318		}
3319
3320		res
3321	}
3322
3323	pub(crate) fn get_stored_preimages(
3324		&self,
3325	) -> HashMap<PaymentHash, (PaymentPreimage, Vec<PaymentClaimDetails>)> {
3326		self.inner.lock().unwrap().payment_preimages.clone()
3327	}
3328}
3329
3330/// Compares a broadcasted commitment transaction's HTLCs with those in the latest state,
3331/// failing any HTLCs which didn't make it into the broadcasted commitment transaction back
3332/// after ANTI_REORG_DELAY blocks.
3333///
3334/// We always compare against the set of HTLCs in counterparty commitment transactions, as those
3335/// are the commitment transactions which are generated by us. The off-chain state machine in
3336/// `Channel` will automatically resolve any HTLCs which were never included in a commitment
3337/// transaction when it detects channel closure, but it is up to us to ensure any HTLCs which were
3338/// included in a remote commitment transaction are failed back if they are not present in the
3339/// broadcasted commitment transaction.
3340///
3341/// Specifically, the removal process for HTLCs in `Channel` is always based on the counterparty
3342/// sending a `revoke_and_ack`, which causes us to clear `prev_counterparty_commitment_txid`. Thus,
3343/// as long as we examine both the current counterparty commitment transaction and, if it hasn't
3344/// been revoked yet, the previous one, we we will never "forget" to resolve an HTLC.
3345macro_rules! fail_unbroadcast_htlcs {
3346	($self: expr, $commitment_tx_type: expr, $commitment_txid_confirmed: expr, $commitment_tx_confirmed: expr,
3347	 $commitment_tx_conf_height: expr, $commitment_tx_conf_hash: expr, $confirmed_htlcs_list: expr, $logger: expr) => { {
3348		debug_assert_eq!($commitment_tx_confirmed.compute_txid(), $commitment_txid_confirmed);
3349
3350		macro_rules! check_htlc_fails {
3351			($txid: expr, $commitment_tx: expr, $per_commitment_outpoints: expr) => {
3352				if let Some(ref latest_outpoints) = $per_commitment_outpoints {
3353					for &(ref htlc, ref source_option) in latest_outpoints.iter() {
3354						if let &Some(ref source) = source_option {
3355							// Check if the HTLC is present in the commitment transaction that was
3356							// broadcast, but not if it was below the dust limit, which we should
3357							// fail backwards immediately as there is no way for us to learn the
3358							// payment_preimage.
3359							// Note that if the dust limit were allowed to change between
3360							// commitment transactions we'd want to be check whether *any*
3361							// broadcastable commitment transaction has the HTLC in it, but it
3362							// cannot currently change after channel initialization, so we don't
3363							// need to here.
3364							let confirmed_htlcs_iter: &mut dyn Iterator<Item = (&HTLCOutputInCommitment, Option<&HTLCSource>)> = &mut $confirmed_htlcs_list;
3365
3366							let mut matched_htlc = false;
3367							for (ref broadcast_htlc, ref broadcast_source) in confirmed_htlcs_iter {
3368								if broadcast_htlc.transaction_output_index.is_some() &&
3369									(Some(&**source) == *broadcast_source ||
3370									 (broadcast_source.is_none() &&
3371									  broadcast_htlc.payment_hash == htlc.payment_hash &&
3372									  broadcast_htlc.amount_msat == htlc.amount_msat)) {
3373									matched_htlc = true;
3374									break;
3375								}
3376							}
3377							if matched_htlc { continue; }
3378							if $self.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).is_some() {
3379								continue;
3380							}
3381							$self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
3382								if entry.height != $commitment_tx_conf_height { return true; }
3383								match entry.event {
3384									OnchainEvent::HTLCUpdate { source: ref update_source, .. } => {
3385										*update_source != **source
3386									},
3387									_ => true,
3388								}
3389							});
3390							let entry = OnchainEventEntry {
3391								txid: $commitment_txid_confirmed,
3392								transaction: Some($commitment_tx_confirmed.clone()),
3393								height: $commitment_tx_conf_height,
3394								block_hash: Some(*$commitment_tx_conf_hash),
3395								event: OnchainEvent::HTLCUpdate {
3396									source: (**source).clone(),
3397									payment_hash: htlc.payment_hash.clone(),
3398									htlc_value_satoshis: Some(htlc.amount_msat / 1000),
3399									commitment_tx_output_idx: None,
3400								},
3401							};
3402							log_trace!($logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of {} commitment transaction {}, waiting for confirmation (at height {})",
3403								&htlc.payment_hash, $commitment_tx, $commitment_tx_type,
3404								$commitment_txid_confirmed, entry.confirmation_threshold());
3405							$self.onchain_events_awaiting_threshold_conf.push(entry);
3406						}
3407					}
3408				}
3409			}
3410		}
3411		if let Some(ref txid) = $self.funding.current_counterparty_commitment_txid {
3412			check_htlc_fails!(txid, "current", $self.funding.counterparty_claimable_outpoints.get(txid));
3413		}
3414		if let Some(ref txid) = $self.funding.prev_counterparty_commitment_txid {
3415			check_htlc_fails!(txid, "previous", $self.funding.counterparty_claimable_outpoints.get(txid));
3416		}
3417	} }
3418}
3419
3420// In the `test_invalid_funding_tx` test, we need a bogus script which matches the HTLC-Accepted
3421// witness length match (ie is 136 bytes long). We generate one here which we also use in some
3422// in-line tests later.
3423
3424#[cfg(any(test, feature = "_test_utils"))]
3425pub fn deliberately_bogus_accepted_htlc_witness_program() -> Vec<u8> {
3426	use bitcoin::opcodes;
3427	let mut ret = [opcodes::all::OP_NOP.to_u8(); 136];
3428	ret[131] = opcodes::all::OP_DROP.to_u8();
3429	ret[132] = opcodes::all::OP_DROP.to_u8();
3430	ret[133] = opcodes::all::OP_DROP.to_u8();
3431	ret[134] = opcodes::all::OP_DROP.to_u8();
3432	ret[135] = opcodes::OP_TRUE.to_u8();
3433	Vec::from(&ret[..])
3434}
3435
3436#[cfg(any(test, feature = "_test_utils"))]
3437#[rustfmt::skip]
3438pub fn deliberately_bogus_accepted_htlc_witness() -> Vec<Vec<u8>> {
3439	vec![Vec::new(), Vec::new(), Vec::new(), Vec::new(), deliberately_bogus_accepted_htlc_witness_program().into()].into()
3440}
3441
3442impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
3443	/// Gets the [`ConfirmationTarget`] we should use when selecting feerates for channel closure
3444	/// transactions for this channel right now.
3445	#[rustfmt::skip]
3446	fn closure_conf_target(&self) -> ConfirmationTarget {
3447		// Treat the sweep as urgent as long as there is at least one HTLC which is pending on a
3448		// valid commitment transaction.
3449		// TODO: This has always considered dust, but maybe it shouldn't?
3450		if holder_commitment_htlcs!(self, CURRENT).next().is_some() {
3451			return ConfirmationTarget::UrgentOnChainSweep;
3452		}
3453		if holder_commitment_htlcs!(self, PREV).map(|mut htlcs| htlcs.next().is_some()).unwrap_or(false) {
3454			return ConfirmationTarget::UrgentOnChainSweep;
3455		}
3456		if let Some(txid) = self.funding.current_counterparty_commitment_txid {
3457			if !self.funding.counterparty_claimable_outpoints.get(&txid).unwrap().is_empty() {
3458				return ConfirmationTarget::UrgentOnChainSweep;
3459			}
3460		}
3461		if let Some(txid) = self.funding.prev_counterparty_commitment_txid {
3462			if !self.funding.counterparty_claimable_outpoints.get(&txid).unwrap().is_empty() {
3463				return ConfirmationTarget::UrgentOnChainSweep;
3464			}
3465		}
3466		ConfirmationTarget::OutputSpendingFee
3467	}
3468
3469	/// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
3470	/// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen
3471	/// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key).
3472	#[rustfmt::skip]
3473	fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
3474		if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
3475			return Err("Previous secret did not match new one");
3476		}
3477
3478		// Prune HTLCs from the previous counterparty commitment tx so we don't generate failure/fulfill
3479		// events for now-revoked/fulfilled HTLCs.
3480		let mut removed_fulfilled_htlcs = false;
3481		let prune_htlc_sources = |funding: &mut FundingScope| {
3482			if let Some(txid) = funding.prev_counterparty_commitment_txid.take() {
3483				if funding.current_counterparty_commitment_txid.unwrap() != txid {
3484					let cur_claimables = funding.counterparty_claimable_outpoints.get(
3485						&funding.current_counterparty_commitment_txid.unwrap()).unwrap();
3486					// We only need to remove fulfilled HTLCs once for the first `FundingScope` we
3487					// come across since all `FundingScope`s share the same set of HTLC sources.
3488					if !removed_fulfilled_htlcs {
3489						for (_, ref source_opt) in funding.counterparty_claimable_outpoints.get(&txid).unwrap() {
3490							if let Some(source) = source_opt {
3491								if !cur_claimables.iter()
3492									.any(|(_, cur_source_opt)| cur_source_opt == source_opt)
3493								{
3494									self.counterparty_fulfilled_htlcs.remove(&SentHTLCId::from_source(source));
3495								}
3496							}
3497						}
3498						removed_fulfilled_htlcs = true;
3499					}
3500					for &mut (_, ref mut source_opt) in funding.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
3501						*source_opt = None;
3502					}
3503				} else {
3504					assert!(cfg!(fuzzing), "Commitment txids are unique outside of fuzzing, where hashes can collide");
3505				}
3506			}
3507		};
3508		core::iter::once(&mut self.funding).chain(&mut self.pending_funding).for_each(prune_htlc_sources);
3509
3510		if !self.payment_preimages.is_empty() {
3511			let min_idx = self.get_min_seen_secret();
3512			let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
3513
3514			self.payment_preimages.retain(|&k, _| {
3515				for htlc in holder_commitment_htlcs!(self, CURRENT) {
3516					if k == htlc.payment_hash {
3517						return true
3518					}
3519				}
3520				if let Some(htlcs) = holder_commitment_htlcs!(self, PREV) {
3521					for htlc in htlcs {
3522						if k == htlc.payment_hash {
3523							return true
3524						}
3525					}
3526				}
3527				let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
3528					if *cn < min_idx {
3529						return true
3530					}
3531					true
3532				} else { false };
3533				if contains {
3534					counterparty_hash_commitment_number.remove(&k);
3535				}
3536				false
3537			});
3538		}
3539
3540		Ok(())
3541	}
3542
3543	#[rustfmt::skip]
3544	fn provide_initial_counterparty_commitment_tx(
3545		&mut self, commitment_tx: CommitmentTransaction,
3546	) {
3547		// We populate this field for downgrades
3548		self.initial_counterparty_commitment_info = Some((commitment_tx.per_commitment_point(),
3549			commitment_tx.negotiated_feerate_per_kw(), commitment_tx.to_broadcaster_value_sat(), commitment_tx.to_countersignatory_value_sat()));
3550
3551		#[cfg(debug_assertions)] {
3552			let rebuilt_commitment_tx = self.initial_counterparty_commitment_tx().unwrap();
3553			debug_assert_eq!(rebuilt_commitment_tx.trust().txid(), commitment_tx.trust().txid());
3554		}
3555
3556		self.provide_latest_counterparty_commitment_tx(commitment_tx.trust().txid(), Vec::new(), commitment_tx.commitment_number(),
3557				commitment_tx.per_commitment_point());
3558		// Soon, we will only populate this field
3559		self.initial_counterparty_commitment_tx = Some(commitment_tx);
3560	}
3561
3562	#[rustfmt::skip]
3563	fn provide_latest_counterparty_commitment_tx(
3564		&mut self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
3565		commitment_number: u64, their_per_commitment_point: PublicKey,
3566	) {
3567		// TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
3568		// so that a remote monitor doesn't learn anything unless there is a malicious close.
3569		// (only maybe, sadly we cant do the same for local info, as we need to be aware of
3570		// timeouts)
3571		for &(ref htlc, _) in &htlc_outputs {
3572			self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
3573		}
3574
3575		self.funding.prev_counterparty_commitment_txid = self.funding.current_counterparty_commitment_txid.take();
3576		self.funding.current_counterparty_commitment_txid = Some(txid);
3577		self.funding.counterparty_claimable_outpoints.insert(txid, htlc_outputs);
3578		self.current_counterparty_commitment_number = commitment_number;
3579
3580		//TODO: Merge this into the other per-counterparty-transaction output storage stuff
3581		match self.their_cur_per_commitment_points {
3582			Some(old_points) => {
3583				if old_points.0 == commitment_number + 1 {
3584					self.their_cur_per_commitment_points = Some((old_points.0, old_points.1, Some(their_per_commitment_point)));
3585				} else if old_points.0 == commitment_number + 2 {
3586					if let Some(old_second_point) = old_points.2 {
3587						self.their_cur_per_commitment_points = Some((old_points.0 - 1, old_second_point, Some(their_per_commitment_point)));
3588					} else {
3589						self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
3590					}
3591				} else {
3592					self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
3593				}
3594			},
3595			None => {
3596				self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
3597			}
3598		}
3599	}
3600
3601	fn update_counterparty_commitment_data(
3602		&mut self, commitment_txs: &[CommitmentTransaction], htlc_data: &CommitmentHTLCData,
3603	) -> Result<(), &'static str> {
3604		self.verify_matching_commitment_transactions(commitment_txs.iter())?;
3605
3606		let htlcs_for_commitment = |commitment: &CommitmentTransaction| {
3607			debug_assert!(htlc_data.nondust_htlc_sources.len() <= commitment.nondust_htlcs().len());
3608			let mut nondust_htlcs = commitment.nondust_htlcs().iter();
3609			let mut sources = htlc_data.nondust_htlc_sources.iter();
3610			let nondust_htlcs = core::iter::from_fn(move || {
3611				let htlc = nondust_htlcs.next()?.clone();
3612				let source = (!htlc.offered).then(|| {
3613					let source = sources
3614						.next()
3615						.expect("Every inbound non-dust HTLC should have a corresponding source")
3616						.clone();
3617					Box::new(source)
3618				});
3619				Some((htlc, source))
3620			});
3621
3622			let dust_htlcs = htlc_data.dust_htlcs.iter().map(|(htlc, source)| {
3623				(htlc.clone(), source.as_ref().map(|source| Box::new(source.clone())))
3624			});
3625
3626			nondust_htlcs.chain(dust_htlcs).collect::<Vec<_>>()
3627		};
3628
3629		let current_funding_commitment_tx = commitment_txs.first().unwrap();
3630		self.provide_latest_counterparty_commitment_tx(
3631			current_funding_commitment_tx.trust().txid(),
3632			htlcs_for_commitment(current_funding_commitment_tx),
3633			current_funding_commitment_tx.commitment_number(),
3634			current_funding_commitment_tx.per_commitment_point(),
3635		);
3636
3637		for (pending_funding, commitment_tx) in
3638			self.pending_funding.iter_mut().zip(commitment_txs.iter().skip(1))
3639		{
3640			let commitment_txid = commitment_tx.trust().txid();
3641			pending_funding.prev_counterparty_commitment_txid =
3642				pending_funding.current_counterparty_commitment_txid.take();
3643			pending_funding.current_counterparty_commitment_txid = Some(commitment_txid);
3644			pending_funding
3645				.counterparty_claimable_outpoints
3646				.insert(commitment_txid, htlcs_for_commitment(commitment_tx));
3647		}
3648
3649		Ok(())
3650	}
3651
3652	/// Informs this monitor of the latest holder (ie broadcastable) commitment transaction. The
3653	/// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
3654	/// is important that any clones of this channel monitor (including remote clones) by kept
3655	/// up-to-date as our holder commitment transaction is updated.
3656	/// Panics if set_on_holder_tx_csv has never been called.
3657	#[rustfmt::skip]
3658	fn provide_latest_holder_commitment_tx(
3659		&mut self, holder_commitment_tx: HolderCommitmentTransaction,
3660		htlc_outputs: &[(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)],
3661		claimed_htlcs: &[(SentHTLCId, PaymentPreimage)], mut nondust_htlc_sources: Vec<HTLCSource>,
3662	) -> Result<(), &'static str> {
3663		let dust_htlcs = if htlc_outputs.iter().any(|(_, s, _)| s.is_some()) {
3664			// If we have non-dust HTLCs in htlc_outputs, ensure they match the HTLCs in the
3665			// `holder_commitment_tx`. In the future, we'll no longer provide the redundant data
3666			// and just pass in source data via `nondust_htlc_sources`.
3667			debug_assert_eq!(htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).count(), holder_commitment_tx.trust().nondust_htlcs().len());
3668			for (a, b) in htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).map(|(h, _, _)| h).zip(holder_commitment_tx.trust().nondust_htlcs().iter()) {
3669				debug_assert_eq!(a, b);
3670			}
3671			debug_assert_eq!(htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).count(), holder_commitment_tx.counterparty_htlc_sigs.len());
3672			for (a, b) in htlc_outputs.iter().filter_map(|(_, s, _)| s.as_ref()).zip(holder_commitment_tx.counterparty_htlc_sigs.iter()) {
3673				debug_assert_eq!(a, b);
3674			}
3675
3676			// Backfill the non-dust HTLC sources.
3677			debug_assert!(nondust_htlc_sources.is_empty());
3678			nondust_htlc_sources.reserve_exact(holder_commitment_tx.nondust_htlcs().len());
3679			htlc_outputs.iter().filter_map(|(htlc, _, source)| {
3680				// Filter our non-dust HTLCs, while at the same time pushing their sources into
3681				// `nondust_htlc_sources`.
3682				if htlc.transaction_output_index.is_none() {
3683					return Some((htlc.clone(), source.clone()));
3684				}
3685				if htlc.offered {
3686					nondust_htlc_sources.push(source.clone().expect("Outbound HTLCs should have a source"));
3687				}
3688				None
3689			}).collect()
3690		} else {
3691			// If we don't have any non-dust HTLCs in htlc_outputs, assume they were all passed via
3692			// `nondust_htlc_sources`, building up the final htlc_outputs by combining
3693			// `nondust_htlc_sources` and the `holder_commitment_tx`
3694			{
3695				let mut prev = -1;
3696				for htlc in holder_commitment_tx.trust().nondust_htlcs().iter() {
3697					assert!(htlc.transaction_output_index.unwrap() as i32 > prev);
3698					prev = htlc.transaction_output_index.unwrap() as i32;
3699				}
3700			}
3701
3702			debug_assert!(htlc_outputs.iter().all(|(htlc, _, _)| htlc.transaction_output_index.is_none()));
3703			debug_assert!(htlc_outputs.iter().all(|(_, sig_opt, _)| sig_opt.is_none()));
3704			debug_assert_eq!(holder_commitment_tx.trust().nondust_htlcs().len(), holder_commitment_tx.counterparty_htlc_sigs.len());
3705
3706			let mut sources = nondust_htlc_sources.iter();
3707			for htlc in holder_commitment_tx.trust().nondust_htlcs().iter() {
3708				if htlc.offered {
3709					let source = sources.next().expect("Non-dust HTLC sources didn't match commitment tx");
3710					assert!(source.possibly_matches_output(htlc));
3711				}
3712			}
3713			assert!(sources.next().is_none(), "All HTLC sources should have been exhausted");
3714
3715			// This only includes dust HTLCs as checked above.
3716			htlc_outputs.iter().map(|(htlc, _, source)| (htlc.clone(), source.clone())).collect()
3717		};
3718
3719		let htlc_data = CommitmentHTLCData { nondust_htlc_sources, dust_htlcs };
3720		self.update_holder_commitment_data(vec![holder_commitment_tx], htlc_data, claimed_htlcs)
3721	}
3722
3723	fn verify_matching_commitment_transactions<
3724		'a,
3725		I: ExactSizeIterator<Item = &'a CommitmentTransaction>,
3726	>(
3727		&self, commitment_txs: I,
3728	) -> Result<(), &'static str> {
3729		if self.pending_funding.len() + 1 != commitment_txs.len() {
3730			return Err("Commitment transaction count mismatch");
3731		}
3732
3733		let mut other_commitment_tx = None::<&CommitmentTransaction>;
3734		for (funding, commitment_tx) in
3735			core::iter::once(&self.funding).chain(self.pending_funding.iter()).zip(commitment_txs)
3736		{
3737			let trusted_tx = &commitment_tx.trust().built_transaction().transaction;
3738			if trusted_tx.input.len() != 1 {
3739				return Err("Commitment transactions must only spend one input");
3740			}
3741			let funding_outpoint_spent = trusted_tx.input[0].previous_output;
3742			if funding_outpoint_spent != funding.funding_outpoint().into_bitcoin_outpoint() {
3743				return Err("Commitment transaction spends invalid funding outpoint");
3744			}
3745
3746			if let Some(other_commitment_tx) = other_commitment_tx {
3747				if commitment_tx.commitment_number() != other_commitment_tx.commitment_number() {
3748					return Err("Commitment number mismatch");
3749				}
3750				if commitment_tx.per_commitment_point()
3751					!= other_commitment_tx.per_commitment_point()
3752				{
3753					return Err("Per-commitment-point mismatch");
3754				}
3755				if commitment_tx.negotiated_feerate_per_kw()
3756					!= other_commitment_tx.negotiated_feerate_per_kw()
3757				{
3758					return Err("Commitment fee rate mismatch");
3759				}
3760				let nondust_htlcs = commitment_tx.nondust_htlcs();
3761				let other_nondust_htlcs = other_commitment_tx.nondust_htlcs();
3762				if nondust_htlcs.len() != other_nondust_htlcs.len() {
3763					return Err("Non-dust HTLC count mismatch");
3764				}
3765				for (nondust_htlc, other_nondust_htlc) in
3766					nondust_htlcs.iter().zip(other_nondust_htlcs.iter())
3767				{
3768					if !nondust_htlc.is_data_equal(other_nondust_htlc) {
3769						return Err("Non-dust HTLC mismatch");
3770					}
3771				}
3772			}
3773
3774			other_commitment_tx = Some(commitment_tx);
3775		}
3776
3777		Ok(())
3778	}
3779
3780	fn update_holder_commitment_data(
3781		&mut self, commitment_txs: Vec<HolderCommitmentTransaction>,
3782		mut htlc_data: CommitmentHTLCData, claimed_htlcs: &[(SentHTLCId, PaymentPreimage)],
3783	) -> Result<(), &'static str> {
3784		self.verify_matching_commitment_transactions(
3785			commitment_txs.iter().map(|holder_commitment_tx| holder_commitment_tx.deref()),
3786		)?;
3787
3788		let current_funding_commitment_tx = commitment_txs.first().unwrap();
3789		self.current_holder_commitment_number = current_funding_commitment_tx.commitment_number();
3790		self.onchain_tx_handler.provide_latest_holder_tx(current_funding_commitment_tx.clone());
3791		for (funding, mut commitment_tx) in core::iter::once(&mut self.funding)
3792			.chain(self.pending_funding.iter_mut())
3793			.zip(commitment_txs.into_iter())
3794		{
3795			mem::swap(&mut commitment_tx, &mut funding.current_holder_commitment_tx);
3796			funding.prev_holder_commitment_tx = Some(commitment_tx);
3797		}
3798
3799		mem::swap(&mut htlc_data, &mut self.current_holder_htlc_data);
3800		self.prev_holder_htlc_data = Some(htlc_data);
3801
3802		for (claimed_htlc_id, claimed_preimage) in claimed_htlcs {
3803			#[cfg(debug_assertions)]
3804			{
3805				let cur_counterparty_htlcs = self
3806					.funding
3807					.counterparty_claimable_outpoints
3808					.get(&self.funding.current_counterparty_commitment_txid.unwrap())
3809					.unwrap();
3810				assert!(cur_counterparty_htlcs.iter().any(|(_, source_opt)| {
3811					if let Some(source) = source_opt {
3812						SentHTLCId::from_source(source) == *claimed_htlc_id
3813					} else {
3814						false
3815					}
3816				}));
3817			}
3818			self.counterparty_fulfilled_htlcs.insert(*claimed_htlc_id, *claimed_preimage);
3819		}
3820
3821		Ok(())
3822	}
3823
3824	/// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
3825	/// commitment_tx_infos which contain the payment hash have been revoked.
3826	///
3827	/// Note that this is often called multiple times for the same payment and must be idempotent.
3828	#[rustfmt::skip]
3829	fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
3830		&mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage,
3831		payment_info: &Option<PaymentClaimDetails>, broadcaster: &B,
3832		fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &WithChannelMonitor<L>)
3833	where B::Target: BroadcasterInterface,
3834		    F::Target: FeeEstimator,
3835		    L::Target: Logger,
3836	{
3837		self.payment_preimages.entry(payment_hash.clone())
3838			.and_modify(|(_, payment_infos)| {
3839				if let Some(payment_info) = payment_info {
3840					if !payment_infos.contains(&payment_info) {
3841						payment_infos.push(payment_info.clone());
3842					}
3843				}
3844			})
3845			.or_insert_with(|| {
3846				(payment_preimage.clone(), payment_info.clone().into_iter().collect())
3847			});
3848
3849		let confirmed_spend_info = self.funding_spend_confirmed
3850			.map(|txid| (txid, None))
3851			.or_else(|| {
3852				self.onchain_events_awaiting_threshold_conf.iter().find_map(|event| match event.event {
3853					OnchainEvent::FundingSpendConfirmation { .. } => Some((event.txid, Some(event.height))),
3854					_ => None,
3855				})
3856			});
3857		let (confirmed_spend_txid, confirmed_spend_height) =
3858			if let Some((txid, height)) = confirmed_spend_info {
3859				(txid, height)
3860			} else {
3861				return;
3862			};
3863		let funding_spent = get_confirmed_funding_scope!(self);
3864
3865		// If the channel is force closed, try to claim the output from this preimage.
3866		// First check if a counterparty commitment transaction has been broadcasted:
3867		macro_rules! claim_htlcs {
3868			($commitment_number: expr, $txid: expr, $htlcs: expr) => {
3869				let htlc_claim_reqs = self.get_counterparty_output_claims_for_preimage(*payment_preimage, funding_spent, $commitment_number, $txid, $htlcs, confirmed_spend_height);
3870				let conf_target = self.closure_conf_target();
3871				self.onchain_tx_handler.update_claims_view_from_requests(
3872					htlc_claim_reqs, self.best_block.height, self.best_block.height, broadcaster,
3873					conf_target, &self.destination_script, fee_estimator, logger,
3874				);
3875			}
3876		}
3877		if let Some(txid) = funding_spent.current_counterparty_commitment_txid {
3878			if txid == confirmed_spend_txid {
3879				if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
3880					claim_htlcs!(*commitment_number, txid, funding_spent.counterparty_claimable_outpoints.get(&txid));
3881				} else {
3882					debug_assert!(false);
3883					log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
3884				}
3885				return;
3886			}
3887		}
3888		if let Some(txid) = funding_spent.prev_counterparty_commitment_txid {
3889			if txid == confirmed_spend_txid {
3890				if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
3891					claim_htlcs!(*commitment_number, txid, funding_spent.counterparty_claimable_outpoints.get(&txid));
3892				} else {
3893					debug_assert!(false);
3894					log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
3895				}
3896				return;
3897			}
3898		}
3899
3900		// Then if a holder commitment transaction has been seen on-chain, broadcast transactions
3901		// claiming the HTLC output from each of the holder commitment transactions.
3902		// Note that we can't just use `self.holder_tx_signed`, because that only covers the case where
3903		// *we* sign a holder commitment transaction, not when e.g. a watchtower broadcasts one of our
3904		// holder commitment transactions.
3905		if self.broadcasted_holder_revokable_script.is_some() {
3906			let holder_commitment_tx = if funding_spent.current_holder_commitment_tx.trust().txid() == confirmed_spend_txid {
3907				Some(&funding_spent.current_holder_commitment_tx)
3908			} else if let Some(prev_holder_commitment_tx) = &funding_spent.prev_holder_commitment_tx {
3909				if prev_holder_commitment_tx.trust().txid() == confirmed_spend_txid {
3910					Some(prev_holder_commitment_tx)
3911				} else {
3912					None
3913				}
3914			} else {
3915				None
3916			};
3917			if let Some(holder_commitment_tx) = holder_commitment_tx {
3918				// Assume that the broadcasted commitment transaction confirmed in the current best
3919				// block. Even if not, its a reasonable metric for the bump criteria on the HTLC
3920				// transactions.
3921				let (claim_reqs, _) = self.get_broadcasted_holder_claims(
3922					funding_spent, holder_commitment_tx, self.best_block.height,
3923				);
3924				let conf_target = self.closure_conf_target();
3925				self.onchain_tx_handler.update_claims_view_from_requests(
3926					claim_reqs, self.best_block.height, self.best_block.height, broadcaster,
3927					conf_target, &self.destination_script, fee_estimator, logger,
3928				);
3929			}
3930		}
3931	}
3932
3933	#[rustfmt::skip]
3934	fn generate_claimable_outpoints_and_watch_outputs(
3935		&mut self, generate_monitor_event_with_reason: Option<ClosureReason>,
3936		require_funding_seen: bool,
3937	) -> (Vec<PackageTemplate>, Vec<TransactionOutputs>) {
3938		let funding = get_confirmed_funding_scope!(self);
3939		let holder_commitment_tx = &funding.current_holder_commitment_tx;
3940		let funding_outp = HolderFundingOutput::build(
3941			holder_commitment_tx.clone(),
3942			funding.channel_parameters.clone(),
3943		);
3944		let funding_outpoint = funding.funding_outpoint();
3945		let commitment_package = PackageTemplate::build_package(
3946			funding_outpoint.txid.clone(), funding_outpoint.index as u32,
3947			PackageSolvingData::HolderFundingOutput(funding_outp),
3948			self.best_block.height,
3949		);
3950		let mut claimable_outpoints = vec![commitment_package];
3951		if let Some(reason) = generate_monitor_event_with_reason {
3952			let event = MonitorEvent::HolderForceClosedWithInfo {
3953				reason,
3954				outpoint: funding_outpoint,
3955				channel_id: self.channel_id,
3956			};
3957			self.pending_monitor_events.push(event);
3958		}
3959
3960		// Although we aren't signing the transaction directly here, the transaction will be signed
3961		// in the claim that is queued to OnchainTxHandler. We set holder_tx_signed here to reject
3962		// new channel updates.
3963		self.holder_tx_signed = true;
3964
3965		// In manual-broadcast mode, if we have not yet observed the funding transaction on-chain,
3966		// return empty vectors rather than triggering a broadcast.
3967		if require_funding_seen && self.is_manual_broadcast && !self.funding_seen_onchain {
3968			return (Vec::new(), Vec::new());
3969		}
3970
3971		let mut watch_outputs = Vec::new();
3972		// In CSV anchor channels, we can't broadcast our HTLC transactions while the commitment transaction is
3973		// unconfirmed.
3974		// We'll delay doing so until we detect the confirmed commitment in `transactions_confirmed`.
3975		//
3976		// TODO: For now in 0FC channels, we also delay broadcasting any HTLC transactions until the commitment
3977		// transaction gets confirmed. It is nonetheless possible to add HTLC spends to the P2A spend
3978		// transaction while the commitment transaction is still unconfirmed.
3979		let zero_fee_htlcs =
3980			self.channel_type_features().supports_anchors_zero_fee_htlc_tx();
3981		let zero_fee_commitments =
3982			self.channel_type_features().supports_anchor_zero_fee_commitments();
3983		if !zero_fee_htlcs && !zero_fee_commitments {
3984			// Because we're broadcasting a commitment transaction, we should construct the package
3985			// assuming it gets confirmed in the next block. Sadly, we have code which considers
3986			// "not yet confirmed" things as discardable, so we cannot do that here.
3987			let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(
3988				funding, holder_commitment_tx, self.best_block.height,
3989			);
3990			let new_outputs = self.get_broadcasted_holder_watch_outputs(holder_commitment_tx);
3991			if !new_outputs.is_empty() {
3992				watch_outputs.push((holder_commitment_tx.trust().txid(), new_outputs));
3993			}
3994			claimable_outpoints.append(&mut new_outpoints);
3995		}
3996		(claimable_outpoints, watch_outputs)
3997	}
3998
3999	#[rustfmt::skip]
4000	/// Note: For channels where the funding transaction is being manually managed (see
4001	/// [`crate::ln::channelmanager::ChannelManager::funding_transaction_generated_manual_broadcast`]),
4002	/// this method returns without queuing any transactions until the funding transaction has been
4003	/// observed on-chain, unless `require_funding_seen` is `false`. This prevents attempting to
4004	/// broadcast unconfirmable holder commitment transactions before the funding is visible.
4005	/// See also [`ChannelMonitor::broadcast_latest_holder_commitment_txn`].
4006	///
4007	/// [`ChannelMonitor::broadcast_latest_holder_commitment_txn`]: crate::chain::channelmonitor::ChannelMonitor::broadcast_latest_holder_commitment_txn
4008	pub(crate) fn queue_latest_holder_commitment_txn_for_broadcast<B: Deref, F: Deref, L: Deref>(
4009		&mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &WithChannelMonitor<L>,
4010		require_funding_seen: bool,
4011	)
4012	where
4013		B::Target: BroadcasterInterface,
4014		F::Target: FeeEstimator,
4015		L::Target: Logger,
4016	{
4017		let reason = ClosureReason::HolderForceClosed {
4018			broadcasted_latest_txn: Some(true),
4019			message: "ChannelMonitor-initiated commitment transaction broadcast".to_owned(),
4020		};
4021		let (claimable_outpoints, _) =
4022			self.generate_claimable_outpoints_and_watch_outputs(Some(reason), require_funding_seen);
4023		// In manual-broadcast mode, if `require_funding_seen` is true and we have not yet observed
4024		// the funding transaction on-chain, do not queue any transactions.
4025		if require_funding_seen && self.is_manual_broadcast && !self.funding_seen_onchain {
4026			log_info!(logger, "Not broadcasting holder commitment for manual-broadcast channel before funding appears on-chain");
4027			return;
4028		}
4029		let conf_target = self.closure_conf_target();
4030		self.onchain_tx_handler.update_claims_view_from_requests(
4031			claimable_outpoints, self.best_block.height, self.best_block.height, broadcaster,
4032			conf_target, &self.destination_script, fee_estimator, logger,
4033		);
4034	}
4035
4036	fn renegotiated_funding<L: Deref>(
4037		&mut self, logger: &WithChannelMonitor<L>,
4038		channel_parameters: &ChannelTransactionParameters,
4039		alternative_holder_commitment_tx: &HolderCommitmentTransaction,
4040		alternative_counterparty_commitment_tx: &CommitmentTransaction,
4041	) -> Result<(), ()>
4042	where
4043		L::Target: Logger,
4044	{
4045		let alternative_counterparty_commitment_txid =
4046			alternative_counterparty_commitment_tx.trust().txid();
4047
4048		// Both the current counterparty commitment and the alternative one share the same set of
4049		// non-dust and dust HTLCs in the same order, though the index of each non-dust HTLC may be
4050		// different.
4051		//
4052		// We clone all HTLCs and their sources to use in the alternative funding scope, and update
4053		// each non-dust HTLC with their corresponding index in the alternative counterparty
4054		// commitment.
4055		let current_counterparty_commitment_htlcs =
4056			if let Some(txid) = &self.funding.current_counterparty_commitment_txid {
4057				self.funding.counterparty_claimable_outpoints.get(txid).unwrap()
4058			} else {
4059				debug_assert!(false);
4060				log_error!(
4061					logger,
4062					"Received funding renegotiation while initial funding negotiation is still pending"
4063				);
4064				return Err(());
4065			};
4066		let mut htlcs_with_sources = current_counterparty_commitment_htlcs.clone();
4067		let alternative_htlcs = alternative_counterparty_commitment_tx.nondust_htlcs();
4068
4069		let expected_non_dust_htlc_count = htlcs_with_sources
4070			.iter()
4071			// Non-dust HTLCs always come first, so the position of the first dust HTLC is equal to
4072			// our non-dust HTLC count.
4073			.position(|(htlc, _)| htlc.transaction_output_index.is_none())
4074			.unwrap_or(htlcs_with_sources.len());
4075		if alternative_htlcs.len() != expected_non_dust_htlc_count {
4076			log_error!(
4077				logger,
4078				"Received alternative counterparty commitment with HTLC count mismatch"
4079			);
4080			return Err(());
4081		}
4082
4083		for (alternative_htlc, (htlc, _)) in
4084			alternative_htlcs.iter().zip(htlcs_with_sources.iter_mut())
4085		{
4086			debug_assert!(htlc.transaction_output_index.is_some());
4087			debug_assert!(alternative_htlc.transaction_output_index.is_some());
4088			if !alternative_htlc.is_data_equal(htlc) {
4089				log_error!(
4090					logger,
4091					"Received alternative counterparty commitment with non-dust HTLC mismatch"
4092				);
4093				return Err(());
4094			}
4095			htlc.transaction_output_index = alternative_htlc.transaction_output_index;
4096		}
4097
4098		let mut counterparty_claimable_outpoints = new_hash_map();
4099		counterparty_claimable_outpoints
4100			.insert(alternative_counterparty_commitment_txid, htlcs_with_sources);
4101
4102		// TODO(splicing): Enforce any necessary RBF validity checks.
4103		let alternative_funding = FundingScope {
4104			channel_parameters: channel_parameters.clone(),
4105			current_counterparty_commitment_txid: Some(alternative_counterparty_commitment_txid),
4106			prev_counterparty_commitment_txid: None,
4107			counterparty_claimable_outpoints,
4108			current_holder_commitment_tx: alternative_holder_commitment_tx.clone(),
4109			prev_holder_commitment_tx: None,
4110		};
4111		let alternative_funding_outpoint = alternative_funding.funding_outpoint();
4112
4113		if self
4114			.pending_funding
4115			.iter()
4116			.any(|funding| funding.funding_txid() == alternative_funding_outpoint.txid)
4117		{
4118			log_error!(
4119				logger,
4120				"Renegotiated funding transaction with a duplicate funding txid {}",
4121				alternative_funding_outpoint.txid
4122			);
4123			return Err(());
4124		}
4125
4126		if let Some(parent_funding_txid) = channel_parameters.splice_parent_funding_txid.as_ref() {
4127			// Only one splice can be negotiated at a time after we've exchanged `channel_ready`
4128			// (implying our funding is confirmed) that spends our currently locked funding.
4129			if !self.pending_funding.is_empty() {
4130				log_error!(
4131					logger,
4132					"Negotiated splice while channel is pending channel_ready/splice_locked"
4133				);
4134				return Err(());
4135			}
4136			if *parent_funding_txid != self.funding.funding_txid() {
4137				log_error!(
4138					logger,
4139					"Negotiated splice that does not spend currently locked funding transaction"
4140				);
4141				return Err(());
4142			}
4143		} else if self.funding.is_splice() {
4144			// If we've already spliced at least once, we're no longer able to RBF the original
4145			// funding transaction.
4146			return Err(());
4147		}
4148
4149		let script_pubkey = channel_parameters.make_funding_redeemscript().to_p2wsh();
4150		self.outputs_to_watch.insert(
4151			alternative_funding_outpoint.txid,
4152			vec![(alternative_funding_outpoint.index as u32, script_pubkey)],
4153		);
4154		self.pending_funding.push(alternative_funding);
4155
4156		Ok(())
4157	}
4158
4159	fn promote_funding(&mut self, new_funding_txid: Txid) -> Result<(), ()> {
4160		let prev_funding_txid = self.funding.funding_txid();
4161
4162		let new_funding = self
4163			.pending_funding
4164			.iter_mut()
4165			.find(|funding| funding.funding_txid() == new_funding_txid);
4166		if new_funding.is_none() {
4167			return Err(());
4168		}
4169		let mut new_funding = new_funding.unwrap();
4170
4171		mem::swap(&mut self.funding, &mut new_funding);
4172		self.onchain_tx_handler.update_after_renegotiated_funding_locked(
4173			self.funding.channel_parameters.clone(),
4174			self.funding.current_holder_commitment_tx.clone(),
4175			self.funding.prev_holder_commitment_tx.clone(),
4176		);
4177
4178		// It's possible that no commitment updates happened during the lifecycle of the pending
4179		// splice's `FundingScope` that was promoted. If so, our `prev_holder_htlc_data` is
4180		// now irrelevant, since there's no valid previous commitment that exists for the current
4181		// funding transaction that could be broadcast.
4182		if self.funding.prev_holder_commitment_tx.is_none() {
4183			self.prev_holder_htlc_data.take();
4184		}
4185
4186		let no_further_updates_allowed = self.no_further_updates_allowed();
4187
4188		// The swap above places the previous `FundingScope` into `pending_funding`.
4189		for funding in self.pending_funding.drain(..) {
4190			let funding_txid = funding.funding_txid();
4191			self.outputs_to_watch.remove(&funding_txid);
4192			if no_further_updates_allowed && funding_txid != prev_funding_txid {
4193				self.pending_events.push(Event::DiscardFunding {
4194					channel_id: self.channel_id,
4195					funding_info: crate::events::FundingInfo::OutPoint {
4196						outpoint: funding.funding_outpoint(),
4197					},
4198				});
4199			}
4200		}
4201		if let Some((alternative_funding_txid, _)) = self.alternative_funding_confirmed.take() {
4202			// In exceedingly rare cases, it's possible there was a reorg that caused a potential funding to
4203			// be locked in that this `ChannelMonitor` has not yet seen. Thus, we avoid a runtime assertion
4204			// and only assert in debug mode.
4205			debug_assert_eq!(alternative_funding_txid, new_funding_txid);
4206		}
4207
4208		Ok(())
4209	}
4210
4211	#[rustfmt::skip]
4212	fn update_monitor<B: Deref, F: Deref, L: Deref>(
4213		&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor<L>
4214	) -> Result<(), ()>
4215	where B::Target: BroadcasterInterface,
4216		F::Target: FeeEstimator,
4217		L::Target: Logger,
4218	{
4219		if self.latest_update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID && updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID {
4220			log_info!(logger, "Applying pre-0.1 post-force-closed update to monitor {} with {} change(s).",
4221				log_funding_info!(self), updates.updates.len());
4222		} else if updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID {
4223			log_info!(logger, "Applying pre-0.1 force close update to monitor {} with {} change(s).",
4224				log_funding_info!(self), updates.updates.len());
4225		} else {
4226			log_info!(logger, "Applying update to monitor {}, bringing update_id from {} to {} with {} change(s).",
4227				log_funding_info!(self), self.latest_update_id, updates.update_id, updates.updates.len());
4228		}
4229
4230		// ChannelMonitor updates may be applied after force close if we receive a preimage for a
4231		// broadcasted commitment transaction HTLC output that we'd like to claim on-chain. If this
4232		// is the case, we no longer have guaranteed access to the monitor's update ID, so we use a
4233		// sentinel value instead.
4234		//
4235		// The `ChannelManager` may also queue redundant `ChannelForceClosed` updates if it still
4236		// thinks the channel needs to have its commitment transaction broadcast, so we'll allow
4237		// them as well.
4238		if updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID || self.lockdown_from_offchain {
4239			assert_eq!(updates.updates.len(), 1);
4240			match updates.updates[0] {
4241				ChannelMonitorUpdateStep::ReleasePaymentComplete { .. } => {},
4242				ChannelMonitorUpdateStep::ChannelForceClosed { .. } => {},
4243				// We should have already seen a `ChannelForceClosed` update if we're trying to
4244				// provide a preimage at this point.
4245				ChannelMonitorUpdateStep::PaymentPreimage { .. } =>
4246					debug_assert!(self.lockdown_from_offchain),
4247				_ => {
4248					log_error!(logger, "Attempted to apply post-force-close ChannelMonitorUpdate of type {}", updates.updates[0].variant_name());
4249					panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage");
4250				},
4251			}
4252		}
4253		if updates.update_id != LEGACY_CLOSED_CHANNEL_UPDATE_ID {
4254			if self.latest_update_id + 1 != updates.update_id {
4255				panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
4256			}
4257		}
4258		let mut ret = Ok(());
4259		let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&**fee_estimator);
4260		for update in updates.updates.iter() {
4261			match update {
4262				ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs, claimed_htlcs, nondust_htlc_sources } => {
4263					log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
4264					if self.lockdown_from_offchain { panic!(); }
4265					if let Err(e) = self.provide_latest_holder_commitment_tx(
4266						commitment_tx.clone(), htlc_outputs, &claimed_htlcs,
4267						nondust_htlc_sources.clone()
4268					) {
4269						log_error!(logger, "Failed updating latest holder commitment transaction info: {}", e);
4270						ret = Err(());
4271					}
4272				}
4273				ChannelMonitorUpdateStep::LatestHolderCommitment {
4274					commitment_txs, htlc_data, claimed_htlcs,
4275				} => {
4276					log_trace!(logger, "Updating ChannelMonitor with {} latest holder commitment(s)", commitment_txs.len());
4277					assert!(!self.lockdown_from_offchain);
4278					if let Err(e) = self.update_holder_commitment_data(
4279						commitment_txs.clone(), htlc_data.clone(), claimed_htlcs,
4280					) {
4281						log_error!(logger, "Failed updating latest holder commitment state: {}", e);
4282						ret = Err(());
4283					}
4284				},
4285				// Soon we will drop the `LatestCounterpartyCommitmentTXInfo` variant in favor of `LatestCounterpartyCommitment`.
4286				// For now we just add the code to handle the new updates.
4287				// Next step: in channel, switch channel monitor updates to use the `LatestCounterpartyCommitment` variant.
4288				ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_per_commitment_point, .. } => {
4289					log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
4290					if self.pending_funding.is_empty() {
4291						self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_per_commitment_point)
4292					} else {
4293						log_error!(logger, "Received unexpected non-splice counterparty commitment monitor update");
4294						ret = Err(());
4295					}
4296				},
4297				ChannelMonitorUpdateStep::LatestCounterpartyCommitment {
4298					commitment_txs, htlc_data,
4299				} => {
4300					log_trace!(logger, "Updating ChannelMonitor with {} latest counterparty commitments", commitment_txs.len());
4301					if let Err(e) = self.update_counterparty_commitment_data(commitment_txs, htlc_data) {
4302						log_error!(logger, "Failed updating latest counterparty commitment state: {}", e);
4303						ret = Err(());
4304					}
4305				},
4306				ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage, payment_info } => {
4307					log_trace!(logger, "Updating ChannelMonitor with payment preimage");
4308					self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()), &payment_preimage, payment_info, broadcaster, &bounded_fee_estimator, logger)
4309				},
4310				ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
4311					log_trace!(logger, "Updating ChannelMonitor with commitment secret");
4312					if let Err(e) = self.provide_secret(*idx, *secret) {
4313						debug_assert!(false, "Latest counterparty commitment secret was invalid");
4314						log_error!(logger, "Providing latest counterparty commitment secret failed/was refused:");
4315						log_error!(logger, "    {}", e);
4316						ret = Err(());
4317					}
4318				},
4319				ChannelMonitorUpdateStep::RenegotiatedFunding {
4320					channel_parameters, holder_commitment_tx, counterparty_commitment_tx,
4321				} => {
4322					log_trace!(logger, "Updating ChannelMonitor with alternative holder and counterparty commitment transactions for funding txid {}",
4323						channel_parameters.funding_outpoint.unwrap().txid);
4324					if let Err(_) = self.renegotiated_funding(
4325						logger, channel_parameters, holder_commitment_tx, counterparty_commitment_tx,
4326					) {
4327						ret = Err(());
4328					}
4329				},
4330				ChannelMonitorUpdateStep::RenegotiatedFundingLocked { funding_txid } => {
4331					log_trace!(logger, "Updating ChannelMonitor with locked renegotiated funding txid {}", funding_txid);
4332					if let Err(_) = self.promote_funding(*funding_txid) {
4333						log_error!(logger, "Unknown funding with txid {} became locked", funding_txid);
4334						ret = Err(());
4335					}
4336				},
4337				ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
4338					log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
4339					self.lockdown_from_offchain = true;
4340					if *should_broadcast {
4341						// There's no need to broadcast our commitment transaction if we've seen one
4342						// confirmed (even with 1 confirmation) as it'll be rejected as
4343						// duplicate/conflicting.
4344						let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
4345							self.onchain_events_awaiting_threshold_conf.iter().any(
4346								|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
4347						if detected_funding_spend {
4348							log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
4349							continue;
4350						}
4351						self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &bounded_fee_estimator, logger, true);
4352					} else if !self.holder_tx_signed {
4353						log_error!(logger, "WARNING: You have a potentially-unsafe holder commitment transaction available to broadcast");
4354						log_error!(logger, "    in channel monitor for channel {}!", &self.channel_id());
4355						log_error!(logger, "    Read the docs for ChannelMonitor::broadcast_latest_holder_commitment_txn to take manual action!");
4356					} else {
4357						// If we generated a MonitorEvent::HolderForceClosed, the ChannelManager
4358						// will still give us a ChannelForceClosed event with !should_broadcast, but we
4359						// shouldn't print the scary warning above.
4360						log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
4361					}
4362				},
4363				ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
4364					log_trace!(logger, "Updating ChannelMonitor with shutdown script");
4365					if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
4366						panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
4367					}
4368				},
4369				ChannelMonitorUpdateStep::ReleasePaymentComplete { htlc } => {
4370					log_trace!(logger, "HTLC {htlc:?} permanently and fully resolved");
4371					self.htlcs_resolved_to_user.insert(*htlc);
4372				},
4373			}
4374		}
4375
4376		#[cfg(debug_assertions)] {
4377			self.counterparty_commitment_txs_from_update(updates);
4378		}
4379
4380		self.latest_update_id = updates.update_id;
4381
4382		// Refuse updates after we've detected a spend onchain (or if the channel was otherwise
4383		// closed), but only if the update isn't the kind of update we expect to see after channel
4384		// closure.
4385		let mut is_pre_close_update = false;
4386		for update in updates.updates.iter() {
4387			match update {
4388				ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. }
4389					|ChannelMonitorUpdateStep::LatestHolderCommitment { .. }
4390					|ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. }
4391					|ChannelMonitorUpdateStep::LatestCounterpartyCommitment { .. }
4392					|ChannelMonitorUpdateStep::ShutdownScript { .. }
4393					|ChannelMonitorUpdateStep::CommitmentSecret { .. }
4394					|ChannelMonitorUpdateStep::RenegotiatedFunding { .. }
4395					|ChannelMonitorUpdateStep::RenegotiatedFundingLocked { .. } =>
4396						is_pre_close_update = true,
4397				// After a channel is closed, we don't communicate with our peer about it, so the
4398				// only things we will update is getting a new preimage (from a different channel),
4399				// being told that the channel is closed, or being told a payment which was
4400				// resolved on-chain has had its resolution communicated to the user. All other
4401				// updates are generated while talking to our peer.
4402				ChannelMonitorUpdateStep::PaymentPreimage { .. } => {},
4403				ChannelMonitorUpdateStep::ChannelForceClosed { .. } => {},
4404				ChannelMonitorUpdateStep::ReleasePaymentComplete { .. } => {},
4405			}
4406		}
4407
4408		if ret.is_ok() && self.no_further_updates_allowed() && is_pre_close_update {
4409			log_error!(logger, "Refusing Channel Monitor Update as counterparty attempted to update commitment after funding was spent");
4410			Err(())
4411		} else { ret }
4412	}
4413
4414	/// Returns true if the channel has been closed (i.e. no further updates are allowed) and no
4415	/// commitment state updates ever happened.
4416	fn is_closed_without_updates(&self) -> bool {
4417		let mut commitment_not_advanced =
4418			self.current_counterparty_commitment_number == INITIAL_COMMITMENT_NUMBER;
4419		commitment_not_advanced &=
4420			self.current_holder_commitment_number == INITIAL_COMMITMENT_NUMBER;
4421		(self.holder_tx_signed || self.lockdown_from_offchain) && commitment_not_advanced
4422	}
4423
4424	fn no_further_updates_allowed(&self) -> bool {
4425		self.funding_spend_seen || self.lockdown_from_offchain || self.holder_tx_signed
4426	}
4427
4428	fn get_latest_update_id(&self) -> u64 {
4429		self.latest_update_id
4430	}
4431
4432	/// Returns the outpoint we are currently monitoring the chain for spends. This will change for
4433	/// every splice that has reached its intended confirmation depth.
4434	#[rustfmt::skip]
4435	fn get_funding_txo(&self) -> OutPoint {
4436		self.funding.channel_parameters.funding_outpoint
4437			.expect("Funding outpoint must be set for active monitor")
4438	}
4439
4440	/// Returns the P2WSH script we are currently monitoring the chain for spends. This will change
4441	/// for every splice that has reached its intended confirmation depth.
4442	fn get_funding_script(&self) -> ScriptBuf {
4443		self.funding.channel_parameters.make_funding_redeemscript().to_p2wsh()
4444	}
4445
4446	pub fn channel_id(&self) -> ChannelId {
4447		self.channel_id
4448	}
4449
4450	fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, ScriptBuf)>> {
4451		// If we've detected a counterparty commitment tx on chain, we must include it in the set
4452		// of outputs to watch for spends of, otherwise we're likely to lose user funds. Because
4453		// its trivial to do, double-check that here.
4454		for txid in self.counterparty_commitment_txn_on_chain.keys() {
4455			self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
4456		}
4457		&self.outputs_to_watch
4458	}
4459
4460	fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
4461		let mut ret = Vec::new();
4462		mem::swap(&mut ret, &mut self.pending_monitor_events);
4463		ret
4464	}
4465
4466	/// Gets the set of events that are repeated regularly (e.g. those which RBF bump
4467	/// transactions). We're okay if we lose these on restart as they'll be regenerated for us at
4468	/// some regular interval via [`ChannelMonitor::rebroadcast_pending_claims`].
4469	#[rustfmt::skip]
4470	pub(super) fn get_repeated_events(&mut self) -> Vec<Event> {
4471		let pending_claim_events = self.onchain_tx_handler.get_and_clear_pending_claim_events();
4472		let mut ret = Vec::with_capacity(pending_claim_events.len());
4473		for (claim_id, claim_event) in pending_claim_events {
4474			match claim_event {
4475				ClaimEvent::BumpCommitment {
4476					package_target_feerate_sat_per_1000_weight, commitment_tx,
4477					commitment_tx_fee_satoshis, pending_nondust_htlcs, anchor_output_idx,
4478					channel_parameters,
4479				} => {
4480					let channel_id = self.channel_id;
4481					let counterparty_node_id = self.counterparty_node_id;
4482					let commitment_txid = commitment_tx.compute_txid();
4483					ret.push(Event::BumpTransaction(BumpTransactionEvent::ChannelClose {
4484						channel_id,
4485						counterparty_node_id,
4486						claim_id,
4487						package_target_feerate_sat_per_1000_weight,
4488						anchor_descriptor: AnchorDescriptor {
4489							channel_derivation_parameters: ChannelDerivationParameters {
4490								keys_id: self.channel_keys_id,
4491								value_satoshis: channel_parameters.channel_value_satoshis,
4492								transaction_parameters: channel_parameters,
4493							},
4494							outpoint: BitcoinOutPoint {
4495								txid: commitment_txid,
4496								vout: anchor_output_idx,
4497							},
4498							value: commitment_tx.output[anchor_output_idx as usize].value,
4499						},
4500						pending_htlcs: pending_nondust_htlcs,
4501						commitment_tx,
4502						commitment_tx_fee_satoshis,
4503					}));
4504				},
4505				ClaimEvent::BumpHTLC {
4506					target_feerate_sat_per_1000_weight, htlcs, tx_lock_time,
4507				} => {
4508					let channel_id = self.channel_id;
4509					let counterparty_node_id = self.counterparty_node_id;
4510					ret.push(Event::BumpTransaction(BumpTransactionEvent::HTLCResolution {
4511						channel_id,
4512						counterparty_node_id,
4513						claim_id,
4514						target_feerate_sat_per_1000_weight,
4515						htlc_descriptors: htlcs,
4516						tx_lock_time,
4517					}));
4518				}
4519			}
4520		}
4521		ret
4522	}
4523
4524	fn initial_counterparty_commitment_tx(&mut self) -> Option<CommitmentTransaction> {
4525		self.initial_counterparty_commitment_tx.clone().or_else(|| {
4526			// This provides forward compatibility; an old monitor will not contain the full
4527			// transaction; only enough information to rebuild it
4528			self.initial_counterparty_commitment_info.map(
4529				|(
4530					their_per_commitment_point,
4531					feerate_per_kw,
4532					to_broadcaster_value,
4533					to_countersignatory_value,
4534				)| {
4535					let nondust_htlcs = vec![];
4536					// Since we're expected to only reach here during the initial persistence of a
4537					// monitor (i.e., via [`Persist::persist_new_channel`]), we expect to only have
4538					// one `FundingScope` present.
4539					debug_assert!(self.pending_funding.is_empty());
4540					let channel_parameters = &self.funding.channel_parameters;
4541
4542					let commitment_tx = self.build_counterparty_commitment_tx(
4543						channel_parameters,
4544						INITIAL_COMMITMENT_NUMBER,
4545						&their_per_commitment_point,
4546						to_broadcaster_value,
4547						to_countersignatory_value,
4548						feerate_per_kw,
4549						nondust_htlcs,
4550					);
4551					// Take the opportunity to populate this recently introduced field
4552					self.initial_counterparty_commitment_tx = Some(commitment_tx.clone());
4553					commitment_tx
4554				},
4555			)
4556		})
4557	}
4558
4559	#[rustfmt::skip]
4560	fn build_counterparty_commitment_tx(
4561		&self, channel_parameters: &ChannelTransactionParameters, commitment_number: u64,
4562		their_per_commitment_point: &PublicKey, to_broadcaster_value: u64,
4563		to_countersignatory_value: u64, feerate_per_kw: u32,
4564		nondust_htlcs: Vec<HTLCOutputInCommitment>
4565	) -> CommitmentTransaction {
4566		let channel_parameters = &channel_parameters.as_counterparty_broadcastable();
4567		CommitmentTransaction::new(commitment_number, their_per_commitment_point,
4568			to_broadcaster_value, to_countersignatory_value, feerate_per_kw, nondust_htlcs, channel_parameters, &self.onchain_tx_handler.secp_ctx)
4569	}
4570
4571	#[rustfmt::skip]
4572	fn counterparty_commitment_txs_from_update(&self, update: &ChannelMonitorUpdate) -> Vec<CommitmentTransaction> {
4573		update.updates.iter().filter_map(|update| {
4574			// Soon we will drop the first branch here in favor of the second.
4575			// In preparation, we just add the second branch without deleting the first.
4576			// Next step: in channel, switch channel monitor updates to use the `LatestCounterpartyCommitment` variant.
4577			match update {
4578				&ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid,
4579					ref htlc_outputs, commitment_number, their_per_commitment_point,
4580					feerate_per_kw: Some(feerate_per_kw),
4581					to_broadcaster_value_sat: Some(to_broadcaster_value),
4582					to_countersignatory_value_sat: Some(to_countersignatory_value) } => {
4583
4584					let nondust_htlcs = htlc_outputs.iter().filter_map(|(htlc, _)| {
4585						htlc.transaction_output_index.map(|_| htlc).cloned()
4586					}).collect::<Vec<_>>();
4587
4588					// This monitor update variant is only applicable while there's a single
4589					// `FundingScope` active, otherwise we expect to see
4590					// `LatestCounterpartyCommitment` instead.
4591					debug_assert!(self.pending_funding.is_empty());
4592					let channel_parameters = &self.funding.channel_parameters;
4593					let commitment_tx = self.build_counterparty_commitment_tx(
4594						channel_parameters,
4595						commitment_number,
4596						&their_per_commitment_point,
4597						to_broadcaster_value,
4598						to_countersignatory_value,
4599						feerate_per_kw,
4600						nondust_htlcs,
4601					);
4602
4603					debug_assert_eq!(commitment_tx.trust().txid(), commitment_txid);
4604
4605					Some(vec![commitment_tx])
4606				},
4607				&ChannelMonitorUpdateStep::LatestCounterpartyCommitment { ref commitment_txs, .. } => {
4608					Some(commitment_txs.clone())
4609				},
4610				&ChannelMonitorUpdateStep::RenegotiatedFunding { ref counterparty_commitment_tx, .. } => {
4611					Some(vec![counterparty_commitment_tx.clone()])
4612				},
4613				_ => None,
4614			}
4615		}).flatten().collect()
4616	}
4617
4618	#[rustfmt::skip]
4619	fn sign_to_local_justice_tx(
4620		&self, mut justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64
4621	) -> Result<Transaction, ()> {
4622		let secret = self.get_secret(commitment_number).ok_or(())?;
4623		let per_commitment_key = SecretKey::from_slice(&secret).map_err(|_| ())?;
4624		let their_per_commitment_point = PublicKey::from_secret_key(
4625			&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
4626
4627		let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,
4628			&self.holder_revocation_basepoint, &their_per_commitment_point);
4629		let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,
4630			&self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &their_per_commitment_point);
4631		let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
4632			self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
4633
4634		let commitment_txid = &justice_tx.input[input_idx].previous_output.txid;
4635		// Since there may be multiple counterparty commitment transactions for the same commitment
4636		// number due to splicing, we have to locate the matching `FundingScope::channel_parameters`
4637		// to provide the signer. Since this is intended to be called during
4638		// `Persist::update_persisted_channel`, the monitor should have already had the update
4639		// applied.
4640		let channel_parameters = core::iter::once(&self.funding)
4641			.chain(&self.pending_funding)
4642			.find(|funding| funding.counterparty_claimable_outpoints.contains_key(commitment_txid))
4643			.map(|funding| &funding.channel_parameters)
4644			.ok_or(())?;
4645		let sig = self.onchain_tx_handler.signer.sign_justice_revoked_output(
4646			&channel_parameters, &justice_tx, input_idx, value, &per_commitment_key,
4647			&self.onchain_tx_handler.secp_ctx,
4648		)?;
4649		justice_tx.input[input_idx].witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(sig));
4650		justice_tx.input[input_idx].witness.push(&[1u8]);
4651		justice_tx.input[input_idx].witness.push(revokeable_redeemscript.as_bytes());
4652		Ok(justice_tx)
4653	}
4654
4655	/// Can only fail if idx is < get_min_seen_secret
4656	fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
4657		self.commitment_secrets.get_secret(idx)
4658	}
4659
4660	fn get_min_seen_secret(&self) -> u64 {
4661		self.commitment_secrets.get_min_seen_secret()
4662	}
4663
4664	fn get_cur_counterparty_commitment_number(&self) -> u64 {
4665		self.current_counterparty_commitment_number
4666	}
4667
4668	fn get_cur_holder_commitment_number(&self) -> u64 {
4669		self.current_holder_commitment_number
4670	}
4671
4672	/// Attempts to claim a counterparty commitment transaction's outputs using the revocation key and
4673	/// data in counterparty_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
4674	/// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
4675	/// HTLC-Success/HTLC-Timeout transactions.
4676	///
4677	/// Returns packages to claim the revoked output(s) and general information about the output that
4678	/// is to the counterparty in the commitment transaction.
4679	#[rustfmt::skip]
4680	fn check_spend_counterparty_transaction<L: Deref>(&mut self, commitment_txid: Txid, commitment_tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L)
4681		-> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo)
4682	where L::Target: Logger {
4683		// Most secp and related errors trying to create keys means we have no hope of constructing
4684		// a spend transaction...so we return no transactions to broadcast
4685		let mut claimable_outpoints = Vec::new();
4686		let mut to_counterparty_output_info = None;
4687
4688		let funding_spent = get_confirmed_funding_scope!(self);
4689		let per_commitment_option = funding_spent.counterparty_claimable_outpoints.get(&commitment_txid);
4690
4691		macro_rules! ignore_error {
4692			( $thing : expr ) => {
4693				match $thing {
4694					Ok(a) => a,
4695					Err(_) => return (claimable_outpoints, to_counterparty_output_info)
4696				}
4697			};
4698		}
4699
4700		let funding_txid_spent = commitment_tx.input[0].previous_output.txid;
4701		let commitment_number = 0xffffffffffff - ((((commitment_tx.input[0].sequence.0 as u64 & 0xffffff) << 3*8) | (commitment_tx.lock_time.to_consensus_u32() as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor);
4702		if commitment_number >= self.get_min_seen_secret() {
4703			assert_eq!(funding_spent.funding_txid(), funding_txid_spent);
4704
4705			let secret = self.get_secret(commitment_number).unwrap();
4706			let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
4707			let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
4708			let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,  &self.holder_revocation_basepoint, &per_commitment_point,);
4709			let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx, &self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key));
4710
4711			let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
4712			let revokeable_p2wsh = revokeable_redeemscript.to_p2wsh();
4713
4714			// First, process non-htlc outputs (to_holder & to_counterparty)
4715			for (idx, outp) in commitment_tx.output.iter().enumerate() {
4716				if outp.script_pubkey == revokeable_p2wsh {
4717					let revk_outp = RevokedOutput::build(
4718						per_commitment_point, per_commitment_key, outp.value,
4719						funding_spent.channel_parameters.clone(), height,
4720					);
4721					let justice_package = PackageTemplate::build_package(
4722						commitment_txid, idx as u32,
4723						PackageSolvingData::RevokedOutput(revk_outp),
4724						height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32,
4725					);
4726					claimable_outpoints.push(justice_package);
4727					to_counterparty_output_info =
4728						Some((idx.try_into().expect("Txn can't have more than 2^32 outputs"), outp.value));
4729				}
4730			}
4731
4732			// Then, try to find revoked htlc outputs
4733			if let Some(per_commitment_claimable_data) = per_commitment_option {
4734				for (htlc, _) in per_commitment_claimable_data {
4735					if let Some(transaction_output_index) = htlc.transaction_output_index {
4736						if transaction_output_index as usize >= commitment_tx.output.len() ||
4737								commitment_tx.output[transaction_output_index as usize].value != htlc.to_bitcoin_amount() {
4738							// per_commitment_data is corrupt or our commitment signing key leaked!
4739							return (claimable_outpoints, to_counterparty_output_info);
4740						}
4741						let revk_htlc_outp = RevokedHTLCOutput::build(
4742							per_commitment_point, per_commitment_key, htlc.clone(),
4743							funding_spent.channel_parameters.clone(), height,
4744						);
4745						let counterparty_spendable_height = if htlc.offered {
4746							htlc.cltv_expiry
4747						} else {
4748							height
4749						};
4750						let justice_package = PackageTemplate::build_package(
4751							commitment_txid,
4752							transaction_output_index,
4753							PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp),
4754							counterparty_spendable_height,
4755						);
4756						claimable_outpoints.push(justice_package);
4757					}
4758				}
4759			}
4760
4761			// Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
4762			if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
4763				// We're definitely a counterparty commitment transaction!
4764				log_error!(logger, "Got broadcast of revoked counterparty commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
4765				self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
4766
4767				if let Some(per_commitment_claimable_data) = per_commitment_option {
4768					fail_unbroadcast_htlcs!(self, "revoked_counterparty", commitment_txid, commitment_tx, height,
4769						block_hash, per_commitment_claimable_data.iter().map(|(htlc, htlc_source)|
4770							(htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
4771						), logger);
4772				} else {
4773					// Our fuzzers aren't constrained by pesky things like valid signatures, so can
4774					// spend our funding output with a transaction which doesn't match our past
4775					// commitment transactions. Thus, we can only debug-assert here when not
4776					// fuzzing.
4777					debug_assert!(cfg!(fuzzing), "We should have per-commitment option for any recognized old commitment txn");
4778					fail_unbroadcast_htlcs!(self, "revoked counterparty", commitment_txid, commitment_tx, height,
4779						block_hash, [].iter().map(|reference| *reference), logger);
4780				}
4781			}
4782		} else if let Some(per_commitment_claimable_data) = per_commitment_option {
4783			assert_eq!(funding_spent.funding_txid(), funding_txid_spent);
4784
4785			// While this isn't useful yet, there is a potential race where if a counterparty
4786			// revokes a state at the same time as the commitment transaction for that state is
4787			// confirmed, and the watchtower receives the block before the user, the user could
4788			// upload a new ChannelMonitor with the revocation secret but the watchtower has
4789			// already processed the block, resulting in the counterparty_commitment_txn_on_chain entry
4790			// not being generated by the above conditional. Thus, to be safe, we go ahead and
4791			// insert it here.
4792			self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
4793
4794			log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
4795			fail_unbroadcast_htlcs!(self, "counterparty", commitment_txid, commitment_tx, height, block_hash,
4796				per_commitment_claimable_data.iter().map(|(htlc, htlc_source)|
4797					(htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
4798				), logger);
4799			let (htlc_claim_reqs, counterparty_output_info) =
4800				self.get_counterparty_output_claim_info(funding_spent, commitment_number, commitment_txid, commitment_tx, per_commitment_claimable_data, Some(height));
4801			to_counterparty_output_info = counterparty_output_info;
4802			for req in htlc_claim_reqs {
4803				claimable_outpoints.push(req);
4804			}
4805		}
4806
4807		(claimable_outpoints, to_counterparty_output_info)
4808	}
4809
4810	fn get_point_for_commitment_number(&self, commitment_number: u64) -> Option<PublicKey> {
4811		let per_commitment_points = &self.their_cur_per_commitment_points?;
4812
4813		// If the counterparty commitment tx is the latest valid state, use their latest
4814		// per-commitment point
4815		if per_commitment_points.0 == commitment_number {
4816			Some(per_commitment_points.1)
4817		} else if let Some(point) = per_commitment_points.2.as_ref() {
4818			// If counterparty commitment tx is the state previous to the latest valid state, use
4819			// their previous per-commitment point (non-atomicity of revocation means it's valid for
4820			// them to temporarily have two valid commitment txns from our viewpoint)
4821			if per_commitment_points.0 == commitment_number + 1 {
4822				Some(*point)
4823			} else {
4824				None
4825			}
4826		} else {
4827			None
4828		}
4829	}
4830
4831	fn get_counterparty_output_claims_for_preimage(
4832		&self, preimage: PaymentPreimage, funding_spent: &FundingScope, commitment_number: u64,
4833		commitment_txid: Txid,
4834		per_commitment_option: Option<&Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
4835		confirmation_height: Option<u32>,
4836	) -> Vec<PackageTemplate> {
4837		let per_commitment_claimable_data = match per_commitment_option {
4838			Some(outputs) => outputs,
4839			None => return Vec::new(),
4840		};
4841		let per_commitment_point = match self.get_point_for_commitment_number(commitment_number) {
4842			Some(point) => point,
4843			None => return Vec::new(),
4844		};
4845
4846		let matching_payment_hash = PaymentHash::from(preimage);
4847		per_commitment_claimable_data
4848			.iter()
4849			.filter_map(|(htlc, _)| {
4850				if let Some(transaction_output_index) = htlc.transaction_output_index {
4851					if htlc.offered && htlc.payment_hash == matching_payment_hash {
4852						let htlc_data = PackageSolvingData::CounterpartyOfferedHTLCOutput(
4853							CounterpartyOfferedHTLCOutput::build(
4854								per_commitment_point,
4855								preimage,
4856								htlc.clone(),
4857								funding_spent.channel_parameters.clone(),
4858								confirmation_height,
4859							),
4860						);
4861						Some(PackageTemplate::build_package(
4862							commitment_txid,
4863							transaction_output_index,
4864							htlc_data,
4865							htlc.cltv_expiry,
4866						))
4867					} else {
4868						None
4869					}
4870				} else {
4871					None
4872				}
4873			})
4874			.collect()
4875	}
4876
4877	/// Returns the HTLC claim package templates and the counterparty output info
4878	fn get_counterparty_output_claim_info(
4879		&self, funding_spent: &FundingScope, commitment_number: u64, commitment_txid: Txid,
4880		tx: &Transaction,
4881		per_commitment_claimable_data: &[(HTLCOutputInCommitment, Option<Box<HTLCSource>>)],
4882		confirmation_height: Option<u32>,
4883	) -> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo) {
4884		let mut claimable_outpoints = Vec::new();
4885		let mut to_counterparty_output_info: CommitmentTxCounterpartyOutputInfo = None;
4886
4887		let per_commitment_point = match self.get_point_for_commitment_number(commitment_number) {
4888			Some(point) => point,
4889			None => return (claimable_outpoints, to_counterparty_output_info),
4890		};
4891
4892		let revocation_pubkey = RevocationKey::from_basepoint(
4893			&self.onchain_tx_handler.secp_ctx,
4894			&self.holder_revocation_basepoint,
4895			&per_commitment_point,
4896		);
4897		let delayed_key = DelayedPaymentKey::from_basepoint(
4898			&self.onchain_tx_handler.secp_ctx,
4899			&self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
4900			&per_commitment_point,
4901		);
4902		let revokeable_p2wsh = chan_utils::get_revokeable_redeemscript(
4903			&revocation_pubkey,
4904			self.counterparty_commitment_params.on_counterparty_tx_csv,
4905			&delayed_key,
4906		)
4907		.to_p2wsh();
4908		for (idx, outp) in tx.output.iter().enumerate() {
4909			if outp.script_pubkey == revokeable_p2wsh {
4910				to_counterparty_output_info =
4911					Some((idx.try_into().expect("Can't have > 2^32 outputs"), outp.value));
4912			}
4913		}
4914
4915		for &(ref htlc, _) in per_commitment_claimable_data.iter() {
4916			if let Some(transaction_output_index) = htlc.transaction_output_index {
4917				if transaction_output_index as usize >= tx.output.len()
4918					|| tx.output[transaction_output_index as usize].value
4919						!= htlc.to_bitcoin_amount()
4920				{
4921					// per_commitment_data is corrupt or our commitment signing key leaked!
4922					return (claimable_outpoints, to_counterparty_output_info);
4923				}
4924				let preimage = if htlc.offered {
4925					if let Some((p, _)) = self.payment_preimages.get(&htlc.payment_hash) {
4926						Some(*p)
4927					} else {
4928						None
4929					}
4930				} else {
4931					None
4932				};
4933				if preimage.is_some() || !htlc.offered {
4934					let counterparty_htlc_outp = if htlc.offered {
4935						PackageSolvingData::CounterpartyOfferedHTLCOutput(
4936							CounterpartyOfferedHTLCOutput::build(
4937								per_commitment_point,
4938								preimage.unwrap(),
4939								htlc.clone(),
4940								funding_spent.channel_parameters.clone(),
4941								confirmation_height,
4942							),
4943						)
4944					} else {
4945						PackageSolvingData::CounterpartyReceivedHTLCOutput(
4946							CounterpartyReceivedHTLCOutput::build(
4947								per_commitment_point,
4948								htlc.clone(),
4949								funding_spent.channel_parameters.clone(),
4950								confirmation_height,
4951							),
4952						)
4953					};
4954					let counterparty_package = PackageTemplate::build_package(
4955						commitment_txid,
4956						transaction_output_index,
4957						counterparty_htlc_outp,
4958						htlc.cltv_expiry,
4959					);
4960					claimable_outpoints.push(counterparty_package);
4961				}
4962			}
4963		}
4964
4965		(claimable_outpoints, to_counterparty_output_info)
4966	}
4967
4968	/// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
4969	#[rustfmt::skip]
4970	fn check_spend_counterparty_htlc<L: Deref>(
4971		&mut self, tx: &Transaction, commitment_number: u64, commitment_txid: &Txid, height: u32, logger: &L
4972	) -> (Vec<PackageTemplate>, Option<TransactionOutputs>) where L::Target: Logger {
4973		let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
4974		let per_commitment_key = match SecretKey::from_slice(&secret) {
4975			Ok(key) => key,
4976			Err(_) => return (Vec::new(), None)
4977		};
4978		let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
4979
4980		let funding_spent = get_confirmed_funding_scope!(self);
4981		debug_assert!(funding_spent.counterparty_claimable_outpoints.contains_key(commitment_txid));
4982
4983		let htlc_txid = tx.compute_txid();
4984		let mut claimable_outpoints = vec![];
4985		let mut outputs_to_watch = None;
4986		// Previously, we would only claim HTLCs from revoked HTLC transactions if they had 1 input
4987		// with a witness of 5 elements and 1 output. This wasn't enough for anchor outputs, as the
4988		// counterparty can now aggregate multiple HTLCs into a single transaction thanks to
4989		// `SIGHASH_SINGLE` remote signatures, leading us to not claim any HTLCs upon seeing a
4990		// confirmed revoked HTLC transaction (for more details, see
4991		// https://lists.linuxfoundation.org/pipermail/lightning-dev/2022-April/003561.html).
4992		//
4993		// We make sure we're not vulnerable to this case by checking all inputs of the transaction,
4994		// and claim those which spend the commitment transaction, have a witness of 5 elements, and
4995		// have a corresponding output at the same index within the transaction.
4996		for (idx, input) in tx.input.iter().enumerate() {
4997			if input.previous_output.txid == *commitment_txid && input.witness.len() == 5 && tx.output.get(idx).is_some() {
4998				log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, idx);
4999				let revk_outp = RevokedOutput::build(
5000					per_commitment_point, per_commitment_key, tx.output[idx].value,
5001					self.funding.channel_parameters.clone(), height,
5002				);
5003				let justice_package = PackageTemplate::build_package(
5004					htlc_txid, idx as u32, PackageSolvingData::RevokedOutput(revk_outp),
5005					height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32,
5006				);
5007				claimable_outpoints.push(justice_package);
5008				if outputs_to_watch.is_none() {
5009					outputs_to_watch = Some((htlc_txid, vec![]));
5010				}
5011				outputs_to_watch.as_mut().unwrap().1.push((idx as u32, tx.output[idx].clone()));
5012			}
5013		}
5014		(claimable_outpoints, outputs_to_watch)
5015	}
5016
5017	#[rustfmt::skip]
5018	fn get_broadcasted_holder_htlc_descriptors(
5019		&self, funding: &FundingScope, holder_tx: &HolderCommitmentTransaction,
5020	) -> Vec<HTLCDescriptor> {
5021		let tx = holder_tx.trust();
5022		let mut htlcs = Vec::with_capacity(holder_tx.nondust_htlcs().len());
5023		debug_assert_eq!(holder_tx.nondust_htlcs().len(), holder_tx.counterparty_htlc_sigs.len());
5024		for (htlc, counterparty_sig) in holder_tx.nondust_htlcs().iter().zip(holder_tx.counterparty_htlc_sigs.iter()) {
5025			assert!(htlc.transaction_output_index.is_some(), "Expected transaction output index for non-dust HTLC");
5026
5027			let preimage = if htlc.offered {
5028				None
5029			} else if let Some((preimage, _)) = self.payment_preimages.get(&htlc.payment_hash) {
5030				Some(*preimage)
5031			} else {
5032				// We can't build an HTLC-Success transaction without the preimage
5033				continue;
5034			};
5035
5036			htlcs.push(HTLCDescriptor {
5037				channel_derivation_parameters: ChannelDerivationParameters {
5038					value_satoshis: funding.channel_parameters.channel_value_satoshis,
5039					keys_id: self.channel_keys_id,
5040					transaction_parameters: funding.channel_parameters.clone(),
5041				},
5042				commitment_txid: tx.txid(),
5043				per_commitment_number: tx.commitment_number(),
5044				per_commitment_point: tx.per_commitment_point(),
5045				feerate_per_kw: tx.negotiated_feerate_per_kw(),
5046				htlc: htlc.clone(),
5047				preimage,
5048				counterparty_sig: *counterparty_sig,
5049			});
5050		}
5051
5052		htlcs
5053	}
5054
5055	// Returns (1) `PackageTemplate`s that can be given to the OnchainTxHandler, so that the handler can
5056	// broadcast transactions claiming holder HTLC commitment outputs and (2) a holder revokable
5057	// script so we can detect whether a holder transaction has been seen on-chain.
5058	#[rustfmt::skip]
5059	fn get_broadcasted_holder_claims(
5060		&self, funding: &FundingScope, holder_tx: &HolderCommitmentTransaction, conf_height: u32,
5061	) -> (Vec<PackageTemplate>, Option<(ScriptBuf, PublicKey, RevocationKey)>) {
5062		let tx = holder_tx.trust();
5063		let keys = tx.keys();
5064		let redeem_script = chan_utils::get_revokeable_redeemscript(
5065			&keys.revocation_key, self.on_holder_tx_csv, &keys.broadcaster_delayed_payment_key,
5066		);
5067		let broadcasted_holder_revokable_script = Some((
5068			redeem_script.to_p2wsh(), holder_tx.per_commitment_point(), keys.revocation_key.clone(),
5069		));
5070
5071		let claim_requests = self.get_broadcasted_holder_htlc_descriptors(funding, holder_tx).into_iter()
5072			.map(|htlc_descriptor| {
5073				let counterparty_spendable_height = if htlc_descriptor.htlc.offered {
5074					conf_height
5075				} else {
5076					htlc_descriptor.htlc.cltv_expiry
5077				};
5078				let transaction_output_index = htlc_descriptor.htlc.transaction_output_index
5079					.expect("Expected transaction output index for non-dust HTLC");
5080				PackageTemplate::build_package(
5081					tx.txid(), transaction_output_index,
5082					PackageSolvingData::HolderHTLCOutput(HolderHTLCOutput::build(htlc_descriptor, conf_height)),
5083					counterparty_spendable_height,
5084				)
5085			})
5086			.collect();
5087
5088		(claim_requests, broadcasted_holder_revokable_script)
5089	}
5090
5091	// Returns holder HTLC outputs to watch and react to in case of spending.
5092	#[rustfmt::skip]
5093	fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderCommitmentTransaction) -> Vec<(u32, TxOut)> {
5094		let mut watch_outputs = Vec::with_capacity(holder_tx.nondust_htlcs().len());
5095		let tx = holder_tx.trust();
5096		for htlc in holder_tx.nondust_htlcs() {
5097			if let Some(transaction_output_index) = htlc.transaction_output_index {
5098				watch_outputs.push((
5099					transaction_output_index,
5100					tx.built_transaction().transaction.output[transaction_output_index as usize].clone(),
5101				));
5102			} else {
5103				debug_assert!(false, "Expected transaction output index for non-dust HTLC");
5104			}
5105		}
5106		watch_outputs
5107	}
5108
5109	/// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
5110	/// revoked using data in holder_claimable_outpoints.
5111	/// Should not be used if check_spend_revoked_transaction succeeds.
5112	/// Returns None unless the transaction is definitely one of our commitment transactions.
5113	fn check_spend_holder_transaction<L: Deref>(
5114		&mut self, commitment_txid: Txid, commitment_tx: &Transaction, height: u32,
5115		block_hash: &BlockHash, logger: &L,
5116	) -> Option<(Vec<PackageTemplate>, TransactionOutputs)>
5117	where
5118		L::Target: Logger,
5119	{
5120		let funding_spent = get_confirmed_funding_scope!(self);
5121
5122		// HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
5123		let holder_commitment_tx = Some((&funding_spent.current_holder_commitment_tx, true))
5124			.filter(|(current_holder_commitment_tx, _)| {
5125				current_holder_commitment_tx.trust().txid() == commitment_txid
5126			})
5127			.or_else(|| {
5128				funding_spent
5129					.prev_holder_commitment_tx
5130					.as_ref()
5131					.map(|prev_holder_commitment_tx| (prev_holder_commitment_tx, false))
5132					.filter(|(prev_holder_commitment_tx, _)| {
5133						prev_holder_commitment_tx.trust().txid() == commitment_txid
5134					})
5135			});
5136
5137		if let Some((holder_commitment_tx, current)) = holder_commitment_tx {
5138			let funding_txid_spent = commitment_tx.input[0].previous_output.txid;
5139			assert_eq!(funding_spent.funding_txid(), funding_txid_spent);
5140
5141			let current_msg = if current { "latest holder" } else { "previous holder" };
5142			log_info!(logger, "Got broadcast of {current_msg} commitment tx {commitment_txid}, searching for available HTLCs to claim");
5143
5144			let (claim_requests, broadcasted_holder_revokable_script) =
5145				self.get_broadcasted_holder_claims(funding_spent, holder_commitment_tx, height);
5146			self.broadcasted_holder_revokable_script = broadcasted_holder_revokable_script;
5147			let watch_outputs = self.get_broadcasted_holder_watch_outputs(holder_commitment_tx);
5148
5149			if current {
5150				fail_unbroadcast_htlcs!(
5151					self,
5152					current_msg,
5153					commitment_txid,
5154					commitment_tx,
5155					height,
5156					block_hash,
5157					holder_commitment_htlcs!(self, CURRENT_WITH_SOURCES),
5158					logger
5159				);
5160			} else {
5161				fail_unbroadcast_htlcs!(
5162					self,
5163					current_msg,
5164					commitment_txid,
5165					commitment_tx,
5166					height,
5167					block_hash,
5168					holder_commitment_htlcs!(self, PREV_WITH_SOURCES).unwrap(),
5169					logger
5170				);
5171			}
5172
5173			Some((claim_requests, (commitment_txid, watch_outputs)))
5174		} else {
5175			None
5176		}
5177	}
5178
5179	/// Cancels any existing pending claims for a commitment that previously confirmed and has now
5180	/// been replaced by another.
5181	#[rustfmt::skip]
5182	pub fn cancel_prev_commitment_claims<L: Deref>(
5183		&mut self, logger: &L, confirmed_commitment_txid: &Txid
5184	) where L::Target: Logger {
5185		for (counterparty_commitment_txid, _) in &self.counterparty_commitment_txn_on_chain {
5186			// Cancel any pending claims for counterparty commitments we've seen confirm.
5187			if counterparty_commitment_txid == confirmed_commitment_txid {
5188				continue;
5189			}
5190			// If we have generated claims for counterparty_commitment_txid earlier, we can rely on always
5191			// having claim related htlcs for counterparty_commitment_txid in counterparty_claimable_outpoints.
5192			for funding in core::iter::once(&self.funding).chain(self.pending_funding.iter()) {
5193				let mut found_claim = false;
5194				for (htlc, _) in funding.counterparty_claimable_outpoints.get(counterparty_commitment_txid).unwrap_or(&vec![]) {
5195					let mut outpoint = BitcoinOutPoint { txid: *counterparty_commitment_txid, vout: 0 };
5196					if let Some(vout) = htlc.transaction_output_index {
5197						outpoint.vout = vout;
5198						if self.onchain_tx_handler.abandon_claim(&outpoint) {
5199							found_claim = true;
5200						}
5201					}
5202				}
5203				if found_claim {
5204					log_trace!(logger, "Canceled claims for previously confirmed counterparty commitment with txid {counterparty_commitment_txid}");
5205				}
5206			}
5207		}
5208		// Cancel any pending claims for any holder commitments in case they had previously
5209		// confirmed or been signed (in which case we will start attempting to claim without
5210		// waiting for confirmation).
5211		for funding in core::iter::once(&self.funding).chain(self.pending_funding.iter()) {
5212			if funding.current_holder_commitment_tx.trust().txid() != *confirmed_commitment_txid {
5213				let mut found_claim = false;
5214				let txid = funding.current_holder_commitment_tx.trust().txid();
5215				let mut outpoint = BitcoinOutPoint { txid, vout: 0 };
5216				for htlc in funding.current_holder_commitment_tx.nondust_htlcs() {
5217					if let Some(vout) = htlc.transaction_output_index {
5218						outpoint.vout = vout;
5219						if self.onchain_tx_handler.abandon_claim(&outpoint) {
5220							found_claim = true;
5221						}
5222					} else {
5223						debug_assert!(false, "Expected transaction output index for non-dust HTLC");
5224					}
5225				}
5226				if found_claim {
5227					log_trace!(logger, "Canceled claims for previously broadcast holder commitment with txid {txid}");
5228				}
5229			}
5230			if let Some(prev_holder_commitment_tx) = &funding.prev_holder_commitment_tx {
5231				let txid = prev_holder_commitment_tx.trust().txid();
5232				if txid != *confirmed_commitment_txid {
5233					let mut found_claim = false;
5234					let mut outpoint = BitcoinOutPoint { txid, vout: 0 };
5235					for htlc in prev_holder_commitment_tx.nondust_htlcs() {
5236						if let Some(vout) = htlc.transaction_output_index {
5237							outpoint.vout = vout;
5238							if self.onchain_tx_handler.abandon_claim(&outpoint) {
5239								found_claim = true;
5240							}
5241						} else {
5242							debug_assert!(false, "Expected transaction output index for non-dust HTLC");
5243						}
5244					}
5245					if found_claim {
5246						log_trace!(logger, "Canceled claims for previously broadcast holder commitment with txid {txid}");
5247					}
5248				}
5249			}
5250		}
5251	}
5252
5253	#[cfg(any(test, feature = "_test_utils", feature = "unsafe_revoked_tx_signing"))]
5254	/// Note that this includes possibly-locktimed-in-the-future transactions!
5255	#[rustfmt::skip]
5256	fn unsafe_get_latest_holder_commitment_txn<L: Deref>(
5257		&mut self, logger: &WithChannelMonitor<L>
5258	) -> Vec<Transaction> where L::Target: Logger {
5259		log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
5260		let commitment_tx = {
5261			let sig = self.onchain_tx_handler.signer.unsafe_sign_holder_commitment(
5262				&self.funding.channel_parameters, &self.funding.current_holder_commitment_tx,
5263				&self.onchain_tx_handler.secp_ctx,
5264			).expect("sign holder commitment");
5265			let redeem_script = self.funding.channel_parameters.make_funding_redeemscript();
5266			self.funding.current_holder_commitment_tx.add_holder_sig(&redeem_script, sig)
5267		};
5268		let mut holder_transactions = vec![commitment_tx];
5269
5270		if self.channel_type_features().supports_anchors_zero_fee_htlc_tx()
5271			|| self.channel_type_features().supports_anchor_zero_fee_commitments()
5272		{
5273			// HTLC transactions in these channels require external funding before finalized,
5274			// so we return the commitment transaction alone here.
5275			//
5276			// In 0FC channels, we *could* use HTLC transactions to pay for fees on a
5277			// 0FC commitment transaction to save the fixed transaction overhead
5278			// (locktime + version), but we would still have to pay for fees using
5279			// external UTXOs to avoid invalidating the counterparty HTLC signature.
5280			// This is something we would consider in the future.
5281			//
5282			// Furthermore, we can't broadcast a HTLC claim transaction while the
5283			// anchor claim transaction and its parent are still unconfirmed due to the
5284			// current single-child restriction on TRUC transactions.
5285			return holder_transactions;
5286		}
5287
5288		self.get_broadcasted_holder_htlc_descriptors(&self.funding, &self.funding.current_holder_commitment_tx)
5289			.into_iter()
5290			.for_each(|htlc_descriptor| {
5291				let txid = self.funding.current_holder_commitment_tx.trust().txid();
5292				let vout = htlc_descriptor.htlc.transaction_output_index
5293					.expect("Expected transaction output index for non-dust HTLC");
5294				let htlc_output = HolderHTLCOutput::build(htlc_descriptor, 0);
5295				if let Some(htlc_tx) = htlc_output.get_maybe_signed_htlc_tx(
5296					&mut self.onchain_tx_handler, &::bitcoin::OutPoint { txid, vout },
5297				) {
5298					if htlc_tx.is_fully_signed() {
5299						holder_transactions.push(htlc_tx.0);
5300					}
5301				}
5302			});
5303
5304		holder_transactions
5305	}
5306
5307	#[rustfmt::skip]
5308	fn block_connected<B: Deref, F: Deref, L: Deref>(
5309		&mut self, header: &Header, txdata: &TransactionData, height: u32, broadcaster: B,
5310		fee_estimator: F, logger: &WithChannelMonitor<L>,
5311	) -> Vec<TransactionOutputs>
5312		where B::Target: BroadcasterInterface,
5313			F::Target: FeeEstimator,
5314			L::Target: Logger,
5315	{
5316		let block_hash = header.block_hash();
5317		self.best_block = BestBlock::new(block_hash, height);
5318
5319		let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
5320		self.transactions_confirmed(header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
5321	}
5322
5323	#[rustfmt::skip]
5324	fn best_block_updated<B: Deref, F: Deref, L: Deref>(
5325		&mut self,
5326		header: &Header,
5327		height: u32,
5328		broadcaster: B,
5329		fee_estimator: &LowerBoundedFeeEstimator<F>,
5330		logger: &WithChannelMonitor<L>,
5331	) -> Vec<TransactionOutputs>
5332	where
5333		B::Target: BroadcasterInterface,
5334		F::Target: FeeEstimator,
5335		L::Target: Logger,
5336	{
5337		let block_hash = header.block_hash();
5338
5339		if height > self.best_block.height {
5340			self.best_block = BestBlock::new(block_hash, height);
5341			log_trace!(logger, "Connecting new block {} at height {}", block_hash, height);
5342			self.block_confirmed(height, block_hash, vec![], vec![], vec![], &broadcaster, &fee_estimator, logger)
5343		} else if block_hash != self.best_block.block_hash {
5344			self.best_block = BestBlock::new(block_hash, height);
5345			log_trace!(logger, "Best block re-orged, replaced with new block {} at height {}", block_hash, height);
5346			self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
5347			let conf_target = self.closure_conf_target();
5348			self.onchain_tx_handler.blocks_disconnected(
5349				height, &broadcaster, conf_target, &self.destination_script, fee_estimator, logger,
5350			);
5351			Vec::new()
5352		} else { Vec::new() }
5353	}
5354
5355	#[rustfmt::skip]
5356	fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
5357		&mut self,
5358		header: &Header,
5359		txdata: &TransactionData,
5360		height: u32,
5361		broadcaster: B,
5362		fee_estimator: &LowerBoundedFeeEstimator<F>,
5363		logger: &WithChannelMonitor<L>,
5364	) -> Vec<TransactionOutputs>
5365	where
5366		B::Target: BroadcasterInterface,
5367		F::Target: FeeEstimator,
5368		L::Target: Logger,
5369	{
5370		let funding_seen_before = self.funding_seen_onchain;
5371		let txn_matched = self.filter_block(txdata);
5372
5373		if !self.funding_seen_onchain {
5374			for &(_, tx) in txdata.iter() {
5375				let txid = tx.compute_txid();
5376				if txid == self.funding.funding_txid() ||
5377					self.pending_funding.iter().any(|f| f.funding_txid() == txid)
5378				{
5379					self.funding_seen_onchain = true;
5380					break;
5381				}
5382			}
5383		}
5384
5385		for tx in &txn_matched {
5386			let mut output_val = Amount::ZERO;
5387			for out in tx.output.iter() {
5388				if out.value > Amount::MAX_MONEY { panic!("Value-overflowing transaction provided to block connected"); }
5389				output_val += out.value;
5390				if output_val > Amount::MAX_MONEY { panic!("Value-overflowing transaction provided to block connected"); }
5391			}
5392		}
5393
5394		let block_hash = header.block_hash();
5395
5396		// We may need to broadcast our holder commitment if we see a funding transaction reorg,
5397		// with a different funding transaction confirming. It's possible we process a
5398		// holder/counterparty commitment within this same block that would invalidate the one we're
5399		// intending to broadcast, so we track whether we should broadcast and wait until all
5400		// transactions in the block have been processed.
5401		let mut should_broadcast_commitment = false;
5402
5403		let mut watch_outputs = Vec::new();
5404		let mut claimable_outpoints = Vec::new();
5405
5406		if self.is_manual_broadcast && !funding_seen_before && self.funding_seen_onchain && self.holder_tx_signed
5407		{
5408			should_broadcast_commitment = true;
5409		}
5410		'tx_iter: for tx in &txn_matched {
5411			let txid = tx.compute_txid();
5412			log_trace!(logger, "Transaction {} confirmed in block {}", txid , block_hash);
5413			// If a transaction has already been confirmed, ensure we don't bother processing it duplicatively.
5414			if self.alternative_funding_confirmed.map(|(alternative_funding_txid, _)| alternative_funding_txid == txid).unwrap_or(false) {
5415				log_debug!(logger, "Skipping redundant processing of funding-spend tx {} as it was previously confirmed", txid);
5416				continue 'tx_iter;
5417			}
5418			if Some(txid) == self.funding_spend_confirmed {
5419				log_debug!(logger, "Skipping redundant processing of funding-spend tx {} as it was previously confirmed", txid);
5420				continue 'tx_iter;
5421			}
5422			for ev in self.onchain_events_awaiting_threshold_conf.iter() {
5423				if ev.txid == txid {
5424					if let Some(conf_hash) = ev.block_hash {
5425						assert_eq!(header.block_hash(), conf_hash,
5426							"Transaction {} was already confirmed and is being re-confirmed in a different block.\n\
5427							This indicates a severe bug in the transaction connection logic - a reorg should have been processed first!", ev.txid);
5428					}
5429					log_debug!(logger, "Skipping redundant processing of confirming tx {} as it was previously confirmed", txid);
5430					continue 'tx_iter;
5431				}
5432			}
5433			for htlc in self.htlcs_resolved_on_chain.iter() {
5434				if Some(txid) == htlc.resolving_txid {
5435					log_debug!(logger, "Skipping redundant processing of HTLC resolution tx {} as it was previously confirmed", txid);
5436					continue 'tx_iter;
5437				}
5438			}
5439			for spendable_txid in self.spendable_txids_confirmed.iter() {
5440				if txid == *spendable_txid {
5441					log_debug!(logger, "Skipping redundant processing of spendable tx {} as it was previously confirmed", txid);
5442					continue 'tx_iter;
5443				}
5444			}
5445
5446			// A splice/dual-funded RBF transaction has confirmed. We can't promote the
5447			// `FundingScope` scope until we see the
5448			// [`ChannelMonitorUpdateStep::RenegotiatedFundingLocked`] for it, but we track the txid
5449			// so we know which holder commitment transaction we may need to broadcast.
5450			if let Some(alternative_funding) = self
5451				.pending_funding
5452				.iter()
5453				.find(|funding| funding.funding_txid() == txid)
5454			{
5455				assert!(self.alternative_funding_confirmed.is_none());
5456				assert!(
5457					!self.onchain_events_awaiting_threshold_conf.iter()
5458						.any(|e| matches!(e.event, OnchainEvent::AlternativeFundingConfirmation {}))
5459				);
5460				assert!(self.funding_spend_confirmed.is_none());
5461				assert!(
5462					!self.onchain_events_awaiting_threshold_conf.iter()
5463						.any(|e| matches!(e.event, OnchainEvent::FundingSpendConfirmation { .. }))
5464				);
5465
5466				let (desc, msg) = if alternative_funding.is_splice() {
5467					debug_assert!(tx.input.iter().any(|input| {
5468						let funding_outpoint = self.funding.funding_outpoint().into_bitcoin_outpoint();
5469						input.previous_output == funding_outpoint
5470					}));
5471					("Splice", "splice_locked")
5472				} else {
5473					("Dual-funded RBF", "channel_ready")
5474				};
5475				let action = if self.holder_tx_signed || self.funding_spend_seen {
5476					", broadcasting holder commitment transaction".to_string()
5477				} else if !self.no_further_updates_allowed() {
5478					format!(", waiting for `{msg}` exchange")
5479				} else {
5480					"".to_string()
5481				};
5482				log_info!(logger, "{desc} for channel {} confirmed with txid {txid}{action}", self.channel_id());
5483
5484				self.alternative_funding_confirmed = Some((txid, height));
5485
5486				if self.no_further_updates_allowed() {
5487					// We can no longer rely on
5488					// [`ChannelMonitorUpdateStep::RenegotiatedFundingLocked`] to promote the
5489					// scope; do so when the funding is no longer under reorg risk.
5490					self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
5491						txid,
5492						transaction: Some((*tx).clone()),
5493						height,
5494						block_hash: Some(block_hash),
5495						event: OnchainEvent::AlternativeFundingConfirmation {},
5496					});
5497				}
5498
5499				if self.holder_tx_signed || self.funding_spend_seen {
5500					// Cancel any previous claims that are no longer valid as they stemmed from a
5501					// different funding transaction.
5502					let new_holder_commitment_txid =
5503						alternative_funding.current_holder_commitment_tx.trust().txid();
5504					self.cancel_prev_commitment_claims(&logger, &new_holder_commitment_txid);
5505
5506					// We either attempted to broadcast a holder commitment, or saw one confirm
5507					// onchain, so broadcast the new holder commitment for the confirmed funding to
5508					// claim our funds as the channel is no longer operational.
5509					should_broadcast_commitment = true;
5510				}
5511
5512				continue 'tx_iter;
5513			}
5514
5515			if tx.input.len() == 1 {
5516				// Assuming our keys were not leaked (in which case we're screwed no matter what),
5517				// commitment transactions and HTLC transactions will all only ever have one input
5518				// (except for HTLC transactions for channels with anchor outputs), which is an easy
5519				// way to filter out any potential non-matching txn for lazy filters.
5520				if let Some(funding_txid_spent) = core::iter::once(&self.funding)
5521					.chain(self.pending_funding.iter())
5522					.find(|funding| {
5523						let funding_outpoint = funding.funding_outpoint().into_bitcoin_outpoint();
5524						funding_outpoint == tx.input[0].previous_output
5525					})
5526					.map(|funding| funding.funding_txid())
5527				{
5528					assert_eq!(
5529						funding_txid_spent,
5530						self.alternative_funding_confirmed
5531							.map(|(txid, _)| txid)
5532							.unwrap_or_else(|| self.funding.funding_txid())
5533					);
5534					log_info!(logger, "Channel {} closed by funding output spend in txid {txid}",
5535						self.channel_id());
5536					if !self.funding_spend_seen {
5537						self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(()));
5538					}
5539					self.funding_spend_seen = true;
5540
5541					let mut balance_spendable_csv = None;
5542					let mut commitment_tx_to_counterparty_output = None;
5543
5544					// Is it a commitment transaction?
5545					if (tx.input[0].sequence.0 >> 8*3) as u8 == 0x80 && (tx.lock_time.to_consensus_u32() >> 8*3) as u8 == 0x20 {
5546						if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(txid, &tx, height, &block_hash, &logger) {
5547							if !new_outputs.1.is_empty() {
5548								watch_outputs.push(new_outputs);
5549							}
5550
5551							claimable_outpoints.append(&mut new_outpoints);
5552							balance_spendable_csv = Some(self.on_holder_tx_csv);
5553						} else {
5554							let mut new_watch_outputs = Vec::new();
5555							for (idx, outp) in tx.output.iter().enumerate() {
5556								new_watch_outputs.push((idx as u32, outp.clone()));
5557							}
5558							watch_outputs.push((txid, new_watch_outputs));
5559
5560							let (mut new_outpoints, counterparty_output_idx_sats) =
5561								self.check_spend_counterparty_transaction(txid, &tx, height, &block_hash, &logger);
5562							commitment_tx_to_counterparty_output = counterparty_output_idx_sats;
5563
5564							claimable_outpoints.append(&mut new_outpoints);
5565						}
5566
5567						// We've just seen a commitment confirm, which conflicts with the holder
5568						// commitment we intend to broadcast
5569						if should_broadcast_commitment {
5570							log_info!(logger, "Canceling our queued holder commitment broadcast as we've found a conflict confirm instead");
5571							should_broadcast_commitment = false;
5572						}
5573					}
5574
5575					self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
5576						txid,
5577						transaction: Some((*tx).clone()),
5578						height,
5579						block_hash: Some(block_hash),
5580						event: OnchainEvent::FundingSpendConfirmation {
5581							on_local_output_csv: balance_spendable_csv,
5582							commitment_tx_to_counterparty_output,
5583						},
5584					});
5585
5586					// Now that we've detected a confirmed commitment transaction, attempt to cancel
5587					// pending claims for any commitments that were previously confirmed such that
5588					// we don't continue claiming inputs that no longer exist.
5589					self.cancel_prev_commitment_claims(&logger, &txid);
5590				}
5591			}
5592			if tx.input.len() >= 1 {
5593				// While all commitment transactions have one input, HTLC transactions may have more
5594				// if the HTLC was present in an anchor channel. HTLCs can also be resolved in a few
5595				// other ways which can have more than one output.
5596				for tx_input in &tx.input {
5597					let commitment_txid = tx_input.previous_output.txid;
5598					if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&commitment_txid) {
5599						let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(
5600							&tx, commitment_number, &commitment_txid, height, &logger
5601						);
5602						claimable_outpoints.append(&mut new_outpoints);
5603						if let Some(new_outputs) = new_outputs_option {
5604							watch_outputs.push(new_outputs);
5605						}
5606						// Since there may be multiple HTLCs for this channel (all spending the
5607						// same commitment tx) being claimed by the counterparty within the same
5608						// transaction, and `check_spend_counterparty_htlc` already checks all the
5609						// ones relevant to this channel, we can safely break from our loop.
5610						break;
5611					}
5612				}
5613				self.is_resolving_htlc_output(&tx, height, &block_hash, logger);
5614
5615				self.check_tx_and_push_spendable_outputs(&tx, height, &block_hash, logger);
5616			}
5617		}
5618
5619		if height > self.best_block.height {
5620			self.best_block = BestBlock::new(block_hash, height);
5621		}
5622
5623		if should_broadcast_commitment {
5624			let (mut claimables, mut outputs) =
5625				self.generate_claimable_outpoints_and_watch_outputs(None, false);
5626			claimable_outpoints.append(&mut claimables);
5627			watch_outputs.append(&mut outputs);
5628		}
5629
5630		self.block_confirmed(height, block_hash, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, logger)
5631	}
5632
5633	/// Update state for new block(s)/transaction(s) confirmed. Note that the caller must update
5634	/// `self.best_block` before calling if a new best blockchain tip is available. More
5635	/// concretely, `self.best_block` must never be at a lower height than `conf_height`, avoiding
5636	/// complexity especially in
5637	/// `OnchainTx::update_claims_view_from_requests`/`OnchainTx::update_claims_view_from_matched_txn`.
5638	///
5639	/// `conf_height` should be set to the height at which any new transaction(s)/block(s) were
5640	/// confirmed at, even if it is not the current best height.
5641	#[rustfmt::skip]
5642	fn block_confirmed<B: Deref, F: Deref, L: Deref>(
5643		&mut self,
5644		conf_height: u32,
5645		conf_hash: BlockHash,
5646		txn_matched: Vec<&Transaction>,
5647		mut watch_outputs: Vec<TransactionOutputs>,
5648		mut claimable_outpoints: Vec<PackageTemplate>,
5649		broadcaster: &B,
5650		fee_estimator: &LowerBoundedFeeEstimator<F>,
5651		logger: &WithChannelMonitor<L>,
5652	) -> Vec<TransactionOutputs>
5653	where
5654		B::Target: BroadcasterInterface,
5655		F::Target: FeeEstimator,
5656		L::Target: Logger,
5657	{
5658		log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
5659		debug_assert!(self.best_block.height >= conf_height);
5660
5661		// Only generate claims if we haven't already done so (e.g., in transactions_confirmed).
5662		if claimable_outpoints.is_empty() {
5663			let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
5664			if let Some(payment_hash) = should_broadcast {
5665				let reason = ClosureReason::HTLCsTimedOut { payment_hash: Some(payment_hash) };
5666				let (mut new_outpoints, mut new_outputs) =
5667					self.generate_claimable_outpoints_and_watch_outputs(Some(reason), false);
5668				if !self.is_manual_broadcast || self.funding_seen_onchain {
5669					claimable_outpoints.append(&mut new_outpoints);
5670					watch_outputs.append(&mut new_outputs);
5671				} else {
5672					log_info!(logger, "Not broadcasting holder commitment for manual-broadcast channel before funding appears on-chain");
5673				}
5674			}
5675		}
5676
5677		// Find which on-chain events have reached their confirmation threshold.
5678		let (onchain_events_reaching_threshold_conf, onchain_events_awaiting_threshold_conf): (Vec<_>, Vec<_>) =
5679			self.onchain_events_awaiting_threshold_conf.drain(..).partition(
5680				|entry| entry.has_reached_confirmation_threshold(&self.best_block));
5681		self.onchain_events_awaiting_threshold_conf = onchain_events_awaiting_threshold_conf;
5682
5683		// Used to check for duplicate HTLC resolutions.
5684		#[cfg(debug_assertions)]
5685		let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
5686			.iter()
5687			.filter_map(|entry| match &entry.event {
5688				OnchainEvent::HTLCUpdate { source, .. } => Some(source.clone()),
5689				_ => None,
5690			})
5691			.collect();
5692		#[cfg(debug_assertions)]
5693		let mut matured_htlcs = Vec::new();
5694
5695		// Produce actionable events from on-chain events having reached their threshold.
5696		for entry in onchain_events_reaching_threshold_conf {
5697			match entry.event {
5698				OnchainEvent::HTLCUpdate { source, payment_hash, htlc_value_satoshis, commitment_tx_output_idx } => {
5699					// Check for duplicate HTLC resolutions.
5700					#[cfg(debug_assertions)]
5701					{
5702						debug_assert!(
5703							!unmatured_htlcs.contains(&source),
5704							"An unmature HTLC transaction conflicts with a maturing one; failed to \
5705							 call either transaction_unconfirmed for the conflicting transaction \
5706							 or blocks_disconnected for a block before it.");
5707						debug_assert!(
5708							!matured_htlcs.contains(&source),
5709							"A matured HTLC transaction conflicts with a maturing one; failed to \
5710							 call either transaction_unconfirmed for the conflicting transaction \
5711							 or blocks_disconnected for a block before it.");
5712						matured_htlcs.push(source.clone());
5713					}
5714
5715					log_debug!(logger, "HTLC {} failure update in {} has got enough confirmations to be passed upstream",
5716						&payment_hash, entry.txid);
5717					self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
5718						payment_hash,
5719						payment_preimage: None,
5720						source,
5721						htlc_value_satoshis,
5722					}));
5723					self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
5724						commitment_tx_output_idx,
5725						resolving_txid: Some(entry.txid),
5726						resolving_tx: entry.transaction,
5727						payment_preimage: None,
5728					});
5729				},
5730				OnchainEvent::MaturingOutput { descriptor } => {
5731					log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
5732					self.pending_events.push(Event::SpendableOutputs {
5733						outputs: vec![descriptor],
5734						channel_id: Some(self.channel_id()),
5735					});
5736					self.spendable_txids_confirmed.push(entry.txid);
5737				},
5738				OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. } => {
5739					self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
5740						commitment_tx_output_idx: Some(commitment_tx_output_idx),
5741						resolving_txid: Some(entry.txid),
5742						resolving_tx: entry.transaction,
5743						payment_preimage: preimage,
5744					});
5745				},
5746				OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } => {
5747					self.funding_spend_confirmed = Some(entry.txid);
5748					self.confirmed_commitment_tx_counterparty_output = commitment_tx_to_counterparty_output;
5749					if self.alternative_funding_confirmed.is_none() {
5750						for funding in self.pending_funding.drain(..) {
5751							self.outputs_to_watch.remove(&funding.funding_txid());
5752							self.pending_events.push(Event::DiscardFunding {
5753								channel_id: self.channel_id,
5754								funding_info: crate::events::FundingInfo::OutPoint {
5755									outpoint: funding.funding_outpoint(),
5756								},
5757							});
5758						}
5759					}
5760				},
5761				OnchainEvent::AlternativeFundingConfirmation {} => {
5762					// An alternative funding transaction has irrevocably confirmed and we're no
5763					// longer allowing monitor updates, so promote the `FundingScope` now.
5764					debug_assert!(self.no_further_updates_allowed());
5765					debug_assert_ne!(self.funding.funding_txid(), entry.txid);
5766					if let Err(_) = self.promote_funding(entry.txid) {
5767						debug_assert!(false);
5768						log_error!(logger, "Missing scope for alternative funding confirmation with txid {}", entry.txid);
5769					}
5770				},
5771			}
5772		}
5773
5774		if self.no_further_updates_allowed() {
5775			// Fail back HTLCs on backwards channels if they expire within
5776			// `LATENCY_GRACE_PERIOD_BLOCKS` blocks and the channel is closed (i.e. we're at a
5777			// point where no further off-chain updates will be accepted). If we haven't seen the
5778			// preimage for an HTLC by the time the previous hop's timeout expires, we've lost that
5779			// HTLC, so we might as well fail it back instead of having our counterparty force-close
5780			// the inbound channel.
5781			let current_counterparty_htlcs = if let Some(txid) = self.funding.current_counterparty_commitment_txid {
5782				if let Some(htlc_outputs) = self.funding.counterparty_claimable_outpoints.get(&txid) {
5783					Some(htlc_outputs.iter().map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))))
5784				} else { None }
5785			} else { None }.into_iter().flatten();
5786
5787			let prev_counterparty_htlcs = if let Some(txid) = self.funding.prev_counterparty_commitment_txid {
5788				if let Some(htlc_outputs) = self.funding.counterparty_claimable_outpoints.get(&txid) {
5789					Some(htlc_outputs.iter().map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))))
5790				} else { None }
5791			} else { None }.into_iter().flatten();
5792
5793			let htlcs = holder_commitment_htlcs!(self, CURRENT_WITH_SOURCES)
5794				.chain(current_counterparty_htlcs)
5795				.chain(prev_counterparty_htlcs);
5796
5797			let height = self.best_block.height;
5798			for (htlc, source_opt) in htlcs {
5799				// Only check forwarded HTLCs' previous hops
5800				let source = match source_opt {
5801					Some(source) => source,
5802					None => continue,
5803				};
5804				let inbound_htlc_expiry = match source.inbound_htlc_expiry() {
5805					Some(cltv_expiry) => cltv_expiry,
5806					None => continue,
5807				};
5808				let max_expiry_height = height.saturating_add(LATENCY_GRACE_PERIOD_BLOCKS);
5809				if inbound_htlc_expiry > max_expiry_height {
5810					continue;
5811				}
5812				let duplicate_event = self.pending_monitor_events.iter().any(
5813					|update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
5814						upd.source == *source
5815					} else { false });
5816				if duplicate_event {
5817					continue;
5818				}
5819				if !self.failed_back_htlc_ids.insert(SentHTLCId::from_source(source)) {
5820					continue;
5821				}
5822				if !duplicate_event {
5823					log_error!(logger, "Failing back HTLC {} upstream to preserve the \
5824						channel as the forward HTLC hasn't resolved and our backward HTLC \
5825						expires soon at {}", log_bytes!(htlc.payment_hash.0), inbound_htlc_expiry);
5826					self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
5827						source: source.clone(),
5828						payment_preimage: None,
5829						payment_hash: htlc.payment_hash,
5830						htlc_value_satoshis: Some(htlc.amount_msat / 1000),
5831					}));
5832				}
5833			}
5834		}
5835
5836		let conf_target = self.closure_conf_target();
5837		self.onchain_tx_handler.update_claims_view_from_requests(
5838			claimable_outpoints, conf_height, self.best_block.height, broadcaster, conf_target,
5839			&self.destination_script, fee_estimator, logger,
5840		);
5841		self.onchain_tx_handler.update_claims_view_from_matched_txn(
5842			&txn_matched, conf_height, conf_hash, self.best_block.height, broadcaster, conf_target,
5843			&self.destination_script, fee_estimator, logger,
5844		);
5845
5846		// Determine new outputs to watch by comparing against previously known outputs to watch,
5847		// updating the latter in the process.
5848		watch_outputs.retain(|&(ref txid, ref txouts)| {
5849			let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
5850			self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
5851		});
5852		#[cfg(test)]
5853		{
5854			// If we see a transaction for which we registered outputs previously,
5855			// make sure the registered scriptpubkey at the expected index match
5856			// the actual transaction output one. We failed this case before #653.
5857			for tx in &txn_matched {
5858				if let Some(outputs) = self.get_outputs_to_watch().get(&tx.compute_txid()) {
5859					for idx_and_script in outputs.iter() {
5860						assert!((idx_and_script.0 as usize) < tx.output.len());
5861						assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
5862					}
5863				}
5864			}
5865		}
5866		watch_outputs
5867	}
5868
5869	#[rustfmt::skip]
5870	fn blocks_disconnected<B: Deref, F: Deref, L: Deref>(
5871		&mut self, fork_point: BestBlock, broadcaster: B, fee_estimator: F, logger: &WithChannelMonitor<L>
5872	) where B::Target: BroadcasterInterface,
5873		F::Target: FeeEstimator,
5874		L::Target: Logger,
5875	{
5876		let new_height = fork_point.height;
5877		log_trace!(logger, "Block(s) disconnected to height {}", new_height);
5878		assert!(self.best_block.height > fork_point.height,
5879			"Blocks disconnected must indicate disconnection from the current best height, i.e. the new chain tip must be lower than the previous best height");
5880
5881		//We may discard:
5882		//- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
5883		//- maturing spendable output has transaction paying us has been disconnected
5884		self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= new_height);
5885
5886		// TODO: Replace with `take_if` once our MSRV is >= 1.80.
5887		let mut should_broadcast_commitment = false;
5888		if let Some((_, conf_height)) = self.alternative_funding_confirmed.as_ref() {
5889			if *conf_height > new_height {
5890				self.alternative_funding_confirmed.take();
5891				if self.holder_tx_signed || self.funding_spend_seen {
5892					// Cancel any previous claims that are no longer valid as they stemmed from a
5893					// different funding transaction.
5894					let new_holder_commitment_txid =
5895						self.funding.current_holder_commitment_tx.trust().txid();
5896					self.cancel_prev_commitment_claims(&logger, &new_holder_commitment_txid);
5897
5898					should_broadcast_commitment = true;
5899				}
5900			}
5901		}
5902
5903		let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
5904		let conf_target = self.closure_conf_target();
5905		self.onchain_tx_handler.blocks_disconnected(
5906			new_height, &broadcaster, conf_target, &self.destination_script, &bounded_fee_estimator, logger
5907		);
5908
5909		// Only attempt to broadcast the new commitment after the `block_disconnected` call above so that
5910		// it doesn't get removed from the set of pending claims.
5911		if should_broadcast_commitment {
5912			self.queue_latest_holder_commitment_txn_for_broadcast(&broadcaster, &bounded_fee_estimator, logger, true);
5913		}
5914
5915		self.best_block = fork_point;
5916	}
5917
5918	#[rustfmt::skip]
5919	fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
5920		&mut self,
5921		txid: &Txid,
5922		broadcaster: B,
5923		fee_estimator: &LowerBoundedFeeEstimator<F>,
5924		logger: &WithChannelMonitor<L>,
5925	) where
5926		B::Target: BroadcasterInterface,
5927		F::Target: FeeEstimator,
5928		L::Target: Logger,
5929	{
5930		let mut removed_height = None;
5931		for entry in self.onchain_events_awaiting_threshold_conf.iter() {
5932			if entry.txid == *txid {
5933				removed_height = Some(entry.height);
5934				break;
5935			}
5936		}
5937
5938		if let Some(removed_height) = removed_height {
5939			log_info!(logger, "transaction_unconfirmed of txid {} implies height {} was reorg'd out", txid, removed_height);
5940			self.onchain_events_awaiting_threshold_conf.retain(|ref entry| if entry.height >= removed_height {
5941				log_info!(logger, "Transaction {} reorg'd out", entry.txid);
5942				false
5943			} else { true });
5944		}
5945
5946		debug_assert!(!self.onchain_events_awaiting_threshold_conf.iter().any(|ref entry| entry.txid == *txid));
5947
5948		// TODO: Replace with `take_if` once our MSRV is >= 1.80.
5949		let mut should_broadcast_commitment = false;
5950		if let Some((alternative_funding_txid, _)) = self.alternative_funding_confirmed.as_ref() {
5951			if alternative_funding_txid == txid {
5952				self.alternative_funding_confirmed.take();
5953				if self.holder_tx_signed || self.funding_spend_seen {
5954					// Cancel any previous claims that are no longer valid as they stemmed from a
5955					// different funding transaction.
5956					let new_holder_commitment_txid =
5957						self.funding.current_holder_commitment_tx.trust().txid();
5958					self.cancel_prev_commitment_claims(&logger, &new_holder_commitment_txid);
5959
5960					should_broadcast_commitment = true;
5961				}
5962			}
5963		}
5964
5965		let conf_target = self.closure_conf_target();
5966		self.onchain_tx_handler.transaction_unconfirmed(
5967			txid, &broadcaster, conf_target, &self.destination_script, fee_estimator, logger
5968		);
5969
5970		// Only attempt to broadcast the new commitment after the `transaction_unconfirmed` call above so
5971		//  that it doesn't get removed from the set of pending claims.
5972		if should_broadcast_commitment {
5973			self.queue_latest_holder_commitment_txn_for_broadcast(&broadcaster, fee_estimator, logger, true);
5974		}
5975	}
5976
5977	/// Filters a block's `txdata` for transactions spending watched outputs or for any child
5978	/// transactions thereof.
5979	#[rustfmt::skip]
5980	fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
5981		let mut matched_txn = new_hash_set();
5982		txdata.iter().filter(|&&(_, tx)| {
5983			let mut matches = self.spends_watched_output(tx);
5984			for input in tx.input.iter() {
5985				if matches { break; }
5986				if matched_txn.contains(&input.previous_output.txid) {
5987					matches = true;
5988				}
5989			}
5990			if matches {
5991				matched_txn.insert(tx.compute_txid());
5992			}
5993			matches
5994		}).map(|(_, tx)| *tx).collect()
5995	}
5996
5997	/// Checks if a given transaction spends any watched outputs.
5998	#[rustfmt::skip]
5999	fn spends_watched_output(&self, tx: &Transaction) -> bool {
6000		for input in tx.input.iter() {
6001			if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
6002				for (idx, _script_pubkey) in outputs.iter() {
6003					if *idx == input.previous_output.vout {
6004						#[cfg(test)]
6005						{
6006							// If the expected script is a known type, check that the witness
6007							// appears to be spending the correct type (ie that the match would
6008							// actually succeed in BIP 158/159-style filters).
6009							if _script_pubkey.is_p2wsh() {
6010								if input.witness.last().unwrap().to_vec() == deliberately_bogus_accepted_htlc_witness_program() {
6011									// In at least one test we use a deliberately bogus witness
6012									// script which hit an old panic. Thus, we check for that here
6013									// and avoid the assert if its the expected bogus script.
6014									return true;
6015								}
6016
6017								assert_eq!(&bitcoin::Address::p2wsh(&ScriptBuf::from(input.witness.last().unwrap().to_vec()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
6018							} else if _script_pubkey.is_p2wpkh() {
6019								assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::CompressedPublicKey(bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap().inner), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
6020							} else if _script_pubkey == &chan_utils::shared_anchor_script_pubkey() {
6021								assert!(input.witness.is_empty());
6022							} else { panic!(); }
6023						}
6024						return true;
6025					}
6026				}
6027			}
6028		}
6029
6030		false
6031	}
6032
6033	#[rustfmt::skip]
6034	fn should_broadcast_holder_commitment_txn<L: Deref>(
6035		&self, logger: &WithChannelMonitor<L>
6036	) -> Option<PaymentHash> where L::Target: Logger {
6037		// There's no need to broadcast our commitment transaction if we've seen one confirmed (even
6038		// with 1 confirmation) as it'll be rejected as duplicate/conflicting.
6039		if self.funding_spend_confirmed.is_some() ||
6040			self.onchain_events_awaiting_threshold_conf.iter().find(|event| match event.event {
6041				OnchainEvent::FundingSpendConfirmation { .. } => true,
6042				_ => false,
6043			}).is_some()
6044		{
6045			return None;
6046		}
6047		// We need to consider all HTLCs which are:
6048		//  * in any unrevoked counterparty commitment transaction, as they could broadcast said
6049		//    transactions and we'd end up in a race, or
6050		//  * are in our latest holder commitment transaction, as this is the thing we will
6051		//    broadcast if we go on-chain.
6052		// Note that we consider HTLCs which were below dust threshold here - while they don't
6053		// strictly imply that we need to fail the channel, we need to go ahead and fail them back
6054		// to the source, and if we don't fail the channel we will have to ensure that the next
6055		// updates that peer sends us are update_fails, failing the channel if not. It's probably
6056		// easier to just fail the channel as this case should be rare enough anyway.
6057		let height = self.best_block.height;
6058		// Grace period in number of blocks we allow for an async payment to resolve before we
6059		// force-close. 4032 blocks are roughly four weeks.
6060		const ASYNC_PAYMENT_GRACE_PERIOD_BLOCKS: u32 = 4032;
6061		macro_rules! scan_commitment {
6062			($htlcs: expr, $holder_tx: expr) => {
6063				for (ref htlc, ref source) in $htlcs {
6064					// For inbound HTLCs which we know the preimage for, we have to ensure we hit the
6065					// chain with enough room to claim the HTLC without our counterparty being able to
6066					// time out the HTLC first.
6067					// For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
6068					// concern is being able to claim the corresponding inbound HTLC (on another
6069					// channel) before it expires. In fact, we don't even really care if our
6070					// counterparty here claims such an outbound HTLC after it expired as long as we
6071					// can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
6072					// chain when our counterparty is waiting for expiration to off-chain fail an HTLC
6073					// we give ourselves a few blocks of headroom after expiration before going
6074					// on-chain for an expired HTLC. In the case of an outbound HTLC for
6075					// an async payment, we allow `ASYNC_PAYMENT_GRACE_PERIOD_BLOCKS` before
6076					// we force-close the channel so that if we've been offline for a
6077					// while we give a chance for the HTLC to be failed on reconnect
6078					// instead closing the channel.
6079					let htlc_outbound = $holder_tx == htlc.offered;
6080					let async_payment = htlc_outbound && matches!(
6081						source.as_deref().expect("Every outbound HTLC should have a corresponding source"),
6082						HTLCSource::OutboundRoute {
6083							bolt12_invoice: Some(PaidBolt12Invoice::StaticInvoice(_)),
6084							..
6085						}
6086					);
6087					if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height && !async_payment) ||
6088					   ( htlc_outbound && htlc.cltv_expiry + ASYNC_PAYMENT_GRACE_PERIOD_BLOCKS <= height && async_payment) ||
6089					   (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
6090						log_info!(logger, "Force-closing channel due to {} HTLC timeout - HTLC with payment hash {} expires at {}", if htlc_outbound { "outbound" } else { "inbound"}, htlc.payment_hash, htlc.cltv_expiry);
6091						return Some(htlc.payment_hash);
6092					}
6093				}
6094			}
6095		}
6096
6097		scan_commitment!(holder_commitment_htlcs!(self, CURRENT_WITH_SOURCES), true);
6098
6099		if let Some(ref txid) = self.funding.current_counterparty_commitment_txid {
6100			if let Some(ref htlc_outputs) = self.funding.counterparty_claimable_outpoints.get(txid) {
6101				scan_commitment!(htlc_outputs.iter(), false);
6102			}
6103		}
6104		if let Some(ref txid) = self.funding.prev_counterparty_commitment_txid {
6105			if let Some(ref htlc_outputs) = self.funding.counterparty_claimable_outpoints.get(txid) {
6106				scan_commitment!(htlc_outputs.iter(), false);
6107			}
6108		}
6109
6110		None
6111	}
6112
6113	/// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder
6114	/// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
6115	#[rustfmt::skip]
6116	fn is_resolving_htlc_output<L: Deref>(
6117		&mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor<L>,
6118	) where L::Target: Logger {
6119		let funding_spent = get_confirmed_funding_scope!(self);
6120
6121		'outer_loop: for input in &tx.input {
6122			let mut payment_data = None;
6123			let htlc_claim = HTLCClaim::from_witness(&input.witness);
6124			let revocation_sig_claim = htlc_claim == Some(HTLCClaim::Revocation);
6125			let accepted_preimage_claim = htlc_claim == Some(HTLCClaim::AcceptedPreimage);
6126			#[cfg(not(fuzzing))]
6127			let accepted_timeout_claim = htlc_claim == Some(HTLCClaim::AcceptedTimeout);
6128			let offered_preimage_claim = htlc_claim == Some(HTLCClaim::OfferedPreimage);
6129			#[cfg(not(fuzzing))]
6130			let offered_timeout_claim = htlc_claim == Some(HTLCClaim::OfferedTimeout);
6131
6132			let mut payment_preimage = PaymentPreimage([0; 32]);
6133			if offered_preimage_claim || accepted_preimage_claim {
6134				payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
6135			}
6136
6137			macro_rules! log_claim {
6138				($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
6139					let outbound_htlc = $holder_tx == $htlc.offered;
6140					// HTLCs must either be claimed by a matching script type or through the
6141					// revocation path:
6142					#[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
6143					debug_assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim);
6144					#[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
6145					debug_assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim);
6146					// Further, only exactly one of the possible spend paths should have been
6147					// matched by any HTLC spend:
6148					#[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
6149					debug_assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
6150					                 offered_preimage_claim as u8 + offered_timeout_claim as u8 +
6151					                 revocation_sig_claim as u8, 1);
6152					if ($holder_tx && revocation_sig_claim) ||
6153							(outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
6154						log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
6155							$tx_info, input.previous_output.txid, input.previous_output.vout, tx.compute_txid(),
6156							if outbound_htlc { "outbound" } else { "inbound" }, &$htlc.payment_hash,
6157							if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back. We can likely claim the HTLC output with a revocation claim" });
6158					} else {
6159						log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
6160							$tx_info, input.previous_output.txid, input.previous_output.vout, tx.compute_txid(),
6161							if outbound_htlc { "outbound" } else { "inbound" }, &$htlc.payment_hash,
6162							if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
6163					}
6164				}
6165			}
6166
6167			macro_rules! check_htlc_valid_counterparty {
6168				($htlc_output: expr, $per_commitment_data: expr) => {
6169						for &(ref pending_htlc, ref pending_source) in $per_commitment_data {
6170							if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
6171								if let &Some(ref source) = pending_source {
6172									log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
6173									payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
6174									break;
6175								}
6176							}
6177						}
6178				}
6179			}
6180
6181			macro_rules! scan_commitment {
6182				($funding_spent: expr, $htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
6183					for (ref htlc_output, source_option) in $htlcs {
6184						if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
6185							if let Some(ref source) = source_option {
6186								log_claim!($tx_info, $holder_tx, htlc_output, true);
6187								// We have a resolution of an HTLC either from one of our latest
6188								// holder commitment transactions or an unrevoked counterparty commitment
6189								// transaction. This implies we either learned a preimage, the HTLC
6190								// has timed out, or we screwed up. In any case, we should now
6191								// resolve the source HTLC with the original sender.
6192								payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
6193							} else if !$holder_tx {
6194								if let Some(current_counterparty_commitment_txid) = &$funding_spent.current_counterparty_commitment_txid {
6195									check_htlc_valid_counterparty!(htlc_output, $funding_spent.counterparty_claimable_outpoints.get(current_counterparty_commitment_txid).unwrap());
6196								}
6197								if payment_data.is_none() {
6198									if let Some(prev_counterparty_commitment_txid) = &$funding_spent.prev_counterparty_commitment_txid {
6199										check_htlc_valid_counterparty!(htlc_output, $funding_spent.counterparty_claimable_outpoints.get(prev_counterparty_commitment_txid).unwrap());
6200									}
6201								}
6202							}
6203							if payment_data.is_none() {
6204								log_claim!($tx_info, $holder_tx, htlc_output, false);
6205								let outbound_htlc = $holder_tx == htlc_output.offered;
6206								self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
6207									txid: tx.compute_txid(), height, block_hash: Some(*block_hash), transaction: Some(tx.clone()),
6208									event: OnchainEvent::HTLCSpendConfirmation {
6209										commitment_tx_output_idx: input.previous_output.vout,
6210										preimage: if accepted_preimage_claim || offered_preimage_claim {
6211											Some(payment_preimage) } else { None },
6212										// If this is a payment to us (ie !outbound_htlc), wait for
6213										// the CSV delay before dropping the HTLC from claimable
6214										// balance if the claim was an HTLC-Success transaction (ie
6215										// accepted_preimage_claim).
6216										on_to_local_output_csv: if accepted_preimage_claim && !outbound_htlc {
6217											Some(self.on_holder_tx_csv) } else { None },
6218									},
6219								});
6220								continue 'outer_loop;
6221							}
6222						}
6223					}
6224				}
6225			}
6226
6227			if input.previous_output.txid == funding_spent.current_holder_commitment_tx.trust().txid() {
6228				scan_commitment!(
6229					funding_spent, holder_commitment_htlcs!(self, CURRENT_WITH_SOURCES),
6230					"our latest holder commitment tx", true
6231				);
6232			}
6233			if let Some(prev_holder_commitment_tx) = funding_spent.prev_holder_commitment_tx.as_ref() {
6234				if input.previous_output.txid == prev_holder_commitment_tx.trust().txid() {
6235					scan_commitment!(
6236						funding_spent, holder_commitment_htlcs!(self, PREV_WITH_SOURCES).unwrap(),
6237						"our previous holder commitment tx", true
6238					);
6239				}
6240			}
6241			if let Some(ref htlc_outputs) = funding_spent.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
6242				let htlcs = htlc_outputs.iter()
6243					.map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed)));
6244				scan_commitment!(funding_spent, htlcs, "counterparty commitment tx", false);
6245			}
6246
6247			// Check that scan_commitment, above, decided there is some source worth relaying an
6248			// HTLC resolution backwards to and figure out whether we learned a preimage from it.
6249			if let Some((source, payment_hash, amount_msat)) = payment_data {
6250				if accepted_preimage_claim {
6251					if !self.pending_monitor_events.iter().any(
6252						|update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
6253						self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
6254							txid: tx.compute_txid(),
6255							height,
6256							block_hash: Some(*block_hash),
6257							transaction: Some(tx.clone()),
6258							event: OnchainEvent::HTLCSpendConfirmation {
6259								commitment_tx_output_idx: input.previous_output.vout,
6260								preimage: Some(payment_preimage),
6261								on_to_local_output_csv: None,
6262							},
6263						});
6264						self.counterparty_fulfilled_htlcs.insert(SentHTLCId::from_source(&source), payment_preimage);
6265						self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
6266							source,
6267							payment_preimage: Some(payment_preimage),
6268							payment_hash,
6269							htlc_value_satoshis: Some(amount_msat / 1000),
6270						}));
6271					}
6272				} else if offered_preimage_claim {
6273					if !self.pending_monitor_events.iter().any(
6274						|update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
6275							upd.source == source
6276						} else { false }) {
6277						self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
6278							txid: tx.compute_txid(),
6279							transaction: Some(tx.clone()),
6280							height,
6281							block_hash: Some(*block_hash),
6282							event: OnchainEvent::HTLCSpendConfirmation {
6283								commitment_tx_output_idx: input.previous_output.vout,
6284								preimage: Some(payment_preimage),
6285								on_to_local_output_csv: None,
6286							},
6287						});
6288						self.counterparty_fulfilled_htlcs.insert(SentHTLCId::from_source(&source), payment_preimage);
6289						self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
6290							source,
6291							payment_preimage: Some(payment_preimage),
6292							payment_hash,
6293							htlc_value_satoshis: Some(amount_msat / 1000),
6294						}));
6295					}
6296				} else {
6297					self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
6298						if entry.height != height { return true; }
6299						match entry.event {
6300							OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
6301								*htlc_source != source
6302							},
6303							_ => true,
6304						}
6305					});
6306					let entry = OnchainEventEntry {
6307						txid: tx.compute_txid(),
6308						transaction: Some(tx.clone()),
6309						height,
6310						block_hash: Some(*block_hash),
6311						event: OnchainEvent::HTLCUpdate {
6312							source,
6313							payment_hash,
6314							htlc_value_satoshis: Some(amount_msat / 1000),
6315							commitment_tx_output_idx: Some(input.previous_output.vout),
6316						},
6317					};
6318					log_info!(logger, "Failing HTLC with payment_hash {} timeout by a spend tx, waiting for confirmation (at height {})", &payment_hash, entry.confirmation_threshold());
6319					self.onchain_events_awaiting_threshold_conf.push(entry);
6320				}
6321			}
6322		}
6323	}
6324
6325	#[rustfmt::skip]
6326	fn get_spendable_outputs(&self, funding_spent: &FundingScope, tx: &Transaction) -> Vec<SpendableOutputDescriptor> {
6327		let mut spendable_outputs = Vec::new();
6328		for (i, outp) in tx.output.iter().enumerate() {
6329			if outp.script_pubkey == self.destination_script {
6330				spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
6331					outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
6332					output: outp.clone(),
6333					channel_keys_id: Some(self.channel_keys_id),
6334				});
6335			}
6336			if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
6337				if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
6338					spendable_outputs.push(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
6339						outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
6340						per_commitment_point: broadcasted_holder_revokable_script.1,
6341						to_self_delay: self.on_holder_tx_csv,
6342						output: outp.clone(),
6343						revocation_pubkey: broadcasted_holder_revokable_script.2,
6344						channel_keys_id: self.channel_keys_id,
6345						channel_value_satoshis: funding_spent.channel_parameters.channel_value_satoshis,
6346						channel_transaction_parameters: Some(funding_spent.channel_parameters.clone()),
6347					}));
6348				}
6349			}
6350			if self.counterparty_payment_script == outp.script_pubkey {
6351				spendable_outputs.push(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
6352					outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
6353					output: outp.clone(),
6354					channel_keys_id: self.channel_keys_id,
6355					channel_value_satoshis: funding_spent.channel_parameters.channel_value_satoshis,
6356					channel_transaction_parameters: Some(funding_spent.channel_parameters.clone()),
6357				}));
6358			}
6359			if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
6360				spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
6361					outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
6362					output: outp.clone(),
6363					channel_keys_id: Some(self.channel_keys_id),
6364				});
6365			}
6366		}
6367		spendable_outputs
6368	}
6369
6370	/// Checks if the confirmed transaction is paying funds back to some address we can assume to
6371	/// own.
6372	#[rustfmt::skip]
6373	fn check_tx_and_push_spendable_outputs<L: Deref>(
6374		&mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor<L>,
6375	) where L::Target: Logger {
6376		let funding_spent = get_confirmed_funding_scope!(self);
6377		for spendable_output in self.get_spendable_outputs(funding_spent, tx) {
6378			let entry = OnchainEventEntry {
6379				txid: tx.compute_txid(),
6380				transaction: Some(tx.clone()),
6381				height,
6382				block_hash: Some(*block_hash),
6383				event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
6384			};
6385			log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
6386			self.onchain_events_awaiting_threshold_conf.push(entry);
6387		}
6388	}
6389
6390	fn channel_type_features(&self) -> &ChannelTypeFeatures {
6391		&self.funding.channel_parameters.channel_type_features
6392	}
6393}
6394
6395impl<Signer: EcdsaChannelSigner, T: Deref, F: Deref, L: Deref> chain::Listen
6396	for (ChannelMonitor<Signer>, T, F, L)
6397where
6398	T::Target: BroadcasterInterface,
6399	F::Target: FeeEstimator,
6400	L::Target: Logger,
6401{
6402	fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
6403		self.0.block_connected(header, txdata, height, &*self.1, &*self.2, &self.3);
6404	}
6405
6406	fn blocks_disconnected(&self, fork_point: BestBlock) {
6407		self.0.blocks_disconnected(fork_point, &*self.1, &*self.2, &self.3);
6408	}
6409}
6410
6411impl<Signer: EcdsaChannelSigner, M, T: Deref, F: Deref, L: Deref> chain::Confirm for (M, T, F, L)
6412where
6413	M: Deref<Target = ChannelMonitor<Signer>>,
6414	T::Target: BroadcasterInterface,
6415	F::Target: FeeEstimator,
6416	L::Target: Logger,
6417{
6418	fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) {
6419		self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &self.3);
6420	}
6421
6422	fn transaction_unconfirmed(&self, txid: &Txid) {
6423		self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &self.3);
6424	}
6425
6426	fn best_block_updated(&self, header: &Header, height: u32) {
6427		self.0.best_block_updated(header, height, &*self.1, &*self.2, &self.3);
6428	}
6429
6430	fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
6431		self.0.get_relevant_txids()
6432	}
6433}
6434
6435const MAX_ALLOC_SIZE: usize = 64 * 1024;
6436
6437impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP)>
6438	for (BlockHash, ChannelMonitor<SP::EcdsaSigner>)
6439{
6440	fn read<R: io::Read>(reader: &mut R, args: (&'a ES, &'b SP)) -> Result<Self, DecodeError> {
6441		match <Option<Self>>::read(reader, args) {
6442			Ok(Some(res)) => Ok(res),
6443			Ok(None) => Err(DecodeError::UnknownRequiredFeature),
6444			Err(e) => Err(e),
6445		}
6446	}
6447}
6448
6449impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP)>
6450	for Option<(BlockHash, ChannelMonitor<SP::EcdsaSigner>)>
6451{
6452	#[rustfmt::skip]
6453	fn read<R: io::Read>(reader: &mut R, args: (&'a ES, &'b SP)) -> Result<Self, DecodeError> {
6454		macro_rules! unwrap_obj {
6455			($key: expr) => {
6456				match $key {
6457					Ok(res) => res,
6458					Err(_) => return Err(DecodeError::InvalidValue),
6459				}
6460			}
6461		}
6462
6463		let (entropy_source, signer_provider) = args;
6464
6465		let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
6466
6467		let latest_update_id: u64 = Readable::read(reader)?;
6468		let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
6469
6470		let destination_script = Readable::read(reader)?;
6471		let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
6472			0 => {
6473				let revokable_address = Readable::read(reader)?;
6474				let per_commitment_point = Readable::read(reader)?;
6475				let revokable_script = Readable::read(reader)?;
6476				Some((revokable_address, per_commitment_point, revokable_script))
6477			},
6478			1 => { None },
6479			_ => return Err(DecodeError::InvalidValue),
6480		};
6481		let mut counterparty_payment_script: ScriptBuf = Readable::read(reader)?;
6482		let shutdown_script = {
6483			let script = <ScriptBuf as Readable>::read(reader)?;
6484			if script.is_empty() { None } else { Some(script) }
6485		};
6486
6487		let channel_keys_id = Readable::read(reader)?;
6488		let holder_revocation_basepoint = Readable::read(reader)?;
6489		// Technically this can fail and serialize fail a round-trip, but only for serialization of
6490		// barely-init'd ChannelMonitors that we can't do anything with.
6491		let outpoint = OutPoint {
6492			txid: Readable::read(reader)?,
6493			index: Readable::read(reader)?,
6494		};
6495		let _funding_script: ScriptBuf = Readable::read(reader)?;
6496		let current_counterparty_commitment_txid = Readable::read(reader)?;
6497		let prev_counterparty_commitment_txid = Readable::read(reader)?;
6498
6499		let counterparty_commitment_params = Readable::read(reader)?;
6500		let _funding_redeemscript: ScriptBuf = Readable::read(reader)?;
6501		let channel_value_satoshis = Readable::read(reader)?;
6502
6503		let their_cur_per_commitment_points = {
6504			let first_idx = <U48 as Readable>::read(reader)?.0;
6505			if first_idx == 0 {
6506				None
6507			} else {
6508				let first_point = Readable::read(reader)?;
6509				let second_point_slice: [u8; 33] = Readable::read(reader)?;
6510				if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
6511					Some((first_idx, first_point, None))
6512				} else {
6513					Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
6514				}
6515			}
6516		};
6517
6518		let on_holder_tx_csv: u16 = Readable::read(reader)?;
6519
6520		let commitment_secrets = Readable::read(reader)?;
6521
6522		macro_rules! read_htlc_in_commitment {
6523			() => {
6524				{
6525					let offered: bool = Readable::read(reader)?;
6526					let amount_msat: u64 = Readable::read(reader)?;
6527					let cltv_expiry: u32 = Readable::read(reader)?;
6528					let payment_hash: PaymentHash = Readable::read(reader)?;
6529					let transaction_output_index: Option<u32> = Readable::read(reader)?;
6530
6531					HTLCOutputInCommitment {
6532						offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
6533					}
6534				}
6535			}
6536		}
6537
6538		let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
6539		let mut counterparty_claimable_outpoints = hash_map_with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
6540		for _ in 0..counterparty_claimable_outpoints_len {
6541			let txid: Txid = Readable::read(reader)?;
6542			let htlcs_count: u64 = Readable::read(reader)?;
6543			let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
6544			for _ in 0..htlcs_count {
6545				htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
6546			}
6547			if counterparty_claimable_outpoints.insert(txid, htlcs).is_some() {
6548				return Err(DecodeError::InvalidValue);
6549			}
6550		}
6551
6552		let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
6553		let mut counterparty_commitment_txn_on_chain = hash_map_with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
6554		for _ in 0..counterparty_commitment_txn_on_chain_len {
6555			let txid: Txid = Readable::read(reader)?;
6556			let commitment_number = <U48 as Readable>::read(reader)?.0;
6557			if counterparty_commitment_txn_on_chain.insert(txid, commitment_number).is_some() {
6558				return Err(DecodeError::InvalidValue);
6559			}
6560		}
6561
6562		let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
6563		let mut counterparty_hash_commitment_number = hash_map_with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
6564		for _ in 0..counterparty_hash_commitment_number_len {
6565			let payment_hash: PaymentHash = Readable::read(reader)?;
6566			let commitment_number = <U48 as Readable>::read(reader)?.0;
6567			if counterparty_hash_commitment_number.insert(payment_hash, commitment_number).is_some() {
6568				return Err(DecodeError::InvalidValue);
6569			}
6570		}
6571
6572		let prev_holder_signed_tx: Option<HolderSignedTx> =
6573			match <u8 as Readable>::read(reader)? {
6574				0 => None,
6575				1 => Some(Readable::read(reader)?),
6576				_ => return Err(DecodeError::InvalidValue),
6577			};
6578		let current_holder_signed_tx: HolderSignedTx = Readable::read(reader)?;
6579
6580		let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
6581		let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
6582
6583		let payment_preimages_len: u64 = Readable::read(reader)?;
6584		let mut payment_preimages = hash_map_with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
6585		for _ in 0..payment_preimages_len {
6586			let preimage: PaymentPreimage = Readable::read(reader)?;
6587			let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
6588			if payment_preimages.insert(hash, (preimage, Vec::new())).is_some() {
6589				return Err(DecodeError::InvalidValue);
6590			}
6591		}
6592
6593		let pending_monitor_events_len: u64 = Readable::read(reader)?;
6594		let mut pending_monitor_events = Some(
6595			Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
6596		for _ in 0..pending_monitor_events_len {
6597			let ev = match <u8 as Readable>::read(reader)? {
6598				0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
6599				1 => MonitorEvent::HolderForceClosed(outpoint),
6600				_ => return Err(DecodeError::InvalidValue)
6601			};
6602			pending_monitor_events.as_mut().unwrap().push(ev);
6603		}
6604
6605		let pending_events_len: u64 = Readable::read(reader)?;
6606		let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
6607		for _ in 0..pending_events_len {
6608			if let Some(event) = MaybeReadable::read(reader)? {
6609				pending_events.push(event);
6610			}
6611		}
6612
6613		let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
6614
6615		let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
6616		let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
6617		for _ in 0..waiting_threshold_conf_len {
6618			if let Some(val) = MaybeReadable::read(reader)? {
6619				onchain_events_awaiting_threshold_conf.push(val);
6620			}
6621		}
6622
6623		let outputs_to_watch_len: u64 = Readable::read(reader)?;
6624		let mut outputs_to_watch = hash_map_with_capacity(cmp::min(outputs_to_watch_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<Txid>() + mem::size_of::<u32>() + mem::size_of::<Vec<ScriptBuf>>())));
6625		for _ in 0..outputs_to_watch_len {
6626			let txid = Readable::read(reader)?;
6627			let outputs_len: u64 = Readable::read(reader)?;
6628			let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<ScriptBuf>())));
6629			for _ in 0..outputs_len {
6630				outputs.push((Readable::read(reader)?, Readable::read(reader)?));
6631			}
6632			if outputs_to_watch.insert(txid, outputs).is_some() {
6633				return Err(DecodeError::InvalidValue);
6634			}
6635		}
6636		let onchain_tx_handler: OnchainTxHandler<SP::EcdsaSigner> = ReadableArgs::read(
6637			reader, (entropy_source, signer_provider, channel_value_satoshis, channel_keys_id)
6638		)?;
6639
6640		let lockdown_from_offchain = Readable::read(reader)?;
6641		let holder_tx_signed = Readable::read(reader)?;
6642
6643		let mut funding_spend_confirmed = None;
6644		let mut htlcs_resolved_on_chain = Some(Vec::new());
6645		let mut htlcs_resolved_to_user = Some(new_hash_set());
6646		let mut funding_spend_seen = Some(false);
6647		let mut counterparty_node_id = None;
6648		let mut confirmed_commitment_tx_counterparty_output = None;
6649		let mut spendable_txids_confirmed = Some(Vec::new());
6650		let mut counterparty_fulfilled_htlcs = Some(new_hash_map());
6651		let mut initial_counterparty_commitment_info = None;
6652		let mut initial_counterparty_commitment_tx = None;
6653		let mut balances_empty_height = None;
6654		let mut channel_id = None;
6655		let mut holder_pays_commitment_tx_fee = None;
6656		let mut payment_preimages_with_info: Option<HashMap<_, _>> = None;
6657		let mut first_negotiated_funding_txo = RequiredWrapper(None);
6658		let mut channel_parameters = None;
6659		let mut pending_funding = None;
6660		let mut alternative_funding_confirmed = None;
6661		let mut is_manual_broadcast = RequiredWrapper(None);
6662		let mut funding_seen_onchain = RequiredWrapper(None);
6663		read_tlv_fields!(reader, {
6664			(1, funding_spend_confirmed, option),
6665			(3, htlcs_resolved_on_chain, optional_vec),
6666			(5, pending_monitor_events, optional_vec),
6667			(7, funding_spend_seen, option),
6668			(9, counterparty_node_id, option),
6669			(11, confirmed_commitment_tx_counterparty_output, option),
6670			(13, spendable_txids_confirmed, optional_vec),
6671			(15, counterparty_fulfilled_htlcs, option),
6672			(17, initial_counterparty_commitment_info, option),
6673			(19, channel_id, option),
6674			(21, balances_empty_height, option),
6675			(23, holder_pays_commitment_tx_fee, option),
6676			(25, payment_preimages_with_info, option),
6677			(27, first_negotiated_funding_txo, (default_value, outpoint)),
6678			(29, initial_counterparty_commitment_tx, option),
6679			(31, channel_parameters, (option: ReadableArgs, None)),
6680			(32, pending_funding, optional_vec),
6681			(33, htlcs_resolved_to_user, option),
6682			(34, alternative_funding_confirmed, option),
6683			(35, is_manual_broadcast, (default_value, false)),
6684			(37, funding_seen_onchain, (default_value, true)),
6685		});
6686		// Note that `payment_preimages_with_info` was added (and is always written) in LDK 0.1, so
6687		// we can use it to determine if this monitor was last written by LDK 0.1 or later.
6688		let written_by_0_1_or_later = payment_preimages_with_info.is_some();
6689		if let Some(payment_preimages_with_info) = payment_preimages_with_info {
6690			if payment_preimages_with_info.len() != payment_preimages.len() {
6691				return Err(DecodeError::InvalidValue);
6692			}
6693			for (payment_hash, (payment_preimage, _)) in payment_preimages.iter() {
6694				// Note that because `payment_preimages` is built back from preimages directly,
6695				// checking that the two maps have the same hash -> preimage pairs also checks that
6696				// the payment hashes in `payment_preimages_with_info`'s preimages match its
6697				// hashes.
6698				let new_preimage = payment_preimages_with_info.get(payment_hash).map(|(p, _)| p);
6699				if new_preimage != Some(payment_preimage) {
6700					return Err(DecodeError::InvalidValue);
6701				}
6702			}
6703			payment_preimages = payment_preimages_with_info;
6704		}
6705
6706		// `HolderForceClosedWithInfo` replaced `HolderForceClosed` in v0.0.122. If we have both
6707		// events, we can remove the `HolderForceClosed` event and just keep the `HolderForceClosedWithInfo`.
6708		if let Some(ref mut pending_monitor_events) = pending_monitor_events {
6709			if pending_monitor_events.iter().any(|e| matches!(e, MonitorEvent::HolderForceClosed(_))) &&
6710				pending_monitor_events.iter().any(|e| matches!(e, MonitorEvent::HolderForceClosedWithInfo { .. }))
6711			{
6712				pending_monitor_events.retain(|e| !matches!(e, MonitorEvent::HolderForceClosed(_)));
6713			}
6714		}
6715
6716		let channel_parameters = channel_parameters.unwrap_or_else(|| {
6717			onchain_tx_handler.channel_parameters().clone()
6718		});
6719
6720		// Monitors for anchor outputs channels opened in v0.0.116 suffered from a bug in which the
6721		// wrong `counterparty_payment_script` was being tracked. Fix it now on deserialization to
6722		// give them a chance to recognize the spendable output.
6723		if channel_parameters.channel_type_features.supports_anchors_zero_fee_htlc_tx() &&
6724			counterparty_payment_script.is_p2wpkh()
6725		{
6726			let payment_point = channel_parameters.holder_pubkeys.payment_point;
6727			counterparty_payment_script =
6728				chan_utils::get_to_countersigner_keyed_anchor_redeemscript(&payment_point).to_p2wsh();
6729		}
6730
6731		let channel_id = channel_id.unwrap_or(ChannelId::v1_from_funding_outpoint(outpoint));
6732
6733		let (current_holder_commitment_tx, current_holder_htlc_data) = {
6734			let holder_commitment_tx = onchain_tx_handler.current_holder_commitment_tx();
6735
6736			#[cfg(debug_assertions)]
6737			let holder_signed_tx_copy = current_holder_signed_tx.clone();
6738
6739			let holder_commitment_htlc_data = CommitmentHTLCData::try_from(current_holder_signed_tx)
6740				.map_err(|_| DecodeError::InvalidValue)?;
6741
6742			#[cfg(debug_assertions)] {
6743				let mut stream = crate::util::ser::VecWriter(Vec::new());
6744				write_legacy_holder_commitment_data(
6745					&mut stream, &holder_commitment_tx, &holder_commitment_htlc_data
6746				).map_err(|_| DecodeError::InvalidValue)?;
6747				let mut cursor = crate::io::Cursor::new(stream.0);
6748				if holder_signed_tx_copy != <HolderSignedTx as Readable>::read(&mut cursor)? {
6749					return Err(DecodeError::InvalidValue);
6750				}
6751			}
6752
6753			(holder_commitment_tx.clone(), holder_commitment_htlc_data)
6754		};
6755
6756		let (prev_holder_commitment_tx, prev_holder_htlc_data) =
6757			if let Some(prev_holder_signed_tx) = prev_holder_signed_tx {
6758				let holder_commitment_tx = onchain_tx_handler.prev_holder_commitment_tx();
6759				if holder_commitment_tx.is_none() {
6760					return Err(DecodeError::InvalidValue);
6761				}
6762
6763				#[cfg(debug_assertions)]
6764				let holder_signed_tx_copy = prev_holder_signed_tx.clone();
6765
6766				let holder_commitment_htlc_data = CommitmentHTLCData::try_from(prev_holder_signed_tx)
6767					.map_err(|_| DecodeError::InvalidValue)?;
6768
6769				#[cfg(debug_assertions)] {
6770					let mut stream = crate::util::ser::VecWriter(Vec::new());
6771					write_legacy_holder_commitment_data(
6772						&mut stream, &holder_commitment_tx.unwrap(), &holder_commitment_htlc_data
6773					).map_err(|_| DecodeError::InvalidValue)?;
6774					let mut cursor = crate::io::Cursor::new(stream.0);
6775					if holder_signed_tx_copy != <HolderSignedTx as Readable>::read(&mut cursor)? {
6776						return Err(DecodeError::InvalidValue);
6777					}
6778				}
6779
6780				(holder_commitment_tx.cloned(), Some(holder_commitment_htlc_data))
6781			} else {
6782				(None, None)
6783			};
6784
6785		let dummy_node_id = PublicKey::from_slice(&[2; 33]).unwrap();
6786		let monitor = ChannelMonitor::from_impl(ChannelMonitorImpl {
6787			funding: FundingScope {
6788				channel_parameters,
6789
6790				current_counterparty_commitment_txid,
6791				prev_counterparty_commitment_txid,
6792				counterparty_claimable_outpoints,
6793
6794				current_holder_commitment_tx,
6795				prev_holder_commitment_tx,
6796			},
6797			pending_funding: pending_funding.unwrap_or(vec![]),
6798			is_manual_broadcast: is_manual_broadcast.0.unwrap(),
6799			// Older monitors prior to LDK 0.2 assume this is `true` when absent
6800			// during upgrade so holder broadcasts aren't gated unexpectedly.
6801			funding_seen_onchain: funding_seen_onchain.0.unwrap(),
6802
6803			latest_update_id,
6804			commitment_transaction_number_obscure_factor,
6805
6806			destination_script,
6807			broadcasted_holder_revokable_script,
6808			counterparty_payment_script,
6809			shutdown_script,
6810
6811			channel_keys_id,
6812			holder_revocation_basepoint,
6813			channel_id,
6814			first_negotiated_funding_txo: first_negotiated_funding_txo.0.unwrap(),
6815
6816			counterparty_commitment_params,
6817			their_cur_per_commitment_points,
6818
6819			on_holder_tx_csv,
6820
6821			commitment_secrets,
6822			counterparty_commitment_txn_on_chain,
6823			counterparty_hash_commitment_number,
6824			counterparty_fulfilled_htlcs: counterparty_fulfilled_htlcs.unwrap(),
6825
6826			current_counterparty_commitment_number,
6827			current_holder_commitment_number,
6828
6829			payment_preimages,
6830			pending_monitor_events: pending_monitor_events.unwrap(),
6831			pending_events,
6832			is_processing_pending_events: false,
6833
6834			onchain_events_awaiting_threshold_conf,
6835			outputs_to_watch,
6836
6837			onchain_tx_handler,
6838
6839			lockdown_from_offchain,
6840			holder_tx_signed,
6841			holder_pays_commitment_tx_fee,
6842			funding_spend_seen: funding_spend_seen.unwrap(),
6843			funding_spend_confirmed,
6844			confirmed_commitment_tx_counterparty_output,
6845			htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
6846			htlcs_resolved_to_user: htlcs_resolved_to_user.unwrap(),
6847			spendable_txids_confirmed: spendable_txids_confirmed.unwrap(),
6848
6849			best_block,
6850			counterparty_node_id: counterparty_node_id.unwrap_or(dummy_node_id),
6851			initial_counterparty_commitment_info,
6852			initial_counterparty_commitment_tx,
6853			balances_empty_height,
6854			failed_back_htlc_ids: new_hash_set(),
6855
6856			current_holder_htlc_data,
6857			prev_holder_htlc_data,
6858
6859			alternative_funding_confirmed,
6860
6861			written_by_0_1_or_later,
6862		});
6863
6864		if counterparty_node_id.is_none() {
6865			if (holder_tx_signed || lockdown_from_offchain) && monitor.get_claimable_balances().is_empty() {
6866				// If the monitor is no longer readable, but it is a candidate for archiving,
6867				// return Ok(None) to allow it to be skipped and not loaded.
6868				return Ok(None);
6869			} else {
6870				panic!("Found monitor for channel {channel_id} with no updates since v0.0.118. \
6871					These monitors are no longer supported. \
6872					To continue, run a v0.1 release, send/route a payment over the channel or close it.");
6873			}
6874		}
6875		Ok(Some((best_block.block_hash, monitor)))
6876	}
6877}
6878
6879#[cfg(test)]
6880mod tests {
6881	use bitcoin::amount::Amount;
6882	use bitcoin::hash_types::{BlockHash, Txid};
6883	use bitcoin::hashes::sha256::Hash as Sha256;
6884	use bitcoin::hashes::Hash;
6885	use bitcoin::hex::FromHex;
6886	use bitcoin::locktime::absolute::LockTime;
6887	use bitcoin::network::Network;
6888	use bitcoin::opcodes;
6889	use bitcoin::script::{Builder, ScriptBuf};
6890	use bitcoin::secp256k1::Secp256k1;
6891	use bitcoin::secp256k1::{PublicKey, SecretKey};
6892	use bitcoin::sighash;
6893	use bitcoin::sighash::EcdsaSighashType;
6894	use bitcoin::transaction::OutPoint as BitcoinOutPoint;
6895	use bitcoin::transaction::{Transaction, TxIn, TxOut, Version};
6896	use bitcoin::{Sequence, Witness};
6897
6898	use crate::chain::chaininterface::LowerBoundedFeeEstimator;
6899	use crate::events::ClosureReason;
6900
6901	use super::ChannelMonitorUpdateStep;
6902	use crate::chain::channelmonitor::{ChannelMonitor, WithChannelMonitor};
6903	use crate::chain::package::{
6904		weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc,
6905		weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT,
6906	};
6907	use crate::chain::transaction::OutPoint;
6908	use crate::chain::{BestBlock, Confirm};
6909	use crate::io;
6910	use crate::ln::chan_utils::{
6911		self, ChannelPublicKeys, ChannelTransactionParameters,
6912		CounterpartyChannelTransactionParameters, HTLCOutputInCommitment,
6913		HolderCommitmentTransaction,
6914	};
6915	use crate::ln::channel_keys::{
6916		DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, RevocationBasepoint,
6917		RevocationKey,
6918	};
6919	use crate::ln::channelmanager::{HTLCSource, PaymentId, RecipientOnionFields};
6920	use crate::ln::functional_test_utils::*;
6921	use crate::ln::script::ShutdownScript;
6922	use crate::ln::types::ChannelId;
6923	use crate::sign::{ChannelSigner, InMemorySigner};
6924	use crate::sync::Arc;
6925	use crate::types::features::ChannelTypeFeatures;
6926	use crate::types::payment::{PaymentHash, PaymentPreimage};
6927	use crate::util::logger::Logger;
6928	use crate::util::ser::{ReadableArgs, Writeable};
6929	use crate::util::test_utils::{TestBroadcaster, TestFeeEstimator, TestLogger};
6930	use crate::{
6931		check_added_monitors, check_spends, get_local_commitment_txn, get_monitor,
6932		get_route_and_payment_hash,
6933	};
6934
6935	#[allow(unused_imports)]
6936	use crate::prelude::*;
6937
6938	use std::str::FromStr;
6939
6940	#[rustfmt::skip]
6941	fn do_test_funding_spend_refuses_updates(use_local_txn: bool) {
6942		// Previously, monitor updates were allowed freely even after a funding-spend transaction
6943		// confirmed. This would allow a race condition where we could receive a payment (including
6944		// the counterparty revoking their broadcasted state!) and accept it without recourse as
6945		// long as the ChannelMonitor receives the block first, the full commitment update dance
6946		// occurs after the block is connected, and before the ChannelManager receives the block.
6947		// Obviously this is an incredibly contrived race given the counterparty would be risking
6948		// their full channel balance for it, but its worth fixing nonetheless as it makes the
6949		// potential ChannelMonitor states simpler to reason about.
6950		//
6951		// This test checks said behavior, as well as ensuring a ChannelMonitorUpdate with multiple
6952		// updates is handled correctly in such conditions.
6953		let chanmon_cfgs = create_chanmon_cfgs(3);
6954		let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6955		let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6956		let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6957		let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
6958		create_announced_chan_between_nodes(&nodes, 1, 2);
6959
6960		// Rebalance somewhat
6961		send_payment(&nodes[0], &[&nodes[1]], 10_000_000);
6962
6963		// First route two payments for testing at the end
6964		let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
6965		let payment_preimage_2 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
6966
6967		let local_txn = get_local_commitment_txn!(nodes[1], channel.2);
6968		assert_eq!(local_txn.len(), 1);
6969		let remote_txn = get_local_commitment_txn!(nodes[0], channel.2);
6970		assert_eq!(remote_txn.len(), 3); // Commitment and two HTLC-Timeouts
6971		check_spends!(remote_txn[1], remote_txn[0]);
6972		check_spends!(remote_txn[2], remote_txn[0]);
6973		let broadcast_tx = if use_local_txn { &local_txn[0] } else { &remote_txn[0] };
6974
6975		// Connect a commitment transaction, but only to the ChainMonitor/ChannelMonitor. The
6976		// channel is now closed, but the ChannelManager doesn't know that yet.
6977		let new_header = create_dummy_header(nodes[0].best_block_info().0, 0);
6978		let conf_height = nodes[0].best_block_info().1 + 1;
6979		nodes[1].chain_monitor.chain_monitor.transactions_confirmed(&new_header,
6980			&[(0, broadcast_tx)], conf_height);
6981
6982		let (_, pre_update_monitor) = <(BlockHash, ChannelMonitor<_>)>::read(
6983						&mut io::Cursor::new(&get_monitor!(nodes[1], channel.2).encode()),
6984						(&nodes[1].keys_manager.backing, &nodes[1].keys_manager.backing)).unwrap();
6985
6986		// If the ChannelManager tries to update the channel, however, the ChainMonitor will pass
6987		// the update through to the ChannelMonitor which will refuse it (as the channel is closed).
6988		let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
6989		nodes[1].node.send_payment_with_route(route, payment_hash,
6990			RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
6991		).unwrap();
6992		check_added_monitors!(nodes[1], 1);
6993
6994		// Build a new ChannelMonitorUpdate which contains both the failing commitment tx update
6995		// and provides the claim preimages for the two pending HTLCs. The first update generates
6996		// an error, but the point of this test is to ensure the later updates are still applied.
6997		let replay_update = {
6998			let monitor_updates = nodes[1].chain_monitor.monitor_updates.lock().unwrap();
6999			let mut replay_update = monitor_updates.get(&channel.2).unwrap().iter().next_back().unwrap().clone();
7000			assert_eq!(replay_update.updates.len(), 1);
7001			if let ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } = replay_update.updates[0] {
7002			} else { panic!(); }
7003			replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage {
7004				payment_preimage: payment_preimage_1, payment_info: None,
7005			});
7006			replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage {
7007				payment_preimage: payment_preimage_2, payment_info: None,
7008			});
7009			replay_update
7010		};
7011
7012		let broadcaster = TestBroadcaster::with_blocks(Arc::clone(&nodes[1].blocks));
7013		assert!(
7014			pre_update_monitor.update_monitor(&replay_update, &&broadcaster, &&chanmon_cfgs[1].fee_estimator, &nodes[1].logger)
7015			.is_err());
7016
7017		// Even though we error'd on the first update, we should still have generated an HTLC claim
7018		// transaction
7019		let txn_broadcasted = broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7020		assert!(txn_broadcasted.len() >= 2);
7021		let htlc_txn = txn_broadcasted.iter().filter(|tx| {
7022			assert_eq!(tx.input.len(), 1);
7023			tx.input[0].previous_output.txid == broadcast_tx.compute_txid()
7024		}).collect::<Vec<_>>();
7025		assert_eq!(htlc_txn.len(), 2);
7026		check_spends!(htlc_txn[0], broadcast_tx);
7027		check_spends!(htlc_txn[1], broadcast_tx);
7028
7029		check_closed_broadcast(&nodes[1], 1, true);
7030		check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false, &[nodes[0].node.get_our_node_id()], 100000);
7031		check_added_monitors(&nodes[1], 1);
7032	}
7033
7034	#[test]
7035	fn test_funding_spend_refuses_updates() {
7036		do_test_funding_spend_refuses_updates(true);
7037		do_test_funding_spend_refuses_updates(false);
7038	}
7039
7040	#[test]
7041	#[rustfmt::skip]
7042	fn test_prune_preimages() {
7043		let secp_ctx = Secp256k1::new();
7044		let logger = Arc::new(TestLogger::new());
7045		let broadcaster = Arc::new(TestBroadcaster::new(Network::Testnet));
7046		let fee_estimator = TestFeeEstimator::new(253);
7047
7048		let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
7049
7050		let mut preimages = Vec::new();
7051		{
7052			for i in 0..20 {
7053				let preimage = PaymentPreimage([i; 32]);
7054				let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
7055				preimages.push((preimage, hash));
7056			}
7057		}
7058
7059		let dummy_source = HTLCSource::dummy();
7060
7061		macro_rules! preimages_slice_to_htlcs {
7062			($preimages_slice: expr) => {
7063				{
7064					let mut res = Vec::new();
7065					for (idx, preimage) in $preimages_slice.iter().enumerate() {
7066						res.push(HTLCOutputInCommitment {
7067							offered: true,
7068							amount_msat: 0,
7069							cltv_expiry: 0,
7070							payment_hash: preimage.1.clone(),
7071							transaction_output_index: Some(idx as u32),
7072						});
7073					}
7074					res
7075				}
7076			}
7077		}
7078		macro_rules! preimages_slice_to_htlc_outputs {
7079			($preimages_slice: expr) => {
7080				preimages_slice_to_htlcs!($preimages_slice).into_iter().map(|htlc| (htlc, None)).collect()
7081			}
7082		}
7083		let dummy_sig = crate::crypto::utils::sign(&secp_ctx,
7084			&bitcoin::secp256k1::Message::from_digest([42; 32]),
7085			&SecretKey::from_slice(&[42; 32]).unwrap());
7086
7087		macro_rules! test_preimages_exist {
7088			($preimages_slice: expr, $monitor: expr) => {
7089				for preimage in $preimages_slice {
7090					assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
7091				}
7092			}
7093		}
7094
7095		let keys = InMemorySigner::new(
7096			SecretKey::from_slice(&[41; 32]).unwrap(),
7097			SecretKey::from_slice(&[41; 32]).unwrap(),
7098			SecretKey::from_slice(&[41; 32]).unwrap(),
7099			SecretKey::from_slice(&[41; 32]).unwrap(),
7100			true,
7101			SecretKey::from_slice(&[41; 32]).unwrap(),
7102			SecretKey::from_slice(&[41; 32]).unwrap(),
7103			[41; 32],
7104			[0; 32],
7105			[0; 32],
7106		);
7107
7108		let counterparty_pubkeys = ChannelPublicKeys {
7109			funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
7110			revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())),
7111			payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
7112			delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
7113			htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap()))
7114		};
7115		let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::MAX };
7116		let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
7117		let channel_parameters = ChannelTransactionParameters {
7118			holder_pubkeys: keys.pubkeys(&secp_ctx),
7119			holder_selected_contest_delay: 66,
7120			is_outbound_from_holder: true,
7121			counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
7122				pubkeys: counterparty_pubkeys,
7123				selected_contest_delay: 67,
7124			}),
7125			funding_outpoint: Some(funding_outpoint),
7126			splice_parent_funding_txid: None,
7127			channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
7128			channel_value_satoshis: 0,
7129		};
7130		// Prune with one old state and a holder commitment tx holding a few overlaps with the
7131		// old state.
7132		let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
7133		let shutdown_script = ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey);
7134		let best_block = BestBlock::from_network(Network::Testnet);
7135		let monitor = ChannelMonitor::new(
7136			Secp256k1::new(), keys, Some(shutdown_script.into_inner()), 0, &ScriptBuf::new(),
7137			&channel_parameters, true, 0, HolderCommitmentTransaction::dummy(0, funding_outpoint, Vec::new()),
7138			best_block, dummy_key, channel_id, false,
7139		);
7140
7141		let nondust_htlcs = preimages_slice_to_htlcs!(preimages[0..10]);
7142		let dummy_commitment_tx = HolderCommitmentTransaction::dummy(0, funding_outpoint, nondust_htlcs);
7143		// These HTLCs now have their output indices assigned
7144		let nondust_htlcs = dummy_commitment_tx.nondust_htlcs();
7145
7146		monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
7147			&nondust_htlcs.iter().map(|htlc| (htlc.clone(), Some(dummy_sig), Some(dummy_source.clone()))).collect::<Vec<_>>());
7148		monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"1").to_byte_array()),
7149			preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
7150		monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"2").to_byte_array()),
7151			preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
7152		for &(ref preimage, ref hash) in preimages.iter() {
7153			let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&fee_estimator);
7154			monitor.provide_payment_preimage_unsafe_legacy(
7155				hash, preimage, &broadcaster, &bounded_fee_estimator, &logger
7156			);
7157		}
7158
7159		// Now provide a secret, pruning preimages 10-15
7160		let mut secret = [0; 32];
7161		secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
7162		monitor.provide_secret(281474976710655, secret.clone()).unwrap();
7163		assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
7164		test_preimages_exist!(&preimages[0..10], monitor);
7165		test_preimages_exist!(&preimages[15..20], monitor);
7166
7167		monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"3").to_byte_array()),
7168			preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
7169
7170		// Now provide a further secret, pruning preimages 15-17
7171		secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
7172		monitor.provide_secret(281474976710654, secret.clone()).unwrap();
7173		assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
7174		test_preimages_exist!(&preimages[0..10], monitor);
7175		test_preimages_exist!(&preimages[17..20], monitor);
7176
7177		monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"4").to_byte_array()),
7178			preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key);
7179
7180		// Now update holder commitment tx info, pruning only element 18 as we still care about the
7181		// previous commitment tx's preimages too
7182		let nondust_htlcs = preimages_slice_to_htlcs!(preimages[0..5]);
7183		let dummy_commitment_tx = HolderCommitmentTransaction::dummy(0, funding_outpoint, nondust_htlcs);
7184		// These HTLCs now have their output indices assigned
7185		let nondust_htlcs = dummy_commitment_tx.nondust_htlcs();
7186		monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
7187			&nondust_htlcs.iter().map(|htlc| (htlc.clone(), Some(dummy_sig), Some(dummy_source.clone()))).collect::<Vec<_>>());
7188		secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
7189		monitor.provide_secret(281474976710653, secret.clone()).unwrap();
7190		assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
7191		test_preimages_exist!(&preimages[0..10], monitor);
7192		test_preimages_exist!(&preimages[18..20], monitor);
7193
7194		// But if we do it again, we'll prune 5-10
7195		let nondust_htlcs = preimages_slice_to_htlcs!(preimages[0..3]);
7196		let dummy_commitment_tx = HolderCommitmentTransaction::dummy(0, funding_outpoint, nondust_htlcs);
7197		// These HTLCs now have their output indices assigned
7198		let nondust_htlcs = dummy_commitment_tx.nondust_htlcs();
7199		monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
7200			&nondust_htlcs.iter().map(|htlc| (htlc.clone(), Some(dummy_sig), Some(dummy_source.clone()))).collect::<Vec<_>>());
7201		secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
7202		monitor.provide_secret(281474976710652, secret.clone()).unwrap();
7203		assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
7204		test_preimages_exist!(&preimages[0..5], monitor);
7205	}
7206
7207	#[test]
7208	#[rustfmt::skip]
7209	fn test_claim_txn_weight_computation() {
7210		// We test Claim txn weight, knowing that we want expected weigth and
7211		// not actual case to avoid sigs and time-lock delays hell variances.
7212
7213		let secp_ctx = Secp256k1::new();
7214		let privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
7215		let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
7216
7217		use crate::ln::channel_keys::{HtlcKey, HtlcBasepoint};
7218		macro_rules! sign_input {
7219			($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => {
7220				let htlc = HTLCOutputInCommitment {
7221					offered: if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_offered_htlc($opt_anchors) { true } else { false },
7222					amount_msat: 0,
7223					cltv_expiry: 2 << 16,
7224					payment_hash: PaymentHash([1; 32]),
7225					transaction_output_index: Some($idx as u32),
7226				};
7227				let redeem_script = if *$weight == WEIGHT_REVOKED_OUTPUT { chan_utils::get_revokeable_redeemscript(&RevocationKey::from_basepoint(&secp_ctx, &RevocationBasepoint::from(pubkey), &pubkey), 256, &DelayedPaymentKey::from_basepoint(&secp_ctx, &DelayedPaymentBasepoint::from(pubkey), &pubkey)) } else { chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, $opt_anchors, &HtlcKey::from_basepoint(&secp_ctx, &HtlcBasepoint::from(pubkey), &pubkey), &HtlcKey::from_basepoint(&secp_ctx, &HtlcBasepoint::from(pubkey), &pubkey), &RevocationKey::from_basepoint(&secp_ctx, &RevocationBasepoint::from(pubkey), &pubkey)) };
7228				let sighash = hash_to_message!(&$sighash_parts.p2wsh_signature_hash($idx, &redeem_script, $amount, EcdsaSighashType::All).unwrap()[..]);
7229				let sig = secp_ctx.sign_ecdsa(&sighash, &privkey);
7230				let mut ser_sig = sig.serialize_der().to_vec();
7231				ser_sig.push(EcdsaSighashType::All as u8);
7232				$sum_actual_sigs += ser_sig.len() as u64;
7233				let witness = $sighash_parts.witness_mut($idx).unwrap();
7234				witness.push(ser_sig);
7235				if *$weight == WEIGHT_REVOKED_OUTPUT {
7236					witness.push(vec!(1));
7237				} else if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_revoked_received_htlc($opt_anchors) {
7238					witness.push(pubkey.clone().serialize().to_vec());
7239				} else if *$weight == weight_received_htlc($opt_anchors) {
7240					witness.push(vec![0]);
7241				} else {
7242					witness.push(PaymentPreimage([1; 32]).0.to_vec());
7243				}
7244				witness.push(redeem_script.into_bytes());
7245				let witness = witness.to_vec();
7246				println!("witness[0] {}", witness[0].len());
7247				println!("witness[1] {}", witness[1].len());
7248				println!("witness[2] {}", witness[2].len());
7249			}
7250		}
7251
7252		let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
7253		let txid = Txid::from_str("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
7254
7255		// Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
7256		for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
7257			let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
7258			let mut sum_actual_sigs = 0;
7259			for i in 0..4 {
7260				claim_tx.input.push(TxIn {
7261					previous_output: BitcoinOutPoint {
7262						txid,
7263						vout: i,
7264					},
7265					script_sig: ScriptBuf::new(),
7266					sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
7267					witness: Witness::new(),
7268				});
7269			}
7270			claim_tx.output.push(TxOut {
7271				script_pubkey: script_pubkey.clone(),
7272				value: Amount::ZERO,
7273			});
7274			let base_weight = claim_tx.weight().to_wu();
7275			let inputs_weight = [WEIGHT_REVOKED_OUTPUT, weight_revoked_offered_htlc(channel_type_features), weight_revoked_offered_htlc(channel_type_features), weight_revoked_received_htlc(channel_type_features)];
7276			let mut inputs_total_weight = 2; // count segwit flags
7277			{
7278				let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
7279				for (idx, inp) in inputs_weight.iter().enumerate() {
7280					sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
7281					inputs_total_weight += inp;
7282				}
7283			}
7284			assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + /* max_length_sig */ (73 * inputs_weight.len() as u64 - sum_actual_sigs));
7285		}
7286
7287		// Claim tx with 1 offered HTLCs, 3 received HTLCs
7288		for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
7289			let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
7290			let mut sum_actual_sigs = 0;
7291			for i in 0..4 {
7292				claim_tx.input.push(TxIn {
7293					previous_output: BitcoinOutPoint {
7294						txid,
7295						vout: i,
7296					},
7297					script_sig: ScriptBuf::new(),
7298					sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
7299					witness: Witness::new(),
7300				});
7301			}
7302			claim_tx.output.push(TxOut {
7303				script_pubkey: script_pubkey.clone(),
7304				value: Amount::ZERO,
7305			});
7306			let base_weight = claim_tx.weight().to_wu();
7307			let inputs_weight = [weight_offered_htlc(channel_type_features), weight_received_htlc(channel_type_features), weight_received_htlc(channel_type_features), weight_received_htlc(channel_type_features)];
7308			let mut inputs_total_weight = 2; // count segwit flags
7309			{
7310				let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
7311				for (idx, inp) in inputs_weight.iter().enumerate() {
7312					sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
7313					inputs_total_weight += inp;
7314				}
7315			}
7316			assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + /* max_length_sig */ (73 * inputs_weight.len() as u64 - sum_actual_sigs));
7317		}
7318
7319		// Justice tx with 1 revoked HTLC-Success tx output
7320		for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
7321			let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
7322			let mut sum_actual_sigs = 0;
7323			claim_tx.input.push(TxIn {
7324				previous_output: BitcoinOutPoint {
7325					txid,
7326					vout: 0,
7327				},
7328				script_sig: ScriptBuf::new(),
7329				sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
7330				witness: Witness::new(),
7331			});
7332			claim_tx.output.push(TxOut {
7333				script_pubkey: script_pubkey.clone(),
7334				value: Amount::ZERO,
7335			});
7336			let base_weight = claim_tx.weight().to_wu();
7337			let inputs_weight = [WEIGHT_REVOKED_OUTPUT];
7338			let mut inputs_total_weight = 2; // count segwit flags
7339			{
7340				let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
7341				for (idx, inp) in inputs_weight.iter().enumerate() {
7342					sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
7343					inputs_total_weight += inp;
7344				}
7345			}
7346			assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + /* max_length_isg */ (73 * inputs_weight.len() as u64 - sum_actual_sigs));
7347		}
7348	}
7349
7350	#[test]
7351	#[rustfmt::skip]
7352	fn test_with_channel_monitor_impl_logger() {
7353		let secp_ctx = Secp256k1::new();
7354		let logger = Arc::new(TestLogger::new());
7355
7356		let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
7357
7358		let keys = InMemorySigner::new(
7359			SecretKey::from_slice(&[41; 32]).unwrap(),
7360			SecretKey::from_slice(&[41; 32]).unwrap(),
7361			SecretKey::from_slice(&[41; 32]).unwrap(),
7362			SecretKey::from_slice(&[41; 32]).unwrap(),
7363			true,
7364			SecretKey::from_slice(&[41; 32]).unwrap(),
7365			SecretKey::from_slice(&[41; 32]).unwrap(),
7366			[41; 32],
7367			[0; 32],
7368			[0; 32],
7369		);
7370
7371		let counterparty_pubkeys = ChannelPublicKeys {
7372			funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
7373			revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())),
7374			payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
7375			delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
7376			htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())),
7377		};
7378		let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::MAX };
7379		let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
7380		let channel_parameters = ChannelTransactionParameters {
7381			holder_pubkeys: keys.pubkeys(&secp_ctx),
7382			holder_selected_contest_delay: 66,
7383			is_outbound_from_holder: true,
7384			counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
7385				pubkeys: counterparty_pubkeys,
7386				selected_contest_delay: 67,
7387			}),
7388			funding_outpoint: Some(funding_outpoint),
7389			splice_parent_funding_txid: None,
7390			channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
7391			channel_value_satoshis: 0,
7392		};
7393		let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
7394		let shutdown_script = ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey);
7395		let best_block = BestBlock::from_network(Network::Testnet);
7396		let monitor = ChannelMonitor::new(
7397			Secp256k1::new(), keys, Some(shutdown_script.into_inner()), 0, &ScriptBuf::new(),
7398			&channel_parameters, true, 0, HolderCommitmentTransaction::dummy(0, funding_outpoint, Vec::new()),
7399			best_block, dummy_key, channel_id, false,
7400		);
7401
7402		let chan_id = monitor.inner.lock().unwrap().channel_id();
7403		let payment_hash = PaymentHash([1; 32]);
7404		let context_logger = WithChannelMonitor::from(&logger, &monitor, Some(payment_hash));
7405		log_error!(context_logger, "This is an error");
7406		log_warn!(context_logger, "This is an error");
7407		log_debug!(context_logger, "This is an error");
7408		log_trace!(context_logger, "This is an error");
7409		log_gossip!(context_logger, "This is an error");
7410		log_info!(context_logger, "This is an error");
7411		logger.assert_log_context_contains("lightning::chain::channelmonitor::tests", Some(dummy_key), Some(chan_id), 6);
7412	}
7413	// Further testing is done in the ChannelManager integration tests.
7414}