Skip to main content

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