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