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_info = self.funding_spend_confirmed
3012			.map(|txid| (txid, None))
3013			.or_else(|| {
3014				self.onchain_events_awaiting_threshold_conf.iter().find_map(|event| match event.event {
3015					OnchainEvent::FundingSpendConfirmation { .. } => Some((event.txid, Some(event.height))),
3016					_ => None,
3017				})
3018			});
3019		let (confirmed_spend_txid, confirmed_spend_height) =
3020			if let Some((txid, height)) = confirmed_spend_info {
3021				(txid, height)
3022			} else {
3023				return;
3024			};
3025
3026		// If the channel is force closed, try to claim the output from this preimage.
3027		// First check if a counterparty commitment transaction has been broadcasted:
3028		macro_rules! claim_htlcs {
3029			($commitment_number: expr, $txid: expr, $htlcs: expr) => {
3030				let (htlc_claim_reqs, _) = self.get_counterparty_output_claim_info($commitment_number, $txid, None, $htlcs, confirmed_spend_height);
3031				let conf_target = self.closure_conf_target();
3032				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);
3033			}
3034		}
3035		if let Some(txid) = self.current_counterparty_commitment_txid {
3036			if txid == confirmed_spend_txid {
3037				if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
3038					claim_htlcs!(*commitment_number, txid, self.counterparty_claimable_outpoints.get(&txid));
3039				} else {
3040					debug_assert!(false);
3041					log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
3042				}
3043				return;
3044			}
3045		}
3046		if let Some(txid) = self.prev_counterparty_commitment_txid {
3047			if txid == confirmed_spend_txid {
3048				if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
3049					claim_htlcs!(*commitment_number, txid, self.counterparty_claimable_outpoints.get(&txid));
3050				} else {
3051					debug_assert!(false);
3052					log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
3053				}
3054				return;
3055			}
3056		}
3057
3058		// Then if a holder commitment transaction has been seen on-chain, broadcast transactions
3059		// claiming the HTLC output from each of the holder commitment transactions.
3060		// Note that we can't just use `self.holder_tx_signed`, because that only covers the case where
3061		// *we* sign a holder commitment transaction, not when e.g. a watchtower broadcasts one of our
3062		// holder commitment transactions.
3063		if self.broadcasted_holder_revokable_script.is_some() {
3064			let holder_commitment_tx = if self.current_holder_commitment_tx.txid == confirmed_spend_txid {
3065				Some(&self.current_holder_commitment_tx)
3066			} else if let Some(prev_holder_commitment_tx) = &self.prev_holder_signed_commitment_tx {
3067				if prev_holder_commitment_tx.txid == confirmed_spend_txid {
3068					Some(prev_holder_commitment_tx)
3069				} else {
3070					None
3071				}
3072			} else {
3073				None
3074			};
3075			if let Some(holder_commitment_tx) = holder_commitment_tx {
3076				// Assume that the broadcasted commitment transaction confirmed in the current best
3077				// block. Even if not, its a reasonable metric for the bump criteria on the HTLC
3078				// transactions.
3079				let (claim_reqs, _) = self.get_broadcasted_holder_claims(&holder_commitment_tx, self.best_block.height);
3080				let conf_target = self.closure_conf_target();
3081				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);
3082			}
3083		}
3084	}
3085
3086	fn generate_claimable_outpoints_and_watch_outputs(&mut self, reason: ClosureReason) -> (Vec<PackageTemplate>, Vec<TransactionOutputs>) {
3087		let funding_outp = HolderFundingOutput::build(
3088			self.funding_redeemscript.clone(),
3089			self.channel_value_satoshis,
3090			self.onchain_tx_handler.channel_type_features().clone()
3091		);
3092		let commitment_package = PackageTemplate::build_package(
3093			self.funding_info.0.txid.clone(), self.funding_info.0.index as u32,
3094			PackageSolvingData::HolderFundingOutput(funding_outp),
3095			self.best_block.height,
3096		);
3097		let mut claimable_outpoints = vec![commitment_package];
3098		let event = MonitorEvent::HolderForceClosedWithInfo {
3099			reason,
3100			outpoint: self.funding_info.0,
3101			channel_id: self.channel_id,
3102		};
3103		self.pending_monitor_events.push(event);
3104
3105		// Although we aren't signing the transaction directly here, the transaction will be signed
3106		// in the claim that is queued to OnchainTxHandler. We set holder_tx_signed here to reject
3107		// new channel updates.
3108		self.holder_tx_signed = true;
3109		let mut watch_outputs = Vec::new();
3110		// We can't broadcast our HTLC transactions while the commitment transaction is
3111		// unconfirmed. We'll delay doing so until we detect the confirmed commitment in
3112		// `transactions_confirmed`.
3113		if !self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
3114			// Because we're broadcasting a commitment transaction, we should construct the package
3115			// assuming it gets confirmed in the next block. Sadly, we have code which considers
3116			// "not yet confirmed" things as discardable, so we cannot do that here.
3117			let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(
3118				&self.current_holder_commitment_tx, self.best_block.height,
3119			);
3120			let unsigned_commitment_tx = self.onchain_tx_handler.get_unsigned_holder_commitment_tx();
3121			let new_outputs = self.get_broadcasted_holder_watch_outputs(
3122				&self.current_holder_commitment_tx, &unsigned_commitment_tx
3123			);
3124			if !new_outputs.is_empty() {
3125				watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
3126			}
3127			claimable_outpoints.append(&mut new_outpoints);
3128		}
3129		(claimable_outpoints, watch_outputs)
3130	}
3131
3132	pub(crate) fn queue_latest_holder_commitment_txn_for_broadcast<B: Deref, F: Deref, L: Deref>(
3133		&mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &WithChannelMonitor<L>
3134	)
3135	where
3136		B::Target: BroadcasterInterface,
3137		F::Target: FeeEstimator,
3138		L::Target: Logger,
3139	{
3140		let (claimable_outpoints, _) = self.generate_claimable_outpoints_and_watch_outputs(ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) });
3141		let conf_target = self.closure_conf_target();
3142		self.onchain_tx_handler.update_claims_view_from_requests(
3143			claimable_outpoints, self.best_block.height, self.best_block.height, broadcaster,
3144			conf_target, fee_estimator, logger,
3145		);
3146	}
3147
3148	fn update_monitor<B: Deref, F: Deref, L: Deref>(
3149		&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor<L>
3150	) -> Result<(), ()>
3151	where B::Target: BroadcasterInterface,
3152		F::Target: FeeEstimator,
3153		L::Target: Logger,
3154	{
3155		if self.latest_update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID && updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID {
3156			log_info!(logger, "Applying pre-0.1 post-force-closed update to monitor {} with {} change(s).",
3157				log_funding_info!(self), updates.updates.len());
3158		} else if updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID {
3159			log_info!(logger, "Applying pre-0.1 force close update to monitor {} with {} change(s).",
3160				log_funding_info!(self), updates.updates.len());
3161		} else {
3162			log_info!(logger, "Applying update to monitor {}, bringing update_id from {} to {} with {} change(s).",
3163				log_funding_info!(self), self.latest_update_id, updates.update_id, updates.updates.len());
3164		}
3165
3166		if updates.counterparty_node_id.is_some() {
3167			if self.counterparty_node_id.is_none() {
3168				self.counterparty_node_id = updates.counterparty_node_id;
3169			} else {
3170				debug_assert_eq!(self.counterparty_node_id, updates.counterparty_node_id);
3171			}
3172		}
3173
3174		// ChannelMonitor updates may be applied after force close if we receive a preimage for a
3175		// broadcasted commitment transaction HTLC output that we'd like to claim on-chain. If this
3176		// is the case, we no longer have guaranteed access to the monitor's update ID, so we use a
3177		// sentinel value instead.
3178		//
3179		// The `ChannelManager` may also queue redundant `ChannelForceClosed` updates if it still
3180		// thinks the channel needs to have its commitment transaction broadcast, so we'll allow
3181		// them as well.
3182		if updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID || self.lockdown_from_offchain {
3183			assert_eq!(updates.updates.len(), 1);
3184			match updates.updates[0] {
3185				ChannelMonitorUpdateStep::ChannelForceClosed { .. } => {},
3186				// We should have already seen a `ChannelForceClosed` update if we're trying to
3187				// provide a preimage at this point.
3188				ChannelMonitorUpdateStep::PaymentPreimage { .. } =>
3189					debug_assert!(self.lockdown_from_offchain),
3190				_ => {
3191					log_error!(logger, "Attempted to apply post-force-close ChannelMonitorUpdate of type {}", updates.updates[0].variant_name());
3192					panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage");
3193				},
3194			}
3195		}
3196		if updates.update_id != LEGACY_CLOSED_CHANNEL_UPDATE_ID {
3197			if self.latest_update_id + 1 != updates.update_id {
3198				panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
3199			}
3200		}
3201		let mut ret = Ok(());
3202		let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&**fee_estimator);
3203		for update in updates.updates.iter() {
3204			match update {
3205				ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs, claimed_htlcs, nondust_htlc_sources } => {
3206					log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
3207					if self.lockdown_from_offchain { panic!(); }
3208					self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone(), &claimed_htlcs, nondust_htlc_sources.clone());
3209				}
3210				ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_per_commitment_point, .. } => {
3211					log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
3212					self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_per_commitment_point, logger)
3213				},
3214				ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage, payment_info } => {
3215					log_trace!(logger, "Updating ChannelMonitor with payment preimage");
3216					self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()), &payment_preimage, payment_info, broadcaster, &bounded_fee_estimator, logger)
3217				},
3218				ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
3219					log_trace!(logger, "Updating ChannelMonitor with commitment secret");
3220					if let Err(e) = self.provide_secret(*idx, *secret) {
3221						debug_assert!(false, "Latest counterparty commitment secret was invalid");
3222						log_error!(logger, "Providing latest counterparty commitment secret failed/was refused:");
3223						log_error!(logger, "    {}", e);
3224						ret = Err(());
3225					}
3226				},
3227				ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
3228					log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
3229					self.lockdown_from_offchain = true;
3230					if *should_broadcast {
3231						// There's no need to broadcast our commitment transaction if we've seen one
3232						// confirmed (even with 1 confirmation) as it'll be rejected as
3233						// duplicate/conflicting.
3234						let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
3235							self.onchain_events_awaiting_threshold_conf.iter().any(
3236								|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
3237						if detected_funding_spend {
3238							log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
3239							continue;
3240						}
3241						self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &bounded_fee_estimator, logger);
3242					} else if !self.holder_tx_signed {
3243						log_error!(logger, "WARNING: You have a potentially-unsafe holder commitment transaction available to broadcast");
3244						log_error!(logger, "    in channel monitor for channel {}!", &self.channel_id());
3245						log_error!(logger, "    Read the docs for ChannelMonitor::broadcast_latest_holder_commitment_txn to take manual action!");
3246					} else {
3247						// If we generated a MonitorEvent::HolderForceClosed, the ChannelManager
3248						// will still give us a ChannelForceClosed event with !should_broadcast, but we
3249						// shouldn't print the scary warning above.
3250						log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
3251					}
3252				},
3253				ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
3254					log_trace!(logger, "Updating ChannelMonitor with shutdown script");
3255					if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
3256						panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
3257					}
3258				},
3259			}
3260		}
3261
3262		#[cfg(debug_assertions)] {
3263			self.counterparty_commitment_txs_from_update(updates);
3264		}
3265
3266		self.latest_update_id = updates.update_id;
3267
3268		// Refuse updates after we've detected a spend onchain (or if the channel was otherwise
3269		// closed), but only if the update isn't the kind of update we expect to see after channel
3270		// closure.
3271		let mut is_pre_close_update = false;
3272		for update in updates.updates.iter() {
3273			match update {
3274				ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. }
3275					|ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. }
3276					|ChannelMonitorUpdateStep::ShutdownScript { .. }
3277					|ChannelMonitorUpdateStep::CommitmentSecret { .. } =>
3278						is_pre_close_update = true,
3279				// After a channel is closed, we don't communicate with our peer about it, so the
3280				// only things we will update is getting a new preimage (from a different channel)
3281				// or being told that the channel is closed. All other updates are generated while
3282				// talking to our peer.
3283				ChannelMonitorUpdateStep::PaymentPreimage { .. } => {},
3284				ChannelMonitorUpdateStep::ChannelForceClosed { .. } => {},
3285			}
3286		}
3287
3288		if ret.is_ok() && self.no_further_updates_allowed() && is_pre_close_update {
3289			log_error!(logger, "Refusing Channel Monitor Update as counterparty attempted to update commitment after funding was spent");
3290			Err(())
3291		} else { ret }
3292	}
3293
3294	fn no_further_updates_allowed(&self) -> bool {
3295		self.funding_spend_seen || self.lockdown_from_offchain || self.holder_tx_signed
3296	}
3297
3298	fn get_latest_update_id(&self) -> u64 {
3299		self.latest_update_id
3300	}
3301
3302	fn get_funding_txo(&self) -> &(OutPoint, ScriptBuf) {
3303		&self.funding_info
3304	}
3305
3306	pub fn channel_id(&self) -> ChannelId {
3307		self.channel_id
3308	}
3309
3310	fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, ScriptBuf)>> {
3311		// If we've detected a counterparty commitment tx on chain, we must include it in the set
3312		// of outputs to watch for spends of, otherwise we're likely to lose user funds. Because
3313		// its trivial to do, double-check that here.
3314		for txid in self.counterparty_commitment_txn_on_chain.keys() {
3315			self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
3316		}
3317		&self.outputs_to_watch
3318	}
3319
3320	fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
3321		let mut ret = Vec::new();
3322		mem::swap(&mut ret, &mut self.pending_monitor_events);
3323		ret
3324	}
3325
3326	/// Gets the set of events that are repeated regularly (e.g. those which RBF bump
3327	/// transactions). We're okay if we lose these on restart as they'll be regenerated for us at
3328	/// some regular interval via [`ChannelMonitor::rebroadcast_pending_claims`].
3329	pub(super) fn get_repeated_events(&mut self) -> Vec<Event> {
3330		let pending_claim_events = self.onchain_tx_handler.get_and_clear_pending_claim_events();
3331		let mut ret = Vec::with_capacity(pending_claim_events.len());
3332		for (claim_id, claim_event) in pending_claim_events {
3333			match claim_event {
3334				ClaimEvent::BumpCommitment {
3335					package_target_feerate_sat_per_1000_weight, commitment_tx, anchor_output_idx,
3336				} => {
3337					let channel_id = self.channel_id;
3338					// unwrap safety: `ClaimEvent`s are only available for Anchor channels,
3339					// introduced with v0.0.116. counterparty_node_id is guaranteed to be `Some`
3340					// since v0.0.110.
3341					let counterparty_node_id = self.counterparty_node_id.unwrap();
3342					let commitment_txid = commitment_tx.compute_txid();
3343					debug_assert_eq!(self.current_holder_commitment_tx.txid, commitment_txid);
3344					let pending_htlcs = self.current_holder_commitment_tx.non_dust_htlcs();
3345					let commitment_tx_fee_satoshis = self.channel_value_satoshis -
3346						commitment_tx.output.iter().fold(0u64, |sum, output| sum + output.value.to_sat());
3347					ret.push(Event::BumpTransaction(BumpTransactionEvent::ChannelClose {
3348						channel_id,
3349						counterparty_node_id,
3350						claim_id,
3351						package_target_feerate_sat_per_1000_weight,
3352						commitment_tx,
3353						commitment_tx_fee_satoshis,
3354						anchor_descriptor: AnchorDescriptor {
3355							channel_derivation_parameters: ChannelDerivationParameters {
3356								keys_id: self.channel_keys_id,
3357								value_satoshis: self.channel_value_satoshis,
3358								transaction_parameters: self.onchain_tx_handler.channel_transaction_parameters.clone(),
3359							},
3360							outpoint: BitcoinOutPoint {
3361								txid: commitment_txid,
3362								vout: anchor_output_idx,
3363							},
3364						},
3365						pending_htlcs,
3366					}));
3367				},
3368				ClaimEvent::BumpHTLC {
3369					target_feerate_sat_per_1000_weight, htlcs, tx_lock_time,
3370				} => {
3371					let channel_id = self.channel_id;
3372					// unwrap safety: `ClaimEvent`s are only available for Anchor channels,
3373					// introduced with v0.0.116. counterparty_node_id is guaranteed to be `Some`
3374					// since v0.0.110.
3375					let counterparty_node_id = self.counterparty_node_id.unwrap();
3376					let mut htlc_descriptors = Vec::with_capacity(htlcs.len());
3377					for htlc in htlcs {
3378						htlc_descriptors.push(HTLCDescriptor {
3379							channel_derivation_parameters: ChannelDerivationParameters {
3380								keys_id: self.channel_keys_id,
3381								value_satoshis: self.channel_value_satoshis,
3382								transaction_parameters: self.onchain_tx_handler.channel_transaction_parameters.clone(),
3383							},
3384							commitment_txid: htlc.commitment_txid,
3385							per_commitment_number: htlc.per_commitment_number,
3386							per_commitment_point: htlc.per_commitment_point,
3387							feerate_per_kw: 0,
3388							htlc: htlc.htlc,
3389							preimage: htlc.preimage,
3390							counterparty_sig: htlc.counterparty_sig,
3391						});
3392					}
3393					ret.push(Event::BumpTransaction(BumpTransactionEvent::HTLCResolution {
3394						channel_id,
3395						counterparty_node_id,
3396						claim_id,
3397						target_feerate_sat_per_1000_weight,
3398						htlc_descriptors,
3399						tx_lock_time,
3400					}));
3401				}
3402			}
3403		}
3404		ret
3405	}
3406
3407	fn initial_counterparty_commitment_tx(&mut self) -> Option<CommitmentTransaction> {
3408		let (their_per_commitment_point, feerate_per_kw, to_broadcaster_value,
3409			to_countersignatory_value) = self.initial_counterparty_commitment_info?;
3410		let htlc_outputs = vec![];
3411
3412		let commitment_tx = self.build_counterparty_commitment_tx(INITIAL_COMMITMENT_NUMBER,
3413			&their_per_commitment_point, to_broadcaster_value, to_countersignatory_value,
3414			feerate_per_kw, htlc_outputs);
3415		Some(commitment_tx)
3416	}
3417
3418	fn build_counterparty_commitment_tx(
3419		&self, commitment_number: u64, their_per_commitment_point: &PublicKey,
3420		to_broadcaster_value: u64, to_countersignatory_value: u64, feerate_per_kw: u32,
3421		mut nondust_htlcs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>
3422	) -> CommitmentTransaction {
3423		let broadcaster_keys = &self.onchain_tx_handler.channel_transaction_parameters
3424			.counterparty_parameters.as_ref().unwrap().pubkeys;
3425		let countersignatory_keys =
3426			&self.onchain_tx_handler.channel_transaction_parameters.holder_pubkeys;
3427
3428		let broadcaster_funding_key = broadcaster_keys.funding_pubkey;
3429		let countersignatory_funding_key = countersignatory_keys.funding_pubkey;
3430		let keys = TxCreationKeys::from_channel_static_keys(&their_per_commitment_point,
3431			&broadcaster_keys, &countersignatory_keys, &self.onchain_tx_handler.secp_ctx);
3432		let channel_parameters =
3433			&self.onchain_tx_handler.channel_transaction_parameters.as_counterparty_broadcastable();
3434
3435		CommitmentTransaction::new_with_auxiliary_htlc_data(commitment_number,
3436			to_broadcaster_value, to_countersignatory_value, broadcaster_funding_key,
3437			countersignatory_funding_key, keys, feerate_per_kw, &mut nondust_htlcs,
3438			channel_parameters)
3439	}
3440
3441	fn counterparty_commitment_txs_from_update(&self, update: &ChannelMonitorUpdate) -> Vec<CommitmentTransaction> {
3442		update.updates.iter().filter_map(|update| {
3443			match update {
3444				&ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid,
3445					ref htlc_outputs, commitment_number, their_per_commitment_point,
3446					feerate_per_kw: Some(feerate_per_kw),
3447					to_broadcaster_value_sat: Some(to_broadcaster_value),
3448					to_countersignatory_value_sat: Some(to_countersignatory_value) } => {
3449
3450					let nondust_htlcs = htlc_outputs.iter().filter_map(|(htlc, _)| {
3451						htlc.transaction_output_index.map(|_| (htlc.clone(), None))
3452					}).collect::<Vec<_>>();
3453
3454					let commitment_tx = self.build_counterparty_commitment_tx(commitment_number,
3455							&their_per_commitment_point, to_broadcaster_value,
3456							to_countersignatory_value, feerate_per_kw, nondust_htlcs);
3457
3458					debug_assert_eq!(commitment_tx.trust().txid(), commitment_txid);
3459
3460					Some(commitment_tx)
3461				},
3462				_ => None,
3463			}
3464		}).collect()
3465	}
3466
3467	fn sign_to_local_justice_tx(
3468		&self, mut justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64
3469	) -> Result<Transaction, ()> {
3470		let secret = self.get_secret(commitment_number).ok_or(())?;
3471		let per_commitment_key = SecretKey::from_slice(&secret).map_err(|_| ())?;
3472		let their_per_commitment_point = PublicKey::from_secret_key(
3473			&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
3474
3475		let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,
3476			&self.holder_revocation_basepoint, &their_per_commitment_point);
3477		let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,
3478			&self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &their_per_commitment_point);
3479		let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
3480			self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
3481
3482		let sig = self.onchain_tx_handler.signer.sign_justice_revoked_output(
3483			&justice_tx, input_idx, value, &per_commitment_key, &self.onchain_tx_handler.secp_ctx)?;
3484		justice_tx.input[input_idx].witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(sig));
3485		justice_tx.input[input_idx].witness.push(&[1u8]);
3486		justice_tx.input[input_idx].witness.push(revokeable_redeemscript.as_bytes());
3487		Ok(justice_tx)
3488	}
3489
3490	/// Can only fail if idx is < get_min_seen_secret
3491	fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
3492		self.commitment_secrets.get_secret(idx)
3493	}
3494
3495	fn get_min_seen_secret(&self) -> u64 {
3496		self.commitment_secrets.get_min_seen_secret()
3497	}
3498
3499	fn get_cur_counterparty_commitment_number(&self) -> u64 {
3500		self.current_counterparty_commitment_number
3501	}
3502
3503	fn get_cur_holder_commitment_number(&self) -> u64 {
3504		self.current_holder_commitment_number
3505	}
3506
3507	/// Attempts to claim a counterparty commitment transaction's outputs using the revocation key and
3508	/// data in counterparty_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
3509	/// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
3510	/// HTLC-Success/HTLC-Timeout transactions.
3511	///
3512	/// Returns packages to claim the revoked output(s) and general information about the output that
3513	/// is to the counterparty in the commitment transaction.
3514	fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L)
3515		-> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo)
3516	where L::Target: Logger {
3517		// Most secp and related errors trying to create keys means we have no hope of constructing
3518		// a spend transaction...so we return no transactions to broadcast
3519		let mut claimable_outpoints = Vec::new();
3520		let mut to_counterparty_output_info = None;
3521
3522		let commitment_txid = tx.compute_txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
3523		let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
3524
3525		macro_rules! ignore_error {
3526			( $thing : expr ) => {
3527				match $thing {
3528					Ok(a) => a,
3529					Err(_) => return (claimable_outpoints, to_counterparty_output_info)
3530				}
3531			};
3532		}
3533
3534		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);
3535		if commitment_number >= self.get_min_seen_secret() {
3536			let secret = self.get_secret(commitment_number).unwrap();
3537			let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
3538			let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
3539			let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,  &self.holder_revocation_basepoint, &per_commitment_point,);
3540			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));
3541
3542			let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
3543			let revokeable_p2wsh = revokeable_redeemscript.to_p2wsh();
3544
3545			// First, process non-htlc outputs (to_holder & to_counterparty)
3546			for (idx, outp) in tx.output.iter().enumerate() {
3547				if outp.script_pubkey == revokeable_p2wsh {
3548					let revk_outp = RevokedOutput::build(per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key, self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key, outp.value, self.counterparty_commitment_params.on_counterparty_tx_csv, self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx(), height);
3549					let justice_package = PackageTemplate::build_package(
3550						commitment_txid, idx as u32,
3551						PackageSolvingData::RevokedOutput(revk_outp),
3552						height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32,
3553					);
3554					claimable_outpoints.push(justice_package);
3555					to_counterparty_output_info =
3556						Some((idx.try_into().expect("Txn can't have more than 2^32 outputs"), outp.value));
3557				}
3558			}
3559
3560			// Then, try to find revoked htlc outputs
3561			if let Some(per_commitment_claimable_data) = per_commitment_option {
3562				for (htlc, _) in per_commitment_claimable_data {
3563					if let Some(transaction_output_index) = htlc.transaction_output_index {
3564						if transaction_output_index as usize >= tx.output.len() ||
3565								tx.output[transaction_output_index as usize].value != htlc.to_bitcoin_amount() {
3566							// per_commitment_data is corrupt or our commitment signing key leaked!
3567							return (claimable_outpoints, to_counterparty_output_info);
3568						}
3569						let revk_htlc_outp = RevokedHTLCOutput::build(per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key, self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key, htlc.amount_msat / 1000, htlc.clone(), &self.onchain_tx_handler.channel_transaction_parameters.channel_type_features, height);
3570						let counterparty_spendable_height = if htlc.offered {
3571							htlc.cltv_expiry
3572						} else {
3573							height
3574						};
3575						let justice_package = PackageTemplate::build_package(
3576							commitment_txid,
3577							transaction_output_index,
3578							PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp),
3579							counterparty_spendable_height,
3580						);
3581						claimable_outpoints.push(justice_package);
3582					}
3583				}
3584			}
3585
3586			// Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
3587			if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
3588				// We're definitely a counterparty commitment transaction!
3589				log_error!(logger, "Got broadcast of revoked counterparty commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
3590				self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
3591
3592				if let Some(per_commitment_claimable_data) = per_commitment_option {
3593					fail_unbroadcast_htlcs!(self, "revoked_counterparty", commitment_txid, tx, height,
3594						block_hash, per_commitment_claimable_data.iter().map(|(htlc, htlc_source)|
3595							(htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
3596						), logger);
3597				} else {
3598					// Our fuzzers aren't constrained by pesky things like valid signatures, so can
3599					// spend our funding output with a transaction which doesn't match our past
3600					// commitment transactions. Thus, we can only debug-assert here when not
3601					// fuzzing.
3602					debug_assert!(cfg!(fuzzing), "We should have per-commitment option for any recognized old commitment txn");
3603					fail_unbroadcast_htlcs!(self, "revoked counterparty", commitment_txid, tx, height,
3604						block_hash, [].iter().map(|reference| *reference), logger);
3605				}
3606			}
3607		} else if let Some(per_commitment_claimable_data) = per_commitment_option {
3608			// While this isn't useful yet, there is a potential race where if a counterparty
3609			// revokes a state at the same time as the commitment transaction for that state is
3610			// confirmed, and the watchtower receives the block before the user, the user could
3611			// upload a new ChannelMonitor with the revocation secret but the watchtower has
3612			// already processed the block, resulting in the counterparty_commitment_txn_on_chain entry
3613			// not being generated by the above conditional. Thus, to be safe, we go ahead and
3614			// insert it here.
3615			self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
3616
3617			log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
3618			fail_unbroadcast_htlcs!(self, "counterparty", commitment_txid, tx, height, block_hash,
3619				per_commitment_claimable_data.iter().map(|(htlc, htlc_source)|
3620					(htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
3621				), logger);
3622			let (htlc_claim_reqs, counterparty_output_info) =
3623				self.get_counterparty_output_claim_info(commitment_number, commitment_txid, Some(tx), per_commitment_option, Some(height));
3624			to_counterparty_output_info = counterparty_output_info;
3625			for req in htlc_claim_reqs {
3626				claimable_outpoints.push(req);
3627			}
3628
3629		}
3630		(claimable_outpoints, to_counterparty_output_info)
3631	}
3632
3633	/// Returns the HTLC claim package templates and the counterparty output info
3634	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>>)>>, confirmation_height: Option<u32>)
3635	-> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo) {
3636		let mut claimable_outpoints = Vec::new();
3637		let mut to_counterparty_output_info: CommitmentTxCounterpartyOutputInfo = None;
3638
3639		let per_commitment_claimable_data = match per_commitment_option {
3640			Some(outputs) => outputs,
3641			None => return (claimable_outpoints, to_counterparty_output_info),
3642		};
3643		let per_commitment_points = match self.their_cur_per_commitment_points {
3644			Some(points) => points,
3645			None => return (claimable_outpoints, to_counterparty_output_info),
3646		};
3647
3648		let per_commitment_point =
3649			// If the counterparty commitment tx is the latest valid state, use their latest
3650			// per-commitment point
3651			if per_commitment_points.0 == commitment_number { &per_commitment_points.1 }
3652			else if let Some(point) = per_commitment_points.2.as_ref() {
3653				// If counterparty commitment tx is the state previous to the latest valid state, use
3654				// their previous per-commitment point (non-atomicity of revocation means it's valid for
3655				// them to temporarily have two valid commitment txns from our viewpoint)
3656				if per_commitment_points.0 == commitment_number + 1 {
3657					point
3658				} else { return (claimable_outpoints, to_counterparty_output_info); }
3659			} else { return (claimable_outpoints, to_counterparty_output_info); };
3660
3661		if let Some(transaction) = tx {
3662			let revocation_pubkey = RevocationKey::from_basepoint(
3663				&self.onchain_tx_handler.secp_ctx,  &self.holder_revocation_basepoint, &per_commitment_point);
3664
3665			let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx, &self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &per_commitment_point);
3666
3667			let revokeable_p2wsh = chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
3668				self.counterparty_commitment_params.on_counterparty_tx_csv,
3669				&delayed_key).to_p2wsh();
3670			for (idx, outp) in transaction.output.iter().enumerate() {
3671				if outp.script_pubkey == revokeable_p2wsh {
3672					to_counterparty_output_info =
3673						Some((idx.try_into().expect("Can't have > 2^32 outputs"), outp.value));
3674				}
3675			}
3676		}
3677
3678		for  &(ref htlc, _) in per_commitment_claimable_data.iter() {
3679			if let Some(transaction_output_index) = htlc.transaction_output_index {
3680				if let Some(transaction) = tx {
3681					if transaction_output_index as usize >= transaction.output.len() ||
3682						transaction.output[transaction_output_index as usize].value != htlc.to_bitcoin_amount() {
3683							// per_commitment_data is corrupt or our commitment signing key leaked!
3684							return (claimable_outpoints, to_counterparty_output_info);
3685						}
3686				}
3687				let preimage = if htlc.offered { if let Some((p, _)) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
3688				if preimage.is_some() || !htlc.offered {
3689					let counterparty_htlc_outp = if htlc.offered {
3690						PackageSolvingData::CounterpartyOfferedHTLCOutput(
3691							CounterpartyOfferedHTLCOutput::build(*per_commitment_point,
3692								self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3693								self.counterparty_commitment_params.counterparty_htlc_base_key,
3694								preimage.unwrap(), htlc.clone(), self.onchain_tx_handler.channel_type_features().clone(),
3695								confirmation_height))
3696					} else {
3697						PackageSolvingData::CounterpartyReceivedHTLCOutput(
3698							CounterpartyReceivedHTLCOutput::build(*per_commitment_point,
3699								self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3700								self.counterparty_commitment_params.counterparty_htlc_base_key,
3701								htlc.clone(), self.onchain_tx_handler.channel_type_features().clone(),
3702								confirmation_height))
3703					};
3704					let counterparty_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, counterparty_htlc_outp, htlc.cltv_expiry);
3705					claimable_outpoints.push(counterparty_package);
3706				}
3707			}
3708		}
3709
3710		(claimable_outpoints, to_counterparty_output_info)
3711	}
3712
3713	/// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
3714	fn check_spend_counterparty_htlc<L: Deref>(
3715		&mut self, tx: &Transaction, commitment_number: u64, commitment_txid: &Txid, height: u32, logger: &L
3716	) -> (Vec<PackageTemplate>, Option<TransactionOutputs>) where L::Target: Logger {
3717		let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
3718		let per_commitment_key = match SecretKey::from_slice(&secret) {
3719			Ok(key) => key,
3720			Err(_) => return (Vec::new(), None)
3721		};
3722		let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
3723
3724		let htlc_txid = tx.compute_txid();
3725		let mut claimable_outpoints = vec![];
3726		let mut outputs_to_watch = None;
3727		// Previously, we would only claim HTLCs from revoked HTLC transactions if they had 1 input
3728		// with a witness of 5 elements and 1 output. This wasn't enough for anchor outputs, as the
3729		// counterparty can now aggregate multiple HTLCs into a single transaction thanks to
3730		// `SIGHASH_SINGLE` remote signatures, leading us to not claim any HTLCs upon seeing a
3731		// confirmed revoked HTLC transaction (for more details, see
3732		// https://lists.linuxfoundation.org/pipermail/lightning-dev/2022-April/003561.html).
3733		//
3734		// We make sure we're not vulnerable to this case by checking all inputs of the transaction,
3735		// and claim those which spend the commitment transaction, have a witness of 5 elements, and
3736		// have a corresponding output at the same index within the transaction.
3737		for (idx, input) in tx.input.iter().enumerate() {
3738			if input.previous_output.txid == *commitment_txid && input.witness.len() == 5 && tx.output.get(idx).is_some() {
3739				log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, idx);
3740				let revk_outp = RevokedOutput::build(
3741					per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3742					self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key,
3743					tx.output[idx].value, self.counterparty_commitment_params.on_counterparty_tx_csv,
3744					false, height,
3745				);
3746				let justice_package = PackageTemplate::build_package(
3747					htlc_txid, idx as u32, PackageSolvingData::RevokedOutput(revk_outp),
3748					height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32,
3749				);
3750				claimable_outpoints.push(justice_package);
3751				if outputs_to_watch.is_none() {
3752					outputs_to_watch = Some((htlc_txid, vec![]));
3753				}
3754				outputs_to_watch.as_mut().unwrap().1.push((idx as u32, tx.output[idx].clone()));
3755			}
3756		}
3757		(claimable_outpoints, outputs_to_watch)
3758	}
3759
3760	// Returns (1) `PackageTemplate`s that can be given to the OnchainTxHandler, so that the handler can
3761	// broadcast transactions claiming holder HTLC commitment outputs and (2) a holder revokable
3762	// script so we can detect whether a holder transaction has been seen on-chain.
3763	fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec<PackageTemplate>, Option<(ScriptBuf, PublicKey, RevocationKey)>) {
3764		let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
3765
3766		let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
3767		let broadcasted_holder_revokable_script = Some((redeemscript.to_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
3768
3769		for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
3770			if let Some(transaction_output_index) = htlc.transaction_output_index {
3771				let (htlc_output, counterparty_spendable_height) = if htlc.offered {
3772					let htlc_output = HolderHTLCOutput::build_offered(
3773						htlc.amount_msat, htlc.cltv_expiry, self.onchain_tx_handler.channel_type_features().clone(), conf_height
3774					);
3775					(htlc_output, conf_height)
3776				} else {
3777					let payment_preimage = if let Some((preimage, _)) = self.payment_preimages.get(&htlc.payment_hash) {
3778						preimage.clone()
3779					} else {
3780						// We can't build an HTLC-Success transaction without the preimage
3781						continue;
3782					};
3783					let htlc_output = HolderHTLCOutput::build_accepted(
3784						payment_preimage, htlc.amount_msat, self.onchain_tx_handler.channel_type_features().clone(), conf_height
3785					);
3786					(htlc_output, htlc.cltv_expiry)
3787				};
3788				let htlc_package = PackageTemplate::build_package(
3789					holder_tx.txid, transaction_output_index,
3790					PackageSolvingData::HolderHTLCOutput(htlc_output),
3791					counterparty_spendable_height,
3792				);
3793				claim_requests.push(htlc_package);
3794			}
3795		}
3796
3797		(claim_requests, broadcasted_holder_revokable_script)
3798	}
3799
3800	// Returns holder HTLC outputs to watch and react to in case of spending.
3801	fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderSignedTx, commitment_tx: &Transaction) -> Vec<(u32, TxOut)> {
3802		let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
3803		for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
3804			if let Some(transaction_output_index) = htlc.transaction_output_index {
3805				watch_outputs.push((transaction_output_index, commitment_tx.output[transaction_output_index as usize].clone()));
3806			}
3807		}
3808		watch_outputs
3809	}
3810
3811	/// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
3812	/// revoked using data in holder_claimable_outpoints.
3813	/// Should not be used if check_spend_revoked_transaction succeeds.
3814	/// Returns None unless the transaction is definitely one of our commitment transactions.
3815	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 {
3816		let commitment_txid = tx.compute_txid();
3817		let mut claim_requests = Vec::new();
3818		let mut watch_outputs = Vec::new();
3819
3820		macro_rules! append_onchain_update {
3821			($updates: expr, $to_watch: expr) => {
3822				claim_requests = $updates.0;
3823				self.broadcasted_holder_revokable_script = $updates.1;
3824				watch_outputs.append(&mut $to_watch);
3825			}
3826		}
3827
3828		// HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
3829		let mut is_holder_tx = false;
3830
3831		if self.current_holder_commitment_tx.txid == commitment_txid {
3832			is_holder_tx = true;
3833			log_info!(logger, "Got broadcast of latest holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
3834			let res = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, height);
3835			let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, tx);
3836			append_onchain_update!(res, to_watch);
3837			fail_unbroadcast_htlcs!(self, "latest holder", commitment_txid, tx, height,
3838				block_hash, self.current_holder_commitment_tx.htlc_outputs.iter()
3839				.map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())), logger);
3840		} else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
3841			if holder_tx.txid == commitment_txid {
3842				is_holder_tx = true;
3843				log_info!(logger, "Got broadcast of previous holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
3844				let res = self.get_broadcasted_holder_claims(holder_tx, height);
3845				let mut to_watch = self.get_broadcasted_holder_watch_outputs(holder_tx, tx);
3846				append_onchain_update!(res, to_watch);
3847				fail_unbroadcast_htlcs!(self, "previous holder", commitment_txid, tx, height, block_hash,
3848					holder_tx.htlc_outputs.iter().map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())),
3849					logger);
3850			}
3851		}
3852
3853		if is_holder_tx {
3854			Some((claim_requests, (commitment_txid, watch_outputs)))
3855		} else {
3856			None
3857		}
3858	}
3859
3860	/// Cancels any existing pending claims for a commitment that previously confirmed and has now
3861	/// been replaced by another.
3862	pub fn cancel_prev_commitment_claims<L: Deref>(
3863		&mut self, logger: &L, confirmed_commitment_txid: &Txid
3864	) where L::Target: Logger {
3865		for (counterparty_commitment_txid, _) in &self.counterparty_commitment_txn_on_chain {
3866			// Cancel any pending claims for counterparty commitments we've seen confirm.
3867			if counterparty_commitment_txid == confirmed_commitment_txid {
3868				continue;
3869			}
3870			// If we have generated claims for counterparty_commitment_txid earlier, we can rely on always
3871			// having claim related htlcs for counterparty_commitment_txid in counterparty_claimable_outpoints.
3872			for (htlc, _) in self.counterparty_claimable_outpoints.get(counterparty_commitment_txid).unwrap_or(&vec![]) {
3873				log_trace!(logger, "Canceling claims for previously confirmed counterparty commitment {}",
3874					counterparty_commitment_txid);
3875				let mut outpoint = BitcoinOutPoint { txid: *counterparty_commitment_txid, vout: 0 };
3876				if let Some(vout) = htlc.transaction_output_index {
3877					outpoint.vout = vout;
3878					self.onchain_tx_handler.abandon_claim(&outpoint);
3879				}
3880			}
3881		}
3882		// Cancel any pending claims for any holder commitments in case they had previously
3883		// confirmed or been signed (in which case we will start attempting to claim without
3884		// waiting for confirmation).
3885		if self.current_holder_commitment_tx.txid != *confirmed_commitment_txid {
3886			log_trace!(logger, "Canceling claims for previously broadcast holder commitment {}",
3887				self.current_holder_commitment_tx.txid);
3888			let mut outpoint = BitcoinOutPoint { txid: self.current_holder_commitment_tx.txid, vout: 0 };
3889			for (htlc, _, _) in &self.current_holder_commitment_tx.htlc_outputs {
3890				if let Some(vout) = htlc.transaction_output_index {
3891					outpoint.vout = vout;
3892					self.onchain_tx_handler.abandon_claim(&outpoint);
3893				}
3894			}
3895		}
3896		if let Some(prev_holder_commitment_tx) = &self.prev_holder_signed_commitment_tx {
3897			if prev_holder_commitment_tx.txid != *confirmed_commitment_txid {
3898				log_trace!(logger, "Canceling claims for previously broadcast holder commitment {}",
3899					prev_holder_commitment_tx.txid);
3900				let mut outpoint = BitcoinOutPoint { txid: prev_holder_commitment_tx.txid, vout: 0 };
3901				for (htlc, _, _) in &prev_holder_commitment_tx.htlc_outputs {
3902					if let Some(vout) = htlc.transaction_output_index {
3903						outpoint.vout = vout;
3904						self.onchain_tx_handler.abandon_claim(&outpoint);
3905					}
3906				}
3907			}
3908		}
3909	}
3910
3911	#[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
3912	/// Note that this includes possibly-locktimed-in-the-future transactions!
3913	fn unsafe_get_latest_holder_commitment_txn<L: Deref>(
3914		&mut self, logger: &WithChannelMonitor<L>
3915	) -> Vec<Transaction> where L::Target: Logger {
3916		log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
3917		let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
3918		let txid = commitment_tx.compute_txid();
3919		let mut holder_transactions = vec![commitment_tx];
3920		// When anchor outputs are present, the HTLC transactions are only final once the commitment
3921		// transaction confirms due to the CSV 1 encumberance.
3922		if self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
3923			return holder_transactions;
3924		}
3925		for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
3926			if let Some(vout) = htlc.0.transaction_output_index {
3927				let preimage = if !htlc.0.offered {
3928					if let Some((preimage, _)) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
3929						// We can't build an HTLC-Success transaction without the preimage
3930						continue;
3931					}
3932				} else { None };
3933				if let Some(htlc_tx) = self.onchain_tx_handler.get_maybe_signed_htlc_tx(
3934					&::bitcoin::OutPoint { txid, vout }, &preimage
3935				) {
3936					if htlc_tx.is_fully_signed() {
3937						holder_transactions.push(htlc_tx.0);
3938					}
3939				}
3940			}
3941		}
3942		holder_transactions
3943	}
3944
3945	fn block_connected<B: Deref, F: Deref, L: Deref>(
3946		&mut self, header: &Header, txdata: &TransactionData, height: u32, broadcaster: B,
3947		fee_estimator: F, logger: &WithChannelMonitor<L>,
3948	) -> Vec<TransactionOutputs>
3949		where B::Target: BroadcasterInterface,
3950			F::Target: FeeEstimator,
3951			L::Target: Logger,
3952	{
3953		let block_hash = header.block_hash();
3954		self.best_block = BestBlock::new(block_hash, height);
3955
3956		let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
3957		self.transactions_confirmed(header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
3958	}
3959
3960	fn best_block_updated<B: Deref, F: Deref, L: Deref>(
3961		&mut self,
3962		header: &Header,
3963		height: u32,
3964		broadcaster: B,
3965		fee_estimator: &LowerBoundedFeeEstimator<F>,
3966		logger: &WithChannelMonitor<L>,
3967	) -> Vec<TransactionOutputs>
3968	where
3969		B::Target: BroadcasterInterface,
3970		F::Target: FeeEstimator,
3971		L::Target: Logger,
3972	{
3973		let block_hash = header.block_hash();
3974
3975		if height > self.best_block.height {
3976			self.best_block = BestBlock::new(block_hash, height);
3977			log_trace!(logger, "Connecting new block {} at height {}", block_hash, height);
3978			self.block_confirmed(height, block_hash, vec![], vec![], vec![], &broadcaster, &fee_estimator, logger)
3979		} else if block_hash != self.best_block.block_hash {
3980			self.best_block = BestBlock::new(block_hash, height);
3981			log_trace!(logger, "Best block re-orged, replaced with new block {} at height {}", block_hash, height);
3982			self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
3983			let conf_target = self.closure_conf_target();
3984			self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, conf_target, fee_estimator, logger);
3985			Vec::new()
3986		} else { Vec::new() }
3987	}
3988
3989	fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
3990		&mut self,
3991		header: &Header,
3992		txdata: &TransactionData,
3993		height: u32,
3994		broadcaster: B,
3995		fee_estimator: &LowerBoundedFeeEstimator<F>,
3996		logger: &WithChannelMonitor<L>,
3997	) -> Vec<TransactionOutputs>
3998	where
3999		B::Target: BroadcasterInterface,
4000		F::Target: FeeEstimator,
4001		L::Target: Logger,
4002	{
4003		let txn_matched = self.filter_block(txdata);
4004		for tx in &txn_matched {
4005			let mut output_val = Amount::ZERO;
4006			for out in tx.output.iter() {
4007				if out.value > Amount::MAX_MONEY { panic!("Value-overflowing transaction provided to block connected"); }
4008				output_val += out.value;
4009				if output_val > Amount::MAX_MONEY { panic!("Value-overflowing transaction provided to block connected"); }
4010			}
4011		}
4012
4013		let block_hash = header.block_hash();
4014
4015		let mut watch_outputs = Vec::new();
4016		let mut claimable_outpoints = Vec::new();
4017		'tx_iter: for tx in &txn_matched {
4018			let txid = tx.compute_txid();
4019			log_trace!(logger, "Transaction {} confirmed in block {}", txid , block_hash);
4020			// If a transaction has already been confirmed, ensure we don't bother processing it duplicatively.
4021			if Some(txid) == self.funding_spend_confirmed {
4022				log_debug!(logger, "Skipping redundant processing of funding-spend tx {} as it was previously confirmed", txid);
4023				continue 'tx_iter;
4024			}
4025			for ev in self.onchain_events_awaiting_threshold_conf.iter() {
4026				if ev.txid == txid {
4027					if let Some(conf_hash) = ev.block_hash {
4028						assert_eq!(header.block_hash(), conf_hash,
4029							"Transaction {} was already confirmed and is being re-confirmed in a different block.\n\
4030							This indicates a severe bug in the transaction connection logic - a reorg should have been processed first!", ev.txid);
4031					}
4032					log_debug!(logger, "Skipping redundant processing of confirming tx {} as it was previously confirmed", txid);
4033					continue 'tx_iter;
4034				}
4035			}
4036			for htlc in self.htlcs_resolved_on_chain.iter() {
4037				if Some(txid) == htlc.resolving_txid {
4038					log_debug!(logger, "Skipping redundant processing of HTLC resolution tx {} as it was previously confirmed", txid);
4039					continue 'tx_iter;
4040				}
4041			}
4042			for spendable_txid in self.spendable_txids_confirmed.iter() {
4043				if txid == *spendable_txid {
4044					log_debug!(logger, "Skipping redundant processing of spendable tx {} as it was previously confirmed", txid);
4045					continue 'tx_iter;
4046				}
4047			}
4048
4049			if tx.input.len() == 1 {
4050				// Assuming our keys were not leaked (in which case we're screwed no matter what),
4051				// commitment transactions and HTLC transactions will all only ever have one input
4052				// (except for HTLC transactions for channels with anchor outputs), which is an easy
4053				// way to filter out any potential non-matching txn for lazy filters.
4054				let prevout = &tx.input[0].previous_output;
4055				if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
4056					let mut balance_spendable_csv = None;
4057					log_info!(logger, "Channel {} closed by funding output spend in txid {}.",
4058						&self.channel_id(), txid);
4059					self.funding_spend_seen = true;
4060					let mut commitment_tx_to_counterparty_output = None;
4061					if (tx.input[0].sequence.0 >> 8*3) as u8 == 0x80 && (tx.lock_time.to_consensus_u32() >> 8*3) as u8 == 0x20 {
4062						if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(&tx, height, &block_hash, &logger) {
4063							if !new_outputs.1.is_empty() {
4064								watch_outputs.push(new_outputs);
4065							}
4066
4067							claimable_outpoints.append(&mut new_outpoints);
4068							balance_spendable_csv = Some(self.on_holder_tx_csv);
4069						} else {
4070							let mut new_watch_outputs = Vec::new();
4071							for (idx, outp) in tx.output.iter().enumerate() {
4072								new_watch_outputs.push((idx as u32, outp.clone()));
4073							}
4074							watch_outputs.push((txid, new_watch_outputs));
4075
4076							let (mut new_outpoints, counterparty_output_idx_sats) =
4077								self.check_spend_counterparty_transaction(&tx, height, &block_hash, &logger);
4078							commitment_tx_to_counterparty_output = counterparty_output_idx_sats;
4079
4080							claimable_outpoints.append(&mut new_outpoints);
4081						}
4082					}
4083					self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4084						txid,
4085						transaction: Some((*tx).clone()),
4086						height,
4087						block_hash: Some(block_hash),
4088						event: OnchainEvent::FundingSpendConfirmation {
4089							on_local_output_csv: balance_spendable_csv,
4090							commitment_tx_to_counterparty_output,
4091						},
4092					});
4093					// Now that we've detected a confirmed commitment transaction, attempt to cancel
4094					// pending claims for any commitments that were previously confirmed such that
4095					// we don't continue claiming inputs that no longer exist.
4096					self.cancel_prev_commitment_claims(&logger, &txid);
4097				}
4098			}
4099			if tx.input.len() >= 1 {
4100				// While all commitment transactions have one input, HTLC transactions may have more
4101				// if the HTLC was present in an anchor channel. HTLCs can also be resolved in a few
4102				// other ways which can have more than one output.
4103				for tx_input in &tx.input {
4104					let commitment_txid = tx_input.previous_output.txid;
4105					if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&commitment_txid) {
4106						let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(
4107							&tx, commitment_number, &commitment_txid, height, &logger
4108						);
4109						claimable_outpoints.append(&mut new_outpoints);
4110						if let Some(new_outputs) = new_outputs_option {
4111							watch_outputs.push(new_outputs);
4112						}
4113						// Since there may be multiple HTLCs for this channel (all spending the
4114						// same commitment tx) being claimed by the counterparty within the same
4115						// transaction, and `check_spend_counterparty_htlc` already checks all the
4116						// ones relevant to this channel, we can safely break from our loop.
4117						break;
4118					}
4119				}
4120				self.is_resolving_htlc_output(&tx, height, &block_hash, logger);
4121
4122				self.check_tx_and_push_spendable_outputs(&tx, height, &block_hash, logger);
4123			}
4124		}
4125
4126		if height > self.best_block.height {
4127			self.best_block = BestBlock::new(block_hash, height);
4128		}
4129
4130		self.block_confirmed(height, block_hash, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, logger)
4131	}
4132
4133	/// Update state for new block(s)/transaction(s) confirmed. Note that the caller must update
4134	/// `self.best_block` before calling if a new best blockchain tip is available. More
4135	/// concretely, `self.best_block` must never be at a lower height than `conf_height`, avoiding
4136	/// complexity especially in
4137	/// `OnchainTx::update_claims_view_from_requests`/`OnchainTx::update_claims_view_from_matched_txn`.
4138	///
4139	/// `conf_height` should be set to the height at which any new transaction(s)/block(s) were
4140	/// confirmed at, even if it is not the current best height.
4141	fn block_confirmed<B: Deref, F: Deref, L: Deref>(
4142		&mut self,
4143		conf_height: u32,
4144		conf_hash: BlockHash,
4145		txn_matched: Vec<&Transaction>,
4146		mut watch_outputs: Vec<TransactionOutputs>,
4147		mut claimable_outpoints: Vec<PackageTemplate>,
4148		broadcaster: &B,
4149		fee_estimator: &LowerBoundedFeeEstimator<F>,
4150		logger: &WithChannelMonitor<L>,
4151	) -> Vec<TransactionOutputs>
4152	where
4153		B::Target: BroadcasterInterface,
4154		F::Target: FeeEstimator,
4155		L::Target: Logger,
4156	{
4157		log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
4158		debug_assert!(self.best_block.height >= conf_height);
4159
4160		let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
4161		if should_broadcast {
4162			let (mut new_outpoints, mut new_outputs) = self.generate_claimable_outpoints_and_watch_outputs(ClosureReason::HTLCsTimedOut);
4163			claimable_outpoints.append(&mut new_outpoints);
4164			watch_outputs.append(&mut new_outputs);
4165		}
4166
4167		// Find which on-chain events have reached their confirmation threshold.
4168		let (onchain_events_reaching_threshold_conf, onchain_events_awaiting_threshold_conf): (Vec<_>, Vec<_>) =
4169			self.onchain_events_awaiting_threshold_conf.drain(..).partition(
4170				|entry| entry.has_reached_confirmation_threshold(&self.best_block));
4171		self.onchain_events_awaiting_threshold_conf = onchain_events_awaiting_threshold_conf;
4172
4173		// Used to check for duplicate HTLC resolutions.
4174		#[cfg(debug_assertions)]
4175		let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
4176			.iter()
4177			.filter_map(|entry| match &entry.event {
4178				OnchainEvent::HTLCUpdate { source, .. } => Some(source),
4179				_ => None,
4180			})
4181			.collect();
4182		#[cfg(debug_assertions)]
4183		let mut matured_htlcs = Vec::new();
4184
4185		// Produce actionable events from on-chain events having reached their threshold.
4186		for entry in onchain_events_reaching_threshold_conf {
4187			match entry.event {
4188				OnchainEvent::HTLCUpdate { source, payment_hash, htlc_value_satoshis, commitment_tx_output_idx } => {
4189					// Check for duplicate HTLC resolutions.
4190					#[cfg(debug_assertions)]
4191					{
4192						debug_assert!(
4193							!unmatured_htlcs.contains(&&source),
4194							"An unmature 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						debug_assert!(
4198							!matured_htlcs.contains(&source),
4199							"A matured HTLC transaction conflicts with a maturing one; failed to \
4200							 call either transaction_unconfirmed for the conflicting transaction \
4201							 or block_disconnected for a block containing it.");
4202						matured_htlcs.push(source.clone());
4203					}
4204
4205					log_debug!(logger, "HTLC {} failure update in {} has got enough confirmations to be passed upstream",
4206						&payment_hash, entry.txid);
4207					self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4208						payment_hash,
4209						payment_preimage: None,
4210						source,
4211						htlc_value_satoshis,
4212					}));
4213					self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
4214						commitment_tx_output_idx,
4215						resolving_txid: Some(entry.txid),
4216						resolving_tx: entry.transaction,
4217						payment_preimage: None,
4218					});
4219				},
4220				OnchainEvent::MaturingOutput { descriptor } => {
4221					log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
4222					self.pending_events.push(Event::SpendableOutputs {
4223						outputs: vec![descriptor],
4224						channel_id: Some(self.channel_id()),
4225					});
4226					self.spendable_txids_confirmed.push(entry.txid);
4227				},
4228				OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. } => {
4229					self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
4230						commitment_tx_output_idx: Some(commitment_tx_output_idx),
4231						resolving_txid: Some(entry.txid),
4232						resolving_tx: entry.transaction,
4233						payment_preimage: preimage,
4234					});
4235				},
4236				OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } => {
4237					self.funding_spend_confirmed = Some(entry.txid);
4238					self.confirmed_commitment_tx_counterparty_output = commitment_tx_to_counterparty_output;
4239				},
4240			}
4241		}
4242
4243		if self.no_further_updates_allowed() {
4244			// Fail back HTLCs on backwards channels if they expire within
4245			// `LATENCY_GRACE_PERIOD_BLOCKS` blocks and the channel is closed (i.e. we're at a
4246			// point where no further off-chain updates will be accepted). If we haven't seen the
4247			// preimage for an HTLC by the time the previous hop's timeout expires, we've lost that
4248			// HTLC, so we might as well fail it back instead of having our counterparty force-close
4249			// the inbound channel.
4250			let current_holder_htlcs = self.current_holder_commitment_tx.htlc_outputs.iter()
4251				.map(|&(ref a, _, ref b)| (a, b.as_ref()));
4252
4253			let current_counterparty_htlcs = if let Some(txid) = self.current_counterparty_commitment_txid {
4254				if let Some(htlc_outputs) = self.counterparty_claimable_outpoints.get(&txid) {
4255					Some(htlc_outputs.iter().map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))))
4256				} else { None }
4257			} else { None }.into_iter().flatten();
4258
4259			let prev_counterparty_htlcs = if let Some(txid) = self.prev_counterparty_commitment_txid {
4260				if let Some(htlc_outputs) = self.counterparty_claimable_outpoints.get(&txid) {
4261					Some(htlc_outputs.iter().map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))))
4262				} else { None }
4263			} else { None }.into_iter().flatten();
4264
4265			let htlcs = current_holder_htlcs
4266				.chain(current_counterparty_htlcs)
4267				.chain(prev_counterparty_htlcs);
4268
4269			let height = self.best_block.height;
4270			for (htlc, source_opt) in htlcs {
4271				// Only check forwarded HTLCs' previous hops
4272				let source = match source_opt {
4273					Some(source) => source,
4274					None => continue,
4275				};
4276				let inbound_htlc_expiry = match source.inbound_htlc_expiry() {
4277					Some(cltv_expiry) => cltv_expiry,
4278					None => continue,
4279				};
4280				let max_expiry_height = height.saturating_add(LATENCY_GRACE_PERIOD_BLOCKS);
4281				if inbound_htlc_expiry > max_expiry_height {
4282					continue;
4283				}
4284				let duplicate_event = self.pending_monitor_events.iter().any(
4285					|update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
4286						upd.source == *source
4287					} else { false });
4288				if duplicate_event {
4289					continue;
4290				}
4291				if !self.failed_back_htlc_ids.insert(SentHTLCId::from_source(source)) {
4292					continue;
4293				}
4294				if !duplicate_event {
4295					log_error!(logger, "Failing back HTLC {} upstream to preserve the \
4296						channel as the forward HTLC hasn't resolved and our backward HTLC \
4297						expires soon at {}", log_bytes!(htlc.payment_hash.0), inbound_htlc_expiry);
4298					self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4299						source: source.clone(),
4300						payment_preimage: None,
4301						payment_hash: htlc.payment_hash,
4302						htlc_value_satoshis: Some(htlc.amount_msat / 1000),
4303					}));
4304				}
4305			}
4306		}
4307
4308		let conf_target = self.closure_conf_target();
4309		self.onchain_tx_handler.update_claims_view_from_requests(claimable_outpoints, conf_height, self.best_block.height, broadcaster, conf_target, fee_estimator, logger);
4310		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);
4311
4312		// Determine new outputs to watch by comparing against previously known outputs to watch,
4313		// updating the latter in the process.
4314		watch_outputs.retain(|&(ref txid, ref txouts)| {
4315			let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
4316			self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
4317		});
4318		#[cfg(test)]
4319		{
4320			// If we see a transaction for which we registered outputs previously,
4321			// make sure the registered scriptpubkey at the expected index match
4322			// the actual transaction output one. We failed this case before #653.
4323			for tx in &txn_matched {
4324				if let Some(outputs) = self.get_outputs_to_watch().get(&tx.compute_txid()) {
4325					for idx_and_script in outputs.iter() {
4326						assert!((idx_and_script.0 as usize) < tx.output.len());
4327						assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
4328					}
4329				}
4330			}
4331		}
4332		watch_outputs
4333	}
4334
4335	fn block_disconnected<B: Deref, F: Deref, L: Deref>(
4336		&mut self, header: &Header, height: u32, broadcaster: B, fee_estimator: F, logger: &WithChannelMonitor<L>
4337	) where B::Target: BroadcasterInterface,
4338		F::Target: FeeEstimator,
4339		L::Target: Logger,
4340	{
4341		log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
4342
4343		//We may discard:
4344		//- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
4345		//- maturing spendable output has transaction paying us has been disconnected
4346		self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height < height);
4347
4348		let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
4349		let conf_target = self.closure_conf_target();
4350		self.onchain_tx_handler.block_disconnected(height, broadcaster, conf_target, &bounded_fee_estimator, logger);
4351
4352		self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
4353	}
4354
4355	fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
4356		&mut self,
4357		txid: &Txid,
4358		broadcaster: B,
4359		fee_estimator: &LowerBoundedFeeEstimator<F>,
4360		logger: &WithChannelMonitor<L>,
4361	) where
4362		B::Target: BroadcasterInterface,
4363		F::Target: FeeEstimator,
4364		L::Target: Logger,
4365	{
4366		let mut removed_height = None;
4367		for entry in self.onchain_events_awaiting_threshold_conf.iter() {
4368			if entry.txid == *txid {
4369				removed_height = Some(entry.height);
4370				break;
4371			}
4372		}
4373
4374		if let Some(removed_height) = removed_height {
4375			log_info!(logger, "transaction_unconfirmed of txid {} implies height {} was reorg'd out", txid, removed_height);
4376			self.onchain_events_awaiting_threshold_conf.retain(|ref entry| if entry.height >= removed_height {
4377				log_info!(logger, "Transaction {} reorg'd out", entry.txid);
4378				false
4379			} else { true });
4380		}
4381
4382		debug_assert!(!self.onchain_events_awaiting_threshold_conf.iter().any(|ref entry| entry.txid == *txid));
4383
4384		let conf_target = self.closure_conf_target();
4385		self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, conf_target, fee_estimator, logger);
4386	}
4387
4388	/// Filters a block's `txdata` for transactions spending watched outputs or for any child
4389	/// transactions thereof.
4390	fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
4391		let mut matched_txn = new_hash_set();
4392		txdata.iter().filter(|&&(_, tx)| {
4393			let mut matches = self.spends_watched_output(tx);
4394			for input in tx.input.iter() {
4395				if matches { break; }
4396				if matched_txn.contains(&input.previous_output.txid) {
4397					matches = true;
4398				}
4399			}
4400			if matches {
4401				matched_txn.insert(tx.compute_txid());
4402			}
4403			matches
4404		}).map(|(_, tx)| *tx).collect()
4405	}
4406
4407	/// Checks if a given transaction spends any watched outputs.
4408	fn spends_watched_output(&self, tx: &Transaction) -> bool {
4409		for input in tx.input.iter() {
4410			if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
4411				for (idx, _script_pubkey) in outputs.iter() {
4412					if *idx == input.previous_output.vout {
4413						#[cfg(test)]
4414						{
4415							// If the expected script is a known type, check that the witness
4416							// appears to be spending the correct type (ie that the match would
4417							// actually succeed in BIP 158/159-style filters).
4418							if _script_pubkey.is_p2wsh() {
4419								if input.witness.last().unwrap().to_vec() == deliberately_bogus_accepted_htlc_witness_program() {
4420									// In at least one test we use a deliberately bogus witness
4421									// script which hit an old panic. Thus, we check for that here
4422									// and avoid the assert if its the expected bogus script.
4423									return true;
4424								}
4425
4426								assert_eq!(&bitcoin::Address::p2wsh(&ScriptBuf::from(input.witness.last().unwrap().to_vec()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
4427							} else if _script_pubkey.is_p2wpkh() {
4428								assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::CompressedPublicKey(bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap().inner), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
4429							} else { panic!(); }
4430						}
4431						return true;
4432					}
4433				}
4434			}
4435		}
4436
4437		false
4438	}
4439
4440	fn should_broadcast_holder_commitment_txn<L: Deref>(
4441		&self, logger: &WithChannelMonitor<L>
4442	) -> bool where L::Target: Logger {
4443		// There's no need to broadcast our commitment transaction if we've seen one confirmed (even
4444		// with 1 confirmation) as it'll be rejected as duplicate/conflicting.
4445		if self.funding_spend_confirmed.is_some() ||
4446			self.onchain_events_awaiting_threshold_conf.iter().find(|event| match event.event {
4447				OnchainEvent::FundingSpendConfirmation { .. } => true,
4448				_ => false,
4449			}).is_some()
4450		{
4451			return false;
4452		}
4453		// We need to consider all HTLCs which are:
4454		//  * in any unrevoked counterparty commitment transaction, as they could broadcast said
4455		//    transactions and we'd end up in a race, or
4456		//  * are in our latest holder commitment transaction, as this is the thing we will
4457		//    broadcast if we go on-chain.
4458		// Note that we consider HTLCs which were below dust threshold here - while they don't
4459		// strictly imply that we need to fail the channel, we need to go ahead and fail them back
4460		// to the source, and if we don't fail the channel we will have to ensure that the next
4461		// updates that peer sends us are update_fails, failing the channel if not. It's probably
4462		// easier to just fail the channel as this case should be rare enough anyway.
4463		let height = self.best_block.height;
4464		macro_rules! scan_commitment {
4465			($htlcs: expr, $holder_tx: expr) => {
4466				for ref htlc in $htlcs {
4467					// For inbound HTLCs which we know the preimage for, we have to ensure we hit the
4468					// chain with enough room to claim the HTLC without our counterparty being able to
4469					// time out the HTLC first.
4470					// For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
4471					// concern is being able to claim the corresponding inbound HTLC (on another
4472					// channel) before it expires. In fact, we don't even really care if our
4473					// counterparty here claims such an outbound HTLC after it expired as long as we
4474					// can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
4475					// chain when our counterparty is waiting for expiration to off-chain fail an HTLC
4476					// we give ourselves a few blocks of headroom after expiration before going
4477					// on-chain for an expired HTLC.
4478					// Note that, to avoid a potential attack whereby a node delays claiming an HTLC
4479					// from us until we've reached the point where we go on-chain with the
4480					// corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
4481					// least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
4482					//  aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
4483					//      inbound_cltv == height + CLTV_CLAIM_BUFFER
4484					//      outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
4485					//      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
4486					//      CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
4487					//      LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
4488					//  The final, above, condition is checked for statically in channelmanager
4489					//  with CHECK_CLTV_EXPIRY_SANITY_2.
4490					let htlc_outbound = $holder_tx == htlc.offered;
4491					if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
4492					   (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
4493						log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
4494						return true;
4495					}
4496				}
4497			}
4498		}
4499
4500		scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
4501
4502		if let Some(ref txid) = self.current_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		if let Some(ref txid) = self.prev_counterparty_commitment_txid {
4508			if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
4509				scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
4510			}
4511		}
4512
4513		false
4514	}
4515
4516	/// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder
4517	/// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
4518	fn is_resolving_htlc_output<L: Deref>(
4519		&mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor<L>,
4520	) where L::Target: Logger {
4521		'outer_loop: for input in &tx.input {
4522			let mut payment_data = None;
4523			let htlc_claim = HTLCClaim::from_witness(&input.witness);
4524			let revocation_sig_claim = htlc_claim == Some(HTLCClaim::Revocation);
4525			let accepted_preimage_claim = htlc_claim == Some(HTLCClaim::AcceptedPreimage);
4526			#[cfg(not(fuzzing))]
4527			let accepted_timeout_claim = htlc_claim == Some(HTLCClaim::AcceptedTimeout);
4528			let offered_preimage_claim = htlc_claim == Some(HTLCClaim::OfferedPreimage);
4529			#[cfg(not(fuzzing))]
4530			let offered_timeout_claim = htlc_claim == Some(HTLCClaim::OfferedTimeout);
4531
4532			let mut payment_preimage = PaymentPreimage([0; 32]);
4533			if offered_preimage_claim || accepted_preimage_claim {
4534				payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
4535			}
4536
4537			macro_rules! log_claim {
4538				($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
4539					let outbound_htlc = $holder_tx == $htlc.offered;
4540					// HTLCs must either be claimed by a matching script type or through the
4541					// revocation path:
4542					#[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
4543					debug_assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim);
4544					#[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
4545					debug_assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim);
4546					// Further, only exactly one of the possible spend paths should have been
4547					// matched by any HTLC spend:
4548					#[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
4549					debug_assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
4550					                 offered_preimage_claim as u8 + offered_timeout_claim as u8 +
4551					                 revocation_sig_claim as u8, 1);
4552					if ($holder_tx && revocation_sig_claim) ||
4553							(outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
4554						log_error!(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 { "preimage claim after we'd passed the HTLC resolution back. We can likely claim the HTLC output with a revocation claim" });
4558					} else {
4559						log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
4560							$tx_info, input.previous_output.txid, input.previous_output.vout, tx.compute_txid(),
4561							if outbound_htlc { "outbound" } else { "inbound" }, &$htlc.payment_hash,
4562							if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
4563					}
4564				}
4565			}
4566
4567			macro_rules! check_htlc_valid_counterparty {
4568				($htlc_output: expr, $per_commitment_data: expr) => {
4569						for &(ref pending_htlc, ref pending_source) in $per_commitment_data {
4570							if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
4571								if let &Some(ref source) = pending_source {
4572									log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
4573									payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
4574									break;
4575								}
4576							}
4577						}
4578				}
4579			}
4580
4581			macro_rules! scan_commitment {
4582				($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
4583					for (ref htlc_output, source_option) in $htlcs {
4584						if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
4585							if let Some(ref source) = source_option {
4586								log_claim!($tx_info, $holder_tx, htlc_output, true);
4587								// We have a resolution of an HTLC either from one of our latest
4588								// holder commitment transactions or an unrevoked counterparty commitment
4589								// transaction. This implies we either learned a preimage, the HTLC
4590								// has timed out, or we screwed up. In any case, we should now
4591								// resolve the source HTLC with the original sender.
4592								payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
4593							} else if !$holder_tx {
4594								if let Some(current_counterparty_commitment_txid) = &self.current_counterparty_commitment_txid {
4595									check_htlc_valid_counterparty!(htlc_output, self.counterparty_claimable_outpoints.get(current_counterparty_commitment_txid).unwrap());
4596								}
4597								if payment_data.is_none() {
4598									if let Some(prev_counterparty_commitment_txid) = &self.prev_counterparty_commitment_txid {
4599										check_htlc_valid_counterparty!(htlc_output, self.counterparty_claimable_outpoints.get(prev_counterparty_commitment_txid).unwrap());
4600									}
4601								}
4602							}
4603							if payment_data.is_none() {
4604								log_claim!($tx_info, $holder_tx, htlc_output, false);
4605								let outbound_htlc = $holder_tx == htlc_output.offered;
4606								self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4607									txid: tx.compute_txid(), height, block_hash: Some(*block_hash), transaction: Some(tx.clone()),
4608									event: OnchainEvent::HTLCSpendConfirmation {
4609										commitment_tx_output_idx: input.previous_output.vout,
4610										preimage: if accepted_preimage_claim || offered_preimage_claim {
4611											Some(payment_preimage) } else { None },
4612										// If this is a payment to us (ie !outbound_htlc), wait for
4613										// the CSV delay before dropping the HTLC from claimable
4614										// balance if the claim was an HTLC-Success transaction (ie
4615										// accepted_preimage_claim).
4616										on_to_local_output_csv: if accepted_preimage_claim && !outbound_htlc {
4617											Some(self.on_holder_tx_csv) } else { None },
4618									},
4619								});
4620								continue 'outer_loop;
4621							}
4622						}
4623					}
4624				}
4625			}
4626
4627			if input.previous_output.txid == self.current_holder_commitment_tx.txid {
4628				scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
4629					"our latest holder commitment tx", true);
4630			}
4631			if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
4632				if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
4633					scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
4634						"our previous holder commitment tx", true);
4635				}
4636			}
4637			if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
4638				scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))),
4639					"counterparty commitment tx", false);
4640			}
4641
4642			// Check that scan_commitment, above, decided there is some source worth relaying an
4643			// HTLC resolution backwards to and figure out whether we learned a preimage from it.
4644			if let Some((source, payment_hash, amount_msat)) = payment_data {
4645				if accepted_preimage_claim {
4646					if !self.pending_monitor_events.iter().any(
4647						|update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
4648						self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4649							txid: tx.compute_txid(),
4650							height,
4651							block_hash: Some(*block_hash),
4652							transaction: Some(tx.clone()),
4653							event: OnchainEvent::HTLCSpendConfirmation {
4654								commitment_tx_output_idx: input.previous_output.vout,
4655								preimage: Some(payment_preimage),
4656								on_to_local_output_csv: None,
4657							},
4658						});
4659						self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4660							source,
4661							payment_preimage: Some(payment_preimage),
4662							payment_hash,
4663							htlc_value_satoshis: Some(amount_msat / 1000),
4664						}));
4665					}
4666				} else if offered_preimage_claim {
4667					if !self.pending_monitor_events.iter().any(
4668						|update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
4669							upd.source == source
4670						} else { false }) {
4671						self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4672							txid: tx.compute_txid(),
4673							transaction: Some(tx.clone()),
4674							height,
4675							block_hash: Some(*block_hash),
4676							event: OnchainEvent::HTLCSpendConfirmation {
4677								commitment_tx_output_idx: input.previous_output.vout,
4678								preimage: Some(payment_preimage),
4679								on_to_local_output_csv: None,
4680							},
4681						});
4682						self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4683							source,
4684							payment_preimage: Some(payment_preimage),
4685							payment_hash,
4686							htlc_value_satoshis: Some(amount_msat / 1000),
4687						}));
4688					}
4689				} else {
4690					self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
4691						if entry.height != height { return true; }
4692						match entry.event {
4693							OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
4694								*htlc_source != source
4695							},
4696							_ => true,
4697						}
4698					});
4699					let entry = OnchainEventEntry {
4700						txid: tx.compute_txid(),
4701						transaction: Some(tx.clone()),
4702						height,
4703						block_hash: Some(*block_hash),
4704						event: OnchainEvent::HTLCUpdate {
4705							source,
4706							payment_hash,
4707							htlc_value_satoshis: Some(amount_msat / 1000),
4708							commitment_tx_output_idx: Some(input.previous_output.vout),
4709						},
4710					};
4711					log_info!(logger, "Failing HTLC with payment_hash {} timeout by a spend tx, waiting for confirmation (at height {})", &payment_hash, entry.confirmation_threshold());
4712					self.onchain_events_awaiting_threshold_conf.push(entry);
4713				}
4714			}
4715		}
4716	}
4717
4718	fn get_spendable_outputs(&self, tx: &Transaction) -> Vec<SpendableOutputDescriptor> {
4719		let mut spendable_outputs = Vec::new();
4720		for (i, outp) in tx.output.iter().enumerate() {
4721			if outp.script_pubkey == self.destination_script {
4722				spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
4723					outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
4724					output: outp.clone(),
4725					channel_keys_id: Some(self.channel_keys_id),
4726				});
4727			}
4728			if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
4729				if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
4730					spendable_outputs.push(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
4731						outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
4732						per_commitment_point: broadcasted_holder_revokable_script.1,
4733						to_self_delay: self.on_holder_tx_csv,
4734						output: outp.clone(),
4735						revocation_pubkey: broadcasted_holder_revokable_script.2,
4736						channel_keys_id: self.channel_keys_id,
4737						channel_value_satoshis: self.channel_value_satoshis,
4738						channel_transaction_parameters: Some(self.onchain_tx_handler.channel_transaction_parameters.clone()),
4739					}));
4740				}
4741			}
4742			if self.counterparty_payment_script == outp.script_pubkey {
4743				spendable_outputs.push(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
4744					outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
4745					output: outp.clone(),
4746					channel_keys_id: self.channel_keys_id,
4747					channel_value_satoshis: self.channel_value_satoshis,
4748					channel_transaction_parameters: Some(self.onchain_tx_handler.channel_transaction_parameters.clone()),
4749				}));
4750			}
4751			if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
4752				spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
4753					outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
4754					output: outp.clone(),
4755					channel_keys_id: Some(self.channel_keys_id),
4756				});
4757			}
4758		}
4759		spendable_outputs
4760	}
4761
4762	/// Checks if the confirmed transaction is paying funds back to some address we can assume to
4763	/// own.
4764	fn check_tx_and_push_spendable_outputs<L: Deref>(
4765		&mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor<L>,
4766	) where L::Target: Logger {
4767		for spendable_output in self.get_spendable_outputs(tx) {
4768			let entry = OnchainEventEntry {
4769				txid: tx.compute_txid(),
4770				transaction: Some(tx.clone()),
4771				height,
4772				block_hash: Some(*block_hash),
4773				event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
4774			};
4775			log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
4776			self.onchain_events_awaiting_threshold_conf.push(entry);
4777		}
4778	}
4779}
4780
4781impl<Signer: EcdsaChannelSigner, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
4782where
4783	T::Target: BroadcasterInterface,
4784	F::Target: FeeEstimator,
4785	L::Target: Logger,
4786{
4787	fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
4788		self.0.block_connected(header, txdata, height, &*self.1, &*self.2, &self.3);
4789	}
4790
4791	fn block_disconnected(&self, header: &Header, height: u32) {
4792		self.0.block_disconnected(header, height, &*self.1, &*self.2, &self.3);
4793	}
4794}
4795
4796impl<Signer: EcdsaChannelSigner, M, T: Deref, F: Deref, L: Deref> chain::Confirm for (M, T, F, L)
4797where
4798	M: Deref<Target = ChannelMonitor<Signer>>,
4799	T::Target: BroadcasterInterface,
4800	F::Target: FeeEstimator,
4801	L::Target: Logger,
4802{
4803	fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) {
4804		self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &self.3);
4805	}
4806
4807	fn transaction_unconfirmed(&self, txid: &Txid) {
4808		self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &self.3);
4809	}
4810
4811	fn best_block_updated(&self, header: &Header, height: u32) {
4812		self.0.best_block_updated(header, height, &*self.1, &*self.2, &self.3);
4813	}
4814
4815	fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
4816		self.0.get_relevant_txids()
4817	}
4818}
4819
4820const MAX_ALLOC_SIZE: usize = 64*1024;
4821
4822impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP)>
4823		for (BlockHash, ChannelMonitor<SP::EcdsaSigner>) {
4824	fn read<R: io::Read>(reader: &mut R, args: (&'a ES, &'b SP)) -> Result<Self, DecodeError> {
4825		macro_rules! unwrap_obj {
4826			($key: expr) => {
4827				match $key {
4828					Ok(res) => res,
4829					Err(_) => return Err(DecodeError::InvalidValue),
4830				}
4831			}
4832		}
4833
4834		let (entropy_source, signer_provider) = args;
4835
4836		let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
4837
4838		let latest_update_id: u64 = Readable::read(reader)?;
4839		let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
4840
4841		let destination_script = Readable::read(reader)?;
4842		let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
4843			0 => {
4844				let revokable_address = Readable::read(reader)?;
4845				let per_commitment_point = Readable::read(reader)?;
4846				let revokable_script = Readable::read(reader)?;
4847				Some((revokable_address, per_commitment_point, revokable_script))
4848			},
4849			1 => { None },
4850			_ => return Err(DecodeError::InvalidValue),
4851		};
4852		let mut counterparty_payment_script: ScriptBuf = Readable::read(reader)?;
4853		let shutdown_script = {
4854			let script = <ScriptBuf as Readable>::read(reader)?;
4855			if script.is_empty() { None } else { Some(script) }
4856		};
4857
4858		let channel_keys_id = Readable::read(reader)?;
4859		let holder_revocation_basepoint = Readable::read(reader)?;
4860		// Technically this can fail and serialize fail a round-trip, but only for serialization of
4861		// barely-init'd ChannelMonitors that we can't do anything with.
4862		let outpoint = OutPoint {
4863			txid: Readable::read(reader)?,
4864			index: Readable::read(reader)?,
4865		};
4866		let funding_info = (outpoint, Readable::read(reader)?);
4867		let current_counterparty_commitment_txid = Readable::read(reader)?;
4868		let prev_counterparty_commitment_txid = Readable::read(reader)?;
4869
4870		let counterparty_commitment_params = Readable::read(reader)?;
4871		let funding_redeemscript = Readable::read(reader)?;
4872		let channel_value_satoshis = Readable::read(reader)?;
4873
4874		let their_cur_per_commitment_points = {
4875			let first_idx = <U48 as Readable>::read(reader)?.0;
4876			if first_idx == 0 {
4877				None
4878			} else {
4879				let first_point = Readable::read(reader)?;
4880				let second_point_slice: [u8; 33] = Readable::read(reader)?;
4881				if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
4882					Some((first_idx, first_point, None))
4883				} else {
4884					Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
4885				}
4886			}
4887		};
4888
4889		let on_holder_tx_csv: u16 = Readable::read(reader)?;
4890
4891		let commitment_secrets = Readable::read(reader)?;
4892
4893		macro_rules! read_htlc_in_commitment {
4894			() => {
4895				{
4896					let offered: bool = Readable::read(reader)?;
4897					let amount_msat: u64 = Readable::read(reader)?;
4898					let cltv_expiry: u32 = Readable::read(reader)?;
4899					let payment_hash: PaymentHash = Readable::read(reader)?;
4900					let transaction_output_index: Option<u32> = Readable::read(reader)?;
4901
4902					HTLCOutputInCommitment {
4903						offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
4904					}
4905				}
4906			}
4907		}
4908
4909		let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
4910		let mut counterparty_claimable_outpoints = hash_map_with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
4911		for _ in 0..counterparty_claimable_outpoints_len {
4912			let txid: Txid = Readable::read(reader)?;
4913			let htlcs_count: u64 = Readable::read(reader)?;
4914			let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
4915			for _ in 0..htlcs_count {
4916				htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
4917			}
4918			if counterparty_claimable_outpoints.insert(txid, htlcs).is_some() {
4919				return Err(DecodeError::InvalidValue);
4920			}
4921		}
4922
4923		let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
4924		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));
4925		for _ in 0..counterparty_commitment_txn_on_chain_len {
4926			let txid: Txid = Readable::read(reader)?;
4927			let commitment_number = <U48 as Readable>::read(reader)?.0;
4928			if counterparty_commitment_txn_on_chain.insert(txid, commitment_number).is_some() {
4929				return Err(DecodeError::InvalidValue);
4930			}
4931		}
4932
4933		let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
4934		let mut counterparty_hash_commitment_number = hash_map_with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
4935		for _ in 0..counterparty_hash_commitment_number_len {
4936			let payment_hash: PaymentHash = Readable::read(reader)?;
4937			let commitment_number = <U48 as Readable>::read(reader)?.0;
4938			if counterparty_hash_commitment_number.insert(payment_hash, commitment_number).is_some() {
4939				return Err(DecodeError::InvalidValue);
4940			}
4941		}
4942
4943		let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
4944			match <u8 as Readable>::read(reader)? {
4945				0 => None,
4946				1 => Some(Readable::read(reader)?),
4947				_ => return Err(DecodeError::InvalidValue),
4948			};
4949		let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
4950
4951		let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
4952		let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
4953
4954		let payment_preimages_len: u64 = Readable::read(reader)?;
4955		let mut payment_preimages = hash_map_with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
4956		for _ in 0..payment_preimages_len {
4957			let preimage: PaymentPreimage = Readable::read(reader)?;
4958			let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
4959			if payment_preimages.insert(hash, (preimage, Vec::new())).is_some() {
4960				return Err(DecodeError::InvalidValue);
4961			}
4962		}
4963
4964		let pending_monitor_events_len: u64 = Readable::read(reader)?;
4965		let mut pending_monitor_events = Some(
4966			Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
4967		for _ in 0..pending_monitor_events_len {
4968			let ev = match <u8 as Readable>::read(reader)? {
4969				0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
4970				1 => MonitorEvent::HolderForceClosed(funding_info.0),
4971				_ => return Err(DecodeError::InvalidValue)
4972			};
4973			pending_monitor_events.as_mut().unwrap().push(ev);
4974		}
4975
4976		let pending_events_len: u64 = Readable::read(reader)?;
4977		let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
4978		for _ in 0..pending_events_len {
4979			if let Some(event) = MaybeReadable::read(reader)? {
4980				pending_events.push(event);
4981			}
4982		}
4983
4984		let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
4985
4986		let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
4987		let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
4988		for _ in 0..waiting_threshold_conf_len {
4989			if let Some(val) = MaybeReadable::read(reader)? {
4990				onchain_events_awaiting_threshold_conf.push(val);
4991			}
4992		}
4993
4994		let outputs_to_watch_len: u64 = Readable::read(reader)?;
4995		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>>())));
4996		for _ in 0..outputs_to_watch_len {
4997			let txid = Readable::read(reader)?;
4998			let outputs_len: u64 = Readable::read(reader)?;
4999			let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<ScriptBuf>())));
5000			for _ in 0..outputs_len {
5001				outputs.push((Readable::read(reader)?, Readable::read(reader)?));
5002			}
5003			if outputs_to_watch.insert(txid, outputs).is_some() {
5004				return Err(DecodeError::InvalidValue);
5005			}
5006		}
5007		let onchain_tx_handler: OnchainTxHandler<SP::EcdsaSigner> = ReadableArgs::read(
5008			reader, (entropy_source, signer_provider, channel_value_satoshis, channel_keys_id)
5009		)?;
5010
5011		let lockdown_from_offchain = Readable::read(reader)?;
5012		let holder_tx_signed = Readable::read(reader)?;
5013
5014		if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
5015			let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
5016			if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
5017			if prev_commitment_tx.to_self_value_sat == u64::MAX {
5018				prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
5019			} else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
5020				return Err(DecodeError::InvalidValue);
5021			}
5022		}
5023
5024		let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
5025		if current_holder_commitment_tx.to_self_value_sat == u64::MAX {
5026			current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
5027		} else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
5028			return Err(DecodeError::InvalidValue);
5029		}
5030
5031		let mut funding_spend_confirmed = None;
5032		let mut htlcs_resolved_on_chain = Some(Vec::new());
5033		let mut funding_spend_seen = Some(false);
5034		let mut counterparty_node_id = None;
5035		let mut confirmed_commitment_tx_counterparty_output = None;
5036		let mut spendable_txids_confirmed = Some(Vec::new());
5037		let mut counterparty_fulfilled_htlcs = Some(new_hash_map());
5038		let mut initial_counterparty_commitment_info = None;
5039		let mut balances_empty_height = None;
5040		let mut channel_id = None;
5041		let mut holder_pays_commitment_tx_fee = None;
5042		let mut payment_preimages_with_info: Option<HashMap<_, _>> = None;
5043		read_tlv_fields!(reader, {
5044			(1, funding_spend_confirmed, option),
5045			(3, htlcs_resolved_on_chain, optional_vec),
5046			(5, pending_monitor_events, optional_vec),
5047			(7, funding_spend_seen, option),
5048			(9, counterparty_node_id, option),
5049			(11, confirmed_commitment_tx_counterparty_output, option),
5050			(13, spendable_txids_confirmed, optional_vec),
5051			(15, counterparty_fulfilled_htlcs, option),
5052			(17, initial_counterparty_commitment_info, option),
5053			(19, channel_id, option),
5054			(21, balances_empty_height, option),
5055			(23, holder_pays_commitment_tx_fee, option),
5056			(25, payment_preimages_with_info, option),
5057		});
5058		if let Some(payment_preimages_with_info) = payment_preimages_with_info {
5059			if payment_preimages_with_info.len() != payment_preimages.len() {
5060				return Err(DecodeError::InvalidValue);
5061			}
5062			for (payment_hash, (payment_preimage, _)) in payment_preimages.iter() {
5063				// Note that because `payment_preimages` is built back from preimages directly,
5064				// checking that the two maps have the same hash -> preimage pairs also checks that
5065				// the payment hashes in `payment_preimages_with_info`'s preimages match its
5066				// hashes.
5067				let new_preimage = payment_preimages_with_info.get(payment_hash).map(|(p, _)| p);
5068				if new_preimage != Some(payment_preimage) {
5069					return Err(DecodeError::InvalidValue);
5070				}
5071			}
5072			payment_preimages = payment_preimages_with_info;
5073		}
5074
5075		// `HolderForceClosedWithInfo` replaced `HolderForceClosed` in v0.0.122. If we have both
5076		// events, we can remove the `HolderForceClosed` event and just keep the `HolderForceClosedWithInfo`.
5077		if let Some(ref mut pending_monitor_events) = pending_monitor_events {
5078			if pending_monitor_events.iter().any(|e| matches!(e, MonitorEvent::HolderForceClosed(_))) &&
5079				pending_monitor_events.iter().any(|e| matches!(e, MonitorEvent::HolderForceClosedWithInfo { .. }))
5080			{
5081				pending_monitor_events.retain(|e| !matches!(e, MonitorEvent::HolderForceClosed(_)));
5082			}
5083		}
5084
5085		// Monitors for anchor outputs channels opened in v0.0.116 suffered from a bug in which the
5086		// wrong `counterparty_payment_script` was being tracked. Fix it now on deserialization to
5087		// give them a chance to recognize the spendable output.
5088		if onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() &&
5089			counterparty_payment_script.is_p2wpkh()
5090		{
5091			let payment_point = onchain_tx_handler.channel_transaction_parameters.holder_pubkeys.payment_point;
5092			counterparty_payment_script =
5093				chan_utils::get_to_countersignatory_with_anchors_redeemscript(&payment_point).to_p2wsh();
5094		}
5095
5096		Ok((best_block.block_hash, ChannelMonitor::from_impl(ChannelMonitorImpl {
5097			latest_update_id,
5098			commitment_transaction_number_obscure_factor,
5099
5100			destination_script,
5101			broadcasted_holder_revokable_script,
5102			counterparty_payment_script,
5103			shutdown_script,
5104
5105			channel_keys_id,
5106			holder_revocation_basepoint,
5107			channel_id: channel_id.unwrap_or(ChannelId::v1_from_funding_outpoint(outpoint)),
5108			funding_info,
5109			current_counterparty_commitment_txid,
5110			prev_counterparty_commitment_txid,
5111
5112			counterparty_commitment_params,
5113			funding_redeemscript,
5114			channel_value_satoshis,
5115			their_cur_per_commitment_points,
5116
5117			on_holder_tx_csv,
5118
5119			commitment_secrets,
5120			counterparty_claimable_outpoints,
5121			counterparty_commitment_txn_on_chain,
5122			counterparty_hash_commitment_number,
5123			counterparty_fulfilled_htlcs: counterparty_fulfilled_htlcs.unwrap(),
5124
5125			prev_holder_signed_commitment_tx,
5126			current_holder_commitment_tx,
5127			current_counterparty_commitment_number,
5128			current_holder_commitment_number,
5129
5130			payment_preimages,
5131			pending_monitor_events: pending_monitor_events.unwrap(),
5132			pending_events,
5133			is_processing_pending_events: false,
5134
5135			onchain_events_awaiting_threshold_conf,
5136			outputs_to_watch,
5137
5138			onchain_tx_handler,
5139
5140			lockdown_from_offchain,
5141			holder_tx_signed,
5142			holder_pays_commitment_tx_fee,
5143			funding_spend_seen: funding_spend_seen.unwrap(),
5144			funding_spend_confirmed,
5145			confirmed_commitment_tx_counterparty_output,
5146			htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
5147			spendable_txids_confirmed: spendable_txids_confirmed.unwrap(),
5148
5149			best_block,
5150			counterparty_node_id,
5151			initial_counterparty_commitment_info,
5152			balances_empty_height,
5153			failed_back_htlc_ids: new_hash_set(),
5154		})))
5155	}
5156}
5157
5158#[cfg(test)]
5159mod tests {
5160	use bitcoin::amount::Amount;
5161	use bitcoin::locktime::absolute::LockTime;
5162	use bitcoin::script::{ScriptBuf, Builder};
5163	use bitcoin::opcodes;
5164	use bitcoin::transaction::{Transaction, TxIn, TxOut, Version};
5165	use bitcoin::transaction::OutPoint as BitcoinOutPoint;
5166	use bitcoin::sighash;
5167	use bitcoin::sighash::EcdsaSighashType;
5168	use bitcoin::hashes::Hash;
5169	use bitcoin::hashes::sha256::Hash as Sha256;
5170	use bitcoin::hex::FromHex;
5171	use bitcoin::hash_types::{BlockHash, Txid};
5172	use bitcoin::network::Network;
5173	use bitcoin::secp256k1::{SecretKey,PublicKey};
5174	use bitcoin::secp256k1::Secp256k1;
5175	use bitcoin::{Sequence, Witness};
5176
5177	use crate::chain::chaininterface::LowerBoundedFeeEstimator;
5178
5179	use super::ChannelMonitorUpdateStep;
5180	use crate::{check_added_monitors, check_spends, get_local_commitment_txn, get_monitor, get_route_and_payment_hash};
5181	use crate::chain::{BestBlock, Confirm};
5182	use crate::chain::channelmonitor::{ChannelMonitor, WithChannelMonitor};
5183	use crate::chain::package::{weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT};
5184	use crate::chain::transaction::OutPoint;
5185	use crate::sign::InMemorySigner;
5186	use crate::ln::types::ChannelId;
5187	use crate::types::payment::{PaymentPreimage, PaymentHash};
5188	use crate::ln::channel_keys::{DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, RevocationBasepoint, RevocationKey};
5189	use crate::ln::chan_utils::{self,HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
5190	use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
5191	use crate::ln::functional_test_utils::*;
5192	use crate::ln::script::ShutdownScript;
5193	use crate::util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
5194	use crate::util::ser::{ReadableArgs, Writeable};
5195	use crate::util::logger::Logger;
5196	use crate::sync::Arc;
5197	use crate::io;
5198	use crate::types::features::ChannelTypeFeatures;
5199
5200	#[allow(unused_imports)]
5201	use crate::prelude::*;
5202
5203	use std::str::FromStr;
5204
5205	fn do_test_funding_spend_refuses_updates(use_local_txn: bool) {
5206		// Previously, monitor updates were allowed freely even after a funding-spend transaction
5207		// confirmed. This would allow a race condition where we could receive a payment (including
5208		// the counterparty revoking their broadcasted state!) and accept it without recourse as
5209		// long as the ChannelMonitor receives the block first, the full commitment update dance
5210		// occurs after the block is connected, and before the ChannelManager receives the block.
5211		// Obviously this is an incredibly contrived race given the counterparty would be risking
5212		// their full channel balance for it, but its worth fixing nonetheless as it makes the
5213		// potential ChannelMonitor states simpler to reason about.
5214		//
5215		// This test checks said behavior, as well as ensuring a ChannelMonitorUpdate with multiple
5216		// updates is handled correctly in such conditions.
5217		let chanmon_cfgs = create_chanmon_cfgs(3);
5218		let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5219		let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5220		let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5221		let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
5222		create_announced_chan_between_nodes(&nodes, 1, 2);
5223
5224		// Rebalance somewhat
5225		send_payment(&nodes[0], &[&nodes[1]], 10_000_000);
5226
5227		// First route two payments for testing at the end
5228		let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
5229		let payment_preimage_2 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
5230
5231		let local_txn = get_local_commitment_txn!(nodes[1], channel.2);
5232		assert_eq!(local_txn.len(), 1);
5233		let remote_txn = get_local_commitment_txn!(nodes[0], channel.2);
5234		assert_eq!(remote_txn.len(), 3); // Commitment and two HTLC-Timeouts
5235		check_spends!(remote_txn[1], remote_txn[0]);
5236		check_spends!(remote_txn[2], remote_txn[0]);
5237		let broadcast_tx = if use_local_txn { &local_txn[0] } else { &remote_txn[0] };
5238
5239		// Connect a commitment transaction, but only to the ChainMonitor/ChannelMonitor. The
5240		// channel is now closed, but the ChannelManager doesn't know that yet.
5241		let new_header = create_dummy_header(nodes[0].best_block_info().0, 0);
5242		let conf_height = nodes[0].best_block_info().1 + 1;
5243		nodes[1].chain_monitor.chain_monitor.transactions_confirmed(&new_header,
5244			&[(0, broadcast_tx)], conf_height);
5245
5246		let (_, pre_update_monitor) = <(BlockHash, ChannelMonitor<InMemorySigner>)>::read(
5247						&mut io::Cursor::new(&get_monitor!(nodes[1], channel.2).encode()),
5248						(&nodes[1].keys_manager.backing, &nodes[1].keys_manager.backing)).unwrap();
5249
5250		// If the ChannelManager tries to update the channel, however, the ChainMonitor will pass
5251		// the update through to the ChannelMonitor which will refuse it (as the channel is closed).
5252		let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
5253		nodes[1].node.send_payment_with_route(route, payment_hash,
5254			RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
5255		).unwrap();
5256		check_added_monitors!(nodes[1], 1);
5257
5258		// Build a new ChannelMonitorUpdate which contains both the failing commitment tx update
5259		// and provides the claim preimages for the two pending HTLCs. The first update generates
5260		// an error, but the point of this test is to ensure the later updates are still applied.
5261		let monitor_updates = nodes[1].chain_monitor.monitor_updates.lock().unwrap();
5262		let mut replay_update = monitor_updates.get(&channel.2).unwrap().iter().rev().next().unwrap().clone();
5263		assert_eq!(replay_update.updates.len(), 1);
5264		if let ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } = replay_update.updates[0] {
5265		} else { panic!(); }
5266		replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage {
5267			payment_preimage: payment_preimage_1, payment_info: None,
5268		});
5269		replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage {
5270			payment_preimage: payment_preimage_2, payment_info: None,
5271		});
5272
5273		let broadcaster = TestBroadcaster::with_blocks(Arc::clone(&nodes[1].blocks));
5274		assert!(
5275			pre_update_monitor.update_monitor(&replay_update, &&broadcaster, &&chanmon_cfgs[1].fee_estimator, &nodes[1].logger)
5276			.is_err());
5277		// Even though we error'd on the first update, we should still have generated an HTLC claim
5278		// transaction
5279		let txn_broadcasted = broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
5280		assert!(txn_broadcasted.len() >= 2);
5281		let htlc_txn = txn_broadcasted.iter().filter(|tx| {
5282			assert_eq!(tx.input.len(), 1);
5283			tx.input[0].previous_output.txid == broadcast_tx.compute_txid()
5284		}).collect::<Vec<_>>();
5285		assert_eq!(htlc_txn.len(), 2);
5286		check_spends!(htlc_txn[0], broadcast_tx);
5287		check_spends!(htlc_txn[1], broadcast_tx);
5288	}
5289	#[test]
5290	fn test_funding_spend_refuses_updates() {
5291		do_test_funding_spend_refuses_updates(true);
5292		do_test_funding_spend_refuses_updates(false);
5293	}
5294
5295	#[test]
5296	fn test_prune_preimages() {
5297		let secp_ctx = Secp256k1::new();
5298		let logger = Arc::new(TestLogger::new());
5299		let broadcaster = Arc::new(TestBroadcaster::new(Network::Testnet));
5300		let fee_estimator = TestFeeEstimator::new(253);
5301
5302		let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5303
5304		let mut preimages = Vec::new();
5305		{
5306			for i in 0..20 {
5307				let preimage = PaymentPreimage([i; 32]);
5308				let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
5309				preimages.push((preimage, hash));
5310			}
5311		}
5312
5313		macro_rules! preimages_slice_to_htlcs {
5314			($preimages_slice: expr) => {
5315				{
5316					let mut res = Vec::new();
5317					for (idx, preimage) in $preimages_slice.iter().enumerate() {
5318						res.push((HTLCOutputInCommitment {
5319							offered: true,
5320							amount_msat: 0,
5321							cltv_expiry: 0,
5322							payment_hash: preimage.1.clone(),
5323							transaction_output_index: Some(idx as u32),
5324						}, ()));
5325					}
5326					res
5327				}
5328			}
5329		}
5330		macro_rules! preimages_slice_to_htlc_outputs {
5331			($preimages_slice: expr) => {
5332				preimages_slice_to_htlcs!($preimages_slice).into_iter().map(|(htlc, _)| (htlc, None)).collect()
5333			}
5334		}
5335		let dummy_sig = crate::crypto::utils::sign(&secp_ctx,
5336			&bitcoin::secp256k1::Message::from_digest([42; 32]),
5337			&SecretKey::from_slice(&[42; 32]).unwrap());
5338
5339		macro_rules! test_preimages_exist {
5340			($preimages_slice: expr, $monitor: expr) => {
5341				for preimage in $preimages_slice {
5342					assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
5343				}
5344			}
5345		}
5346
5347		let keys = InMemorySigner::new(
5348			&secp_ctx,
5349			SecretKey::from_slice(&[41; 32]).unwrap(),
5350			SecretKey::from_slice(&[41; 32]).unwrap(),
5351			SecretKey::from_slice(&[41; 32]).unwrap(),
5352			SecretKey::from_slice(&[41; 32]).unwrap(),
5353			SecretKey::from_slice(&[41; 32]).unwrap(),
5354			[41; 32],
5355			0,
5356			[0; 32],
5357			[0; 32],
5358		);
5359
5360		let counterparty_pubkeys = ChannelPublicKeys {
5361			funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
5362			revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())),
5363			payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
5364			delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
5365			htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap()))
5366		};
5367		let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::MAX };
5368		let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
5369		let channel_parameters = ChannelTransactionParameters {
5370			holder_pubkeys: keys.holder_channel_pubkeys.clone(),
5371			holder_selected_contest_delay: 66,
5372			is_outbound_from_holder: true,
5373			counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
5374				pubkeys: counterparty_pubkeys,
5375				selected_contest_delay: 67,
5376			}),
5377			funding_outpoint: Some(funding_outpoint),
5378			channel_type_features: ChannelTypeFeatures::only_static_remote_key()
5379		};
5380		// Prune with one old state and a holder commitment tx holding a few overlaps with the
5381		// old state.
5382		let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5383		let best_block = BestBlock::from_network(Network::Testnet);
5384		let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
5385			Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &ScriptBuf::new(),
5386			(OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, ScriptBuf::new()),
5387			&channel_parameters, true, ScriptBuf::new(), 46, 0, HolderCommitmentTransaction::dummy(&mut Vec::new()),
5388			best_block, dummy_key, channel_id);
5389
5390		let mut htlcs = preimages_slice_to_htlcs!(preimages[0..10]);
5391		let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
5392
5393		monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
5394			htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect());
5395		monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"1").to_byte_array()),
5396			preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
5397		monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"2").to_byte_array()),
5398			preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
5399		for &(ref preimage, ref hash) in preimages.iter() {
5400			let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&fee_estimator);
5401			monitor.provide_payment_preimage_unsafe_legacy(
5402				hash, preimage, &broadcaster, &bounded_fee_estimator, &logger
5403			);
5404		}
5405
5406		// Now provide a secret, pruning preimages 10-15
5407		let mut secret = [0; 32];
5408		secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
5409		monitor.provide_secret(281474976710655, secret.clone()).unwrap();
5410		assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
5411		test_preimages_exist!(&preimages[0..10], monitor);
5412		test_preimages_exist!(&preimages[15..20], monitor);
5413
5414		monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"3").to_byte_array()),
5415			preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
5416
5417		// Now provide a further secret, pruning preimages 15-17
5418		secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
5419		monitor.provide_secret(281474976710654, secret.clone()).unwrap();
5420		assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
5421		test_preimages_exist!(&preimages[0..10], monitor);
5422		test_preimages_exist!(&preimages[17..20], monitor);
5423
5424		monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"4").to_byte_array()),
5425			preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
5426
5427		// Now update holder commitment tx info, pruning only element 18 as we still care about the
5428		// previous commitment tx's preimages too
5429		let mut htlcs = preimages_slice_to_htlcs!(preimages[0..5]);
5430		let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
5431		monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
5432			htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect());
5433		secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
5434		monitor.provide_secret(281474976710653, secret.clone()).unwrap();
5435		assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
5436		test_preimages_exist!(&preimages[0..10], monitor);
5437		test_preimages_exist!(&preimages[18..20], monitor);
5438
5439		// But if we do it again, we'll prune 5-10
5440		let mut htlcs = preimages_slice_to_htlcs!(preimages[0..3]);
5441		let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
5442		monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx,
5443			htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect());
5444		secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
5445		monitor.provide_secret(281474976710652, secret.clone()).unwrap();
5446		assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
5447		test_preimages_exist!(&preimages[0..5], monitor);
5448	}
5449
5450	#[test]
5451	fn test_claim_txn_weight_computation() {
5452		// We test Claim txn weight, knowing that we want expected weigth and
5453		// not actual case to avoid sigs and time-lock delays hell variances.
5454
5455		let secp_ctx = Secp256k1::new();
5456		let privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
5457		let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
5458
5459		use crate::ln::channel_keys::{HtlcKey, HtlcBasepoint};
5460		macro_rules! sign_input {
5461			($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => {
5462				let htlc = HTLCOutputInCommitment {
5463					offered: if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_offered_htlc($opt_anchors) { true } else { false },
5464					amount_msat: 0,
5465					cltv_expiry: 2 << 16,
5466					payment_hash: PaymentHash([1; 32]),
5467					transaction_output_index: Some($idx as u32),
5468				};
5469				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)) };
5470				let sighash = hash_to_message!(&$sighash_parts.p2wsh_signature_hash($idx, &redeem_script, $amount, EcdsaSighashType::All).unwrap()[..]);
5471				let sig = secp_ctx.sign_ecdsa(&sighash, &privkey);
5472				let mut ser_sig = sig.serialize_der().to_vec();
5473				ser_sig.push(EcdsaSighashType::All as u8);
5474				$sum_actual_sigs += ser_sig.len() as u64;
5475				let witness = $sighash_parts.witness_mut($idx).unwrap();
5476				witness.push(ser_sig);
5477				if *$weight == WEIGHT_REVOKED_OUTPUT {
5478					witness.push(vec!(1));
5479				} else if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_revoked_received_htlc($opt_anchors) {
5480					witness.push(pubkey.clone().serialize().to_vec());
5481				} else if *$weight == weight_received_htlc($opt_anchors) {
5482					witness.push(vec![0]);
5483				} else {
5484					witness.push(PaymentPreimage([1; 32]).0.to_vec());
5485				}
5486				witness.push(redeem_script.into_bytes());
5487				let witness = witness.to_vec();
5488				println!("witness[0] {}", witness[0].len());
5489				println!("witness[1] {}", witness[1].len());
5490				println!("witness[2] {}", witness[2].len());
5491			}
5492		}
5493
5494		let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
5495		let txid = Txid::from_str("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
5496
5497		// Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
5498		for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5499			let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5500			let mut sum_actual_sigs = 0;
5501			for i in 0..4 {
5502				claim_tx.input.push(TxIn {
5503					previous_output: BitcoinOutPoint {
5504						txid,
5505						vout: i,
5506					},
5507					script_sig: ScriptBuf::new(),
5508					sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5509					witness: Witness::new(),
5510				});
5511			}
5512			claim_tx.output.push(TxOut {
5513				script_pubkey: script_pubkey.clone(),
5514				value: Amount::ZERO,
5515			});
5516			let base_weight = claim_tx.weight().to_wu();
5517			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)];
5518			let mut inputs_total_weight = 2; // count segwit flags
5519			{
5520				let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5521				for (idx, inp) in inputs_weight.iter().enumerate() {
5522					sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
5523					inputs_total_weight += inp;
5524				}
5525			}
5526			assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + /* max_length_sig */ (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5527		}
5528
5529		// Claim tx with 1 offered HTLCs, 3 received HTLCs
5530		for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5531			let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5532			let mut sum_actual_sigs = 0;
5533			for i in 0..4 {
5534				claim_tx.input.push(TxIn {
5535					previous_output: BitcoinOutPoint {
5536						txid,
5537						vout: i,
5538					},
5539					script_sig: ScriptBuf::new(),
5540					sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5541					witness: Witness::new(),
5542				});
5543			}
5544			claim_tx.output.push(TxOut {
5545				script_pubkey: script_pubkey.clone(),
5546				value: Amount::ZERO,
5547			});
5548			let base_weight = claim_tx.weight().to_wu();
5549			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)];
5550			let mut inputs_total_weight = 2; // count segwit flags
5551			{
5552				let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5553				for (idx, inp) in inputs_weight.iter().enumerate() {
5554					sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
5555					inputs_total_weight += inp;
5556				}
5557			}
5558			assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + /* max_length_sig */ (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5559		}
5560
5561		// Justice tx with 1 revoked HTLC-Success tx output
5562		for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5563			let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5564			let mut sum_actual_sigs = 0;
5565			claim_tx.input.push(TxIn {
5566				previous_output: BitcoinOutPoint {
5567					txid,
5568					vout: 0,
5569				},
5570				script_sig: ScriptBuf::new(),
5571				sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5572				witness: Witness::new(),
5573			});
5574			claim_tx.output.push(TxOut {
5575				script_pubkey: script_pubkey.clone(),
5576				value: Amount::ZERO,
5577			});
5578			let base_weight = claim_tx.weight().to_wu();
5579			let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
5580			let mut inputs_total_weight = 2; // count segwit flags
5581			{
5582				let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5583				for (idx, inp) in inputs_weight.iter().enumerate() {
5584					sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
5585					inputs_total_weight += inp;
5586				}
5587			}
5588			assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + /* max_length_isg */ (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5589		}
5590	}
5591
5592	#[test]
5593	fn test_with_channel_monitor_impl_logger() {
5594		let secp_ctx = Secp256k1::new();
5595		let logger = Arc::new(TestLogger::new());
5596
5597		let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5598
5599		let keys = InMemorySigner::new(
5600			&secp_ctx,
5601			SecretKey::from_slice(&[41; 32]).unwrap(),
5602			SecretKey::from_slice(&[41; 32]).unwrap(),
5603			SecretKey::from_slice(&[41; 32]).unwrap(),
5604			SecretKey::from_slice(&[41; 32]).unwrap(),
5605			SecretKey::from_slice(&[41; 32]).unwrap(),
5606			[41; 32],
5607			0,
5608			[0; 32],
5609			[0; 32],
5610		);
5611
5612		let counterparty_pubkeys = ChannelPublicKeys {
5613			funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
5614			revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())),
5615			payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
5616			delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
5617			htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())),
5618		};
5619		let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::MAX };
5620		let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
5621		let channel_parameters = ChannelTransactionParameters {
5622			holder_pubkeys: keys.holder_channel_pubkeys.clone(),
5623			holder_selected_contest_delay: 66,
5624			is_outbound_from_holder: true,
5625			counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
5626				pubkeys: counterparty_pubkeys,
5627				selected_contest_delay: 67,
5628			}),
5629			funding_outpoint: Some(funding_outpoint),
5630			channel_type_features: ChannelTypeFeatures::only_static_remote_key()
5631		};
5632		let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5633		let best_block = BestBlock::from_network(Network::Testnet);
5634		let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
5635			Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &ScriptBuf::new(),
5636			(OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, ScriptBuf::new()),
5637			&channel_parameters, true, ScriptBuf::new(), 46, 0, HolderCommitmentTransaction::dummy(&mut Vec::new()),
5638			best_block, dummy_key, channel_id);
5639
5640		let chan_id = monitor.inner.lock().unwrap().channel_id();
5641		let payment_hash = PaymentHash([1; 32]);
5642		let context_logger = WithChannelMonitor::from(&logger, &monitor, Some(payment_hash));
5643		log_error!(context_logger, "This is an error");
5644		log_warn!(context_logger, "This is an error");
5645		log_debug!(context_logger, "This is an error");
5646		log_trace!(context_logger, "This is an error");
5647		log_gossip!(context_logger, "This is an error");
5648		log_info!(context_logger, "This is an error");
5649		logger.assert_log_context_contains("lightning::chain::channelmonitor::tests", Some(dummy_key), Some(chan_id), 6);
5650	}
5651	// Further testing is done in the ChannelManager integration tests.
5652}