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