Skip to main content

lightning/events/
mod.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//! Events are returned from various bits in the library which indicate some action must be taken
11//! by the client.
12//!
13//! Because we don't have a built-in runtime, it's up to the client to call events at a time in the
14//! future, as well as generate and broadcast funding transactions handle payment preimages and a
15//! few other things.
16
17pub mod bump_transaction;
18
19pub use bump_transaction::BumpTransactionEvent;
20
21use crate::blinded_path::message::{BlindedMessagePath, NextMessageHop, OffersContext};
22use crate::blinded_path::payment::{
23	Bolt12OfferContext, Bolt12RefundContext, PaymentContext, PaymentContextRef,
24};
25use crate::chain::transaction;
26use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
27use crate::ln::channelmanager::{InterceptId, PaymentId};
28use crate::ln::funding::FundingContribution;
29use crate::ln::msgs;
30use crate::ln::onion_utils::LocalHTLCFailureReason;
31use crate::ln::outbound_payment::RecipientOnionFields;
32use crate::ln::types::ChannelId;
33use crate::offers::invoice::Bolt12Invoice;
34use crate::offers::invoice_request::InvoiceRequest;
35pub use crate::offers::payer_proof::PaidBolt12Invoice;
36use crate::offers::static_invoice::StaticInvoice;
37use crate::onion_message::messenger::Responder;
38use crate::routing::gossip::NetworkUpdate;
39use crate::routing::router::{BlindedTail, Path, RouteHop, RouteParameters};
40use crate::sign::SpendableOutputDescriptor;
41use crate::types::features::ChannelTypeFeatures;
42use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
43use crate::types::string::UntrustedString;
44use crate::util::errors::APIError;
45use crate::util::ser::{
46	BigSize, FixedLengthReader, Iterable, MaybeReadable, Readable, ReadableArgs, RequiredWrapper,
47	UpgradableRequired, WithoutLength, Writeable, Writer,
48};
49
50use crate::io;
51use crate::sync::Arc;
52use bitcoin::hashes::sha256::Hash as Sha256;
53use bitcoin::hashes::Hash;
54use bitcoin::script::ScriptBuf;
55use bitcoin::secp256k1::PublicKey;
56use bitcoin::{OutPoint, Transaction, TxOut};
57use core::ops::Deref;
58
59#[allow(unused_imports)]
60use crate::prelude::*;
61
62/// `FundingInfo` holds information about a channel's funding transaction.
63///
64/// When LDK is set to manual propagation of the funding transaction
65/// (via [`ChannelManager::unsafe_manual_funding_transaction_generated`),
66/// LDK does not have the full transaction data. Instead, the `OutPoint`
67/// for the funding is provided here.
68///
69/// [`ChannelManager::unsafe_manual_funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::unsafe_manual_funding_transaction_generated
70#[derive(Debug, PartialEq, Eq, Clone)]
71pub enum FundingInfo {
72	/// The full funding `Transaction`.
73	Tx {
74		/// The funding transaction
75		transaction: Transaction,
76	},
77	/// The `OutPoint` of the funding.
78	OutPoint {
79		/// The outpoint of the funding
80		outpoint: transaction::OutPoint,
81	},
82	/// The contributions used for a dual funding or splice funding transaction.
83	Contribution {
84		/// UTXOs spent as inputs contributed to the funding transaction.
85		inputs: Vec<OutPoint>,
86		/// Output scripts contributed to the funding transaction.
87		outputs: Vec<ScriptBuf>,
88	},
89}
90
91impl_writeable_tlv_based_enum!(FundingInfo,
92	(0, Tx) => {
93		(0, transaction, required)
94	},
95	(1, OutPoint) => {
96		(1, outpoint, required)
97	},
98	(2, Contribution) => {
99		(1, inputs, optional_vec),
100		(3, outputs, optional_vec),
101	}
102);
103
104impl FundingInfo {
105	/// Returns a [`FundingInfo::Contribution`] for the given inputs and outputs, or `None` if both
106	/// are empty and there is thus nothing to discard.
107	pub(crate) fn contribution(inputs: Vec<OutPoint>, outputs: Vec<ScriptBuf>) -> Option<Self> {
108		if inputs.is_empty() && outputs.is_empty() {
109			None
110		} else {
111			Some(FundingInfo::Contribution { inputs, outputs })
112		}
113	}
114}
115
116/// The funding contribution from a failed splice negotiation round, see
117/// [`Event::SpliceNegotiationFailed`].
118#[derive(Clone, Debug, PartialEq, Eq)]
119pub struct FailedSpliceContribution {
120	/// UTXOs spent as inputs contributed to the failed round that were released by the failure,
121	/// i.e., excluding any inherited from a splice attempt that remains pending.
122	contributed_inputs: Vec<OutPoint>,
123	/// Outputs contributed to the failed round that were released by the failure.
124	contributed_outputs: Vec<TxOut>,
125	/// The full contribution from the failed round.
126	contribution: FundingContribution,
127}
128
129impl FailedSpliceContribution {
130	pub(crate) fn new(
131		contributed_inputs: Vec<OutPoint>, contributed_outputs: Vec<TxOut>,
132		contribution: FundingContribution,
133	) -> Self {
134		Self { contributed_inputs, contributed_outputs, contribution }
135	}
136
137	/// The funding contribution from the failed negotiation round. This can be fed back to
138	/// [`ChannelManager::funding_contributed`] to retry with the same parameters. Alternatively,
139	/// call [`ChannelManager::splice_channel`] to obtain a fresh [`FundingTemplate`] and build a
140	/// new contribution.
141	///
142	/// The [`Event::DiscardFunding`] for the failure releases the inputs and outputs this
143	/// contribution reserved for itself, [`FundingContribution::reserved_inputs`] and
144	/// [`FundingContribution::reserved_outputs`]. Anything else it holds was inherited from a
145	/// splice attempt that remains pending and stays reserved by that attempt. Before retrying,
146	/// reserve the released ones again, confirming they are still free:
147	/// [`ChannelManager::funding_contributed`] requires everything a contribution holds to be
148	/// reserved for it alone, other than what it inherited. If the channel has since closed,
149	/// retrying is refused and the same inputs and outputs are released again.
150	///
151	/// Check [`NegotiationFailureReason::is_retriable`] before retrying; it is `false` for
152	/// [`NegotiationFailureReason::ChannelClosing`]. If the counterparty had already signed the
153	/// splice transaction when the channel closed, it may still confirm. No
154	/// [`Event::DiscardFunding`] is emitted for it until the closing transaction confirms, and a
155	/// refused retry would release its inputs and outputs before then.
156	///
157	/// [`ChannelManager::funding_contributed`]: crate::ln::channelmanager::ChannelManager::funding_contributed
158	/// [`ChannelManager::splice_channel`]: crate::ln::channelmanager::ChannelManager::splice_channel
159	/// [`FundingTemplate`]: crate::ln::funding::FundingTemplate
160	pub fn contribution(&self) -> &FundingContribution {
161		&self.contribution
162	}
163
164	/// Consumes this, returning the funding contribution from the failed negotiation round, see
165	/// [`Self::contribution`].
166	pub fn into_contribution(self) -> FundingContribution {
167		self.contribution
168	}
169
170	#[cfg(test)]
171	pub(crate) fn contributed_inputs(&self) -> &[OutPoint] {
172		&self.contributed_inputs
173	}
174
175	#[cfg(test)]
176	pub(crate) fn contributed_outputs(&self) -> &[TxOut] {
177		&self.contributed_outputs
178	}
179}
180
181/// The reason a funding negotiation round failed.
182///
183/// Each negotiation attempt (initial or RBF) resolves to either success or failure. This enum
184/// indicates what caused the failure. It is reported through [`Event::SpliceNegotiationFailed`],
185/// or through [`SpliceContributionError::NegotiationFailed`] when
186/// [`ChannelManager::funding_contributed`] refuses the contribution outright. Use
187/// [`is_retriable`] to determine whether the splice can be reattempted on this channel by calling
188/// [`ChannelManager::splice_channel`].
189///
190/// [`is_retriable`]: Self::is_retriable
191/// [`SpliceContributionError::NegotiationFailed`]: crate::ln::channelmanager::SpliceContributionError::NegotiationFailed
192/// [`ChannelManager::funding_contributed`]: crate::ln::channelmanager::ChannelManager::funding_contributed
193/// [`ChannelManager::splice_channel`]: crate::ln::channelmanager::ChannelManager::splice_channel
194#[derive(Clone, Debug, PartialEq, Eq)]
195pub enum NegotiationFailureReason {
196	/// The reason was not available (e.g., from an older serialization).
197	Unknown,
198	/// The peer disconnected during negotiation. Wait for the peer to reconnect, then retry.
199	PeerDisconnected,
200	/// The counterparty explicitly aborted the negotiation by sending `tx_abort`. Retrying with
201	/// the same parameters is unlikely to succeed — consider adjusting the contribution or
202	/// waiting for the counterparty to initiate.
203	CounterpartyAborted {
204		/// The counterparty's abort message.
205		///
206		/// This is counterparty-provided data. Use `Display` on [`UntrustedString`] for safe
207		/// logging.
208		msg: UntrustedString,
209	},
210	/// An error occurred during interactive transaction negotiation (e.g., the counterparty sent
211	/// an invalid message). The negotiation was aborted.
212	NegotiationError {
213		/// A developer-readable error message.
214		msg: String,
215	},
216	/// The funding contribution was invalid (e.g., insufficient balance for the splice amount).
217	/// Call [`ChannelManager::splice_channel`] for a fresh [`FundingTemplate`] and build a new
218	/// contribution with adjusted parameters.
219	///
220	/// [`ChannelManager::splice_channel`]: crate::ln::channelmanager::ChannelManager::splice_channel
221	/// [`FundingTemplate`]: crate::ln::funding::FundingTemplate
222	ContributionInvalid,
223	/// The negotiation was locally canceled via [`ChannelManager::cancel_funding_contributed`].
224	///
225	/// [`ChannelManager::cancel_funding_contributed`]: crate::ln::channelmanager::ChannelManager::cancel_funding_contributed
226	LocallyCanceled,
227	/// The channel is closing, so the negotiation cannot continue. See [`Event::ChannelClosed`]
228	/// for the closure reason.
229	ChannelClosing,
230	/// The contribution's feerate was too low for RBF. Call [`ChannelManager::splice_channel`]
231	/// for a fresh [`FundingTemplate`] (which includes the updated minimum feerate) and build a
232	/// new contribution with a higher feerate.
233	///
234	/// [`ChannelManager::splice_channel`]: crate::ln::channelmanager::ChannelManager::splice_channel
235	/// [`FundingTemplate`]: crate::ln::funding::FundingTemplate
236	FeeRateTooLow,
237	/// An RBF attempt could not be initiated (e.g., a prior splice transaction already
238	/// confirmed). The channel remains operational — start a new splice with
239	/// [`ChannelManager::splice_channel`] if further changes are needed.
240	///
241	/// [`ChannelManager::splice_channel`]: crate::ln::channelmanager::ChannelManager::splice_channel
242	CannotInitiateRbf,
243}
244
245impl NegotiationFailureReason {
246	/// Whether the splice negotiation is likely to succeed if retried on this channel. When `true`,
247	/// call [`ChannelManager::splice_channel`] to obtain a fresh [`FundingTemplate`] and retry.
248	///
249	/// [`ChannelManager::splice_channel`]: crate::ln::channelmanager::ChannelManager::splice_channel
250	/// [`FundingTemplate`]: crate::ln::funding::FundingTemplate
251	pub fn is_retriable(&self) -> bool {
252		match self {
253			Self::Unknown
254			| Self::PeerDisconnected
255			| Self::ContributionInvalid
256			| Self::FeeRateTooLow => true,
257			Self::CounterpartyAborted { .. }
258			| Self::NegotiationError { .. }
259			| Self::LocallyCanceled
260			| Self::ChannelClosing
261			| Self::CannotInitiateRbf => false,
262		}
263	}
264}
265
266impl core::fmt::Display for NegotiationFailureReason {
267	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
268		match self {
269			Self::Unknown => f.write_str("unknown reason"),
270			Self::PeerDisconnected => f.write_str("peer disconnected during negotiation"),
271			Self::CounterpartyAborted { msg } => {
272				write!(f, "counterparty aborted: {}", msg)
273			},
274			Self::NegotiationError { msg } => write!(f, "negotiation error: {}", msg),
275			Self::ContributionInvalid => f.write_str("funding contribution was invalid"),
276			Self::LocallyCanceled => f.write_str("splice locally canceled"),
277
278			Self::ChannelClosing => f.write_str("channel is closing"),
279			Self::FeeRateTooLow => f.write_str("feerate too low for RBF"),
280			Self::CannotInitiateRbf => f.write_str("cannot initiate RBF"),
281		}
282	}
283}
284
285impl_writeable_tlv_based_enum_upgradable!(NegotiationFailureReason,
286	(1, Unknown) => {},
287	(3, PeerDisconnected) => {},
288	(5, CounterpartyAborted) => {
289		(1, msg, required),
290	},
291	(7, NegotiationError) => {
292		(1, msg, required),
293	},
294	(9, ContributionInvalid) => {},
295	(11, LocallyCanceled) => {},
296	(13, ChannelClosing) => {},
297	(15, FeeRateTooLow) => {},
298	(17, CannotInitiateRbf) => {},
299);
300
301/// Some information provided on receipt of payment depends on whether the payment received is a
302/// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
303#[derive(Clone, Debug, PartialEq, Eq)]
304pub enum PaymentPurpose {
305	/// A payment for a BOLT 11 invoice.
306	Bolt11InvoicePayment {
307		/// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
308		/// [`ChannelManager::create_inbound_payment`]. When handling [`Event::PaymentClaimable`],
309		/// this can be passed directly to [`ChannelManager::claim_funds`] to claim the payment. No
310		/// action is needed when seen in [`Event::PaymentClaimed`].
311		///
312		/// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
313		/// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
314		payment_preimage: Option<PaymentPreimage>,
315		/// The "payment secret". This authenticates the sender to the recipient, preventing a
316		/// number of deanonymization attacks during the routing process.
317		/// It is provided here for your reference, however its accuracy is enforced directly by
318		/// [`ChannelManager`] using the values you previously provided to
319		/// [`ChannelManager::create_inbound_payment`] or
320		/// [`ChannelManager::create_inbound_payment_for_hash`].
321		///
322		/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
323		/// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
324		/// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
325		payment_secret: PaymentSecret,
326	},
327	/// A payment for a BOLT 12 [`Offer`].
328	///
329	/// [`Offer`]: crate::offers::offer::Offer
330	Bolt12OfferPayment {
331		/// The preimage to the payment hash. When handling [`Event::PaymentClaimable`], this can be
332		/// passed directly to [`ChannelManager::claim_funds`], if provided. No action is needed
333		/// when seen in [`Event::PaymentClaimed`].
334		///
335		/// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
336		payment_preimage: Option<PaymentPreimage>,
337		/// The secret used to authenticate the sender to the recipient, preventing a number of
338		/// de-anonymization attacks while routing a payment.
339		///
340		/// See [`PaymentPurpose::Bolt11InvoicePayment::payment_secret`] for further details.
341		payment_secret: PaymentSecret,
342		/// The context of the payment such as information about the corresponding [`Offer`] and
343		/// [`InvoiceRequest`].
344		///
345		/// This includes the Human Readable Name which the sender indicated they were paying to,
346		/// for possible recipient disambiguation if you're using a single wildcard DNS entry to
347		/// resolve to many recipients.
348		///
349		/// [`Offer`]: crate::offers::offer::Offer
350		/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
351		payment_context: Bolt12OfferContext,
352	},
353	/// A payment for a BOLT 12 [`Refund`].
354	///
355	/// [`Refund`]: crate::offers::refund::Refund
356	Bolt12RefundPayment {
357		/// The preimage to the payment hash. When handling [`Event::PaymentClaimable`], this can be
358		/// passed directly to [`ChannelManager::claim_funds`], if provided. No action is needed
359		/// when seen in [`Event::PaymentClaimed`].
360		///
361		/// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
362		payment_preimage: Option<PaymentPreimage>,
363		/// The secret used to authenticate the sender to the recipient, preventing a number of
364		/// de-anonymization attacks while routing a payment.
365		///
366		/// See [`PaymentPurpose::Bolt11InvoicePayment::payment_secret`] for further details.
367		payment_secret: PaymentSecret,
368		/// The context of the payment such as information about the corresponding [`Refund`].
369		///
370		/// [`Refund`]: crate::offers::refund::Refund
371		payment_context: Bolt12RefundContext,
372	},
373	/// Because this is a spontaneous payment, the payer generated their own preimage rather than us
374	/// (the payee) providing a preimage.
375	SpontaneousPayment(PaymentPreimage),
376}
377
378impl PaymentPurpose {
379	/// Returns the preimage for this payment, if it is known.
380	pub fn preimage(&self) -> Option<PaymentPreimage> {
381		match self {
382			PaymentPurpose::Bolt11InvoicePayment { payment_preimage, .. } => *payment_preimage,
383			PaymentPurpose::Bolt12OfferPayment { payment_preimage, .. } => *payment_preimage,
384			PaymentPurpose::Bolt12RefundPayment { payment_preimage, .. } => *payment_preimage,
385			PaymentPurpose::SpontaneousPayment(preimage) => Some(*preimage),
386		}
387	}
388
389	pub(crate) fn is_keysend(&self) -> bool {
390		match self {
391			PaymentPurpose::Bolt11InvoicePayment { .. } => false,
392			PaymentPurpose::Bolt12OfferPayment { .. } => false,
393			PaymentPurpose::Bolt12RefundPayment { .. } => false,
394			PaymentPurpose::SpontaneousPayment(..) => true,
395		}
396	}
397
398	/// Errors when provided an `AsyncBolt12OfferContext`, see below.
399	pub(crate) fn from_parts(
400		payment_preimage: Option<PaymentPreimage>, payment_secret: PaymentSecret,
401		payment_context: Option<PaymentContext>,
402	) -> Result<Self, ()> {
403		match payment_context {
404			None => Ok(PaymentPurpose::Bolt11InvoicePayment { payment_preimage, payment_secret }),
405			Some(PaymentContext::Bolt12Offer(context)) => Ok(PaymentPurpose::Bolt12OfferPayment {
406				payment_preimage,
407				payment_secret,
408				payment_context: context,
409			}),
410			Some(PaymentContext::Bolt12Refund(context)) => {
411				Ok(PaymentPurpose::Bolt12RefundPayment {
412					payment_preimage,
413					payment_secret,
414					payment_context: context,
415				})
416			},
417			Some(PaymentContext::AsyncBolt12Offer(_)) => {
418				// Callers are expected to convert from `AsyncBolt12OfferContext` to `Bolt12OfferContext`
419				// using the invoice request provided in the payment onion prior to calling this method.
420				debug_assert!(false);
421				Err(())
422			},
423		}
424	}
425}
426
427impl_writeable_tlv_based_enum_legacy!(PaymentPurpose,
428	(0, Bolt11InvoicePayment) => {
429		(0, payment_preimage, option),
430		(2, payment_secret, required),
431	},
432	(4, Bolt12OfferPayment) => {
433		(0, payment_preimage, option),
434		(2, payment_secret, required),
435		(4, payment_context, required),
436	},
437	(6, Bolt12RefundPayment) => {
438		(0, payment_preimage, option),
439		(2, payment_secret, required),
440		(4, payment_context, required),
441	},
442	;
443	(2, SpontaneousPayment)
444);
445
446/// Information about an HTLC that is part of a payment that can be claimed.
447#[derive(Clone, Debug, PartialEq, Eq)]
448pub struct ClaimedHTLC {
449	/// The counterparty of the channel.
450	///
451	/// This value will always be `None` for objects serialized with LDK versions prior to 0.2 and
452	/// `Some` otherwise.
453	pub counterparty_node_id: Option<PublicKey>,
454	/// The `channel_id` of the channel over which the HTLC was received.
455	pub channel_id: ChannelId,
456	/// The `user_channel_id` of the channel over which the HTLC was received. This is the value
457	/// passed in to [`ChannelManager::create_channel`] for outbound channels, or to
458	/// [`ChannelManager::accept_inbound_channel`] for inbound channels.
459	///
460	/// This field will be zero for a payment that was serialized prior to LDK version 0.0.117. (This
461	/// should only happen in the case that a payment was claimable prior to LDK version 0.0.117, but
462	/// was not actually claimed until after upgrading.)
463	///
464	/// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
465	/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
466	pub user_channel_id: u128,
467	/// The block height at which this HTLC expires.
468	pub cltv_expiry: u32,
469	/// The amount (in msats) of this part of an MPP.
470	pub value_msat: u64,
471	/// The extra fee our counterparty skimmed off the top of this HTLC, if any.
472	///
473	/// This value will always be 0 for [`ClaimedHTLC`]s serialized with LDK versions prior to
474	/// 0.0.119.
475	pub counterparty_skimmed_fee_msat: u64,
476}
477impl_writeable_tlv_based!(ClaimedHTLC, {
478	(0, channel_id, required),
479	(1, counterparty_skimmed_fee_msat, (default_value, 0u64)),
480	(2, user_channel_id, required),
481	(3, counterparty_node_id, option),
482	(4, cltv_expiry, required),
483	(6, value_msat, required),
484});
485
486/// When the payment path failure took place and extra details about it. [`PathFailure::OnPath`] may
487/// contain a [`NetworkUpdate`] that needs to be applied to the [`NetworkGraph`].
488///
489/// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
490/// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
491#[derive(Clone, Debug, Eq, PartialEq)]
492pub enum PathFailure {
493	/// We failed to initially send the payment and no HTLC was committed to. Contains the relevant
494	/// error.
495	InitialSend {
496		/// The error surfaced from initial send.
497		err: APIError,
498	},
499	/// A hop on the path failed to forward our payment.
500	OnPath {
501		/// If present, this [`NetworkUpdate`] should be applied to the [`NetworkGraph`] so that routing
502		/// decisions can take into account the update.
503		///
504		/// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
505		/// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
506		network_update: Option<NetworkUpdate>,
507	},
508}
509
510impl_writeable_tlv_based_enum_upgradable!(PathFailure,
511	(0, OnPath) => {
512		(0, network_update, upgradable_option),
513	},
514	(2, InitialSend) => {
515		(0, err, upgradable_required),
516	},
517);
518
519#[derive(Clone, Debug, PartialEq, Eq)]
520/// The reason the channel was closed. See individual variants for more details.
521pub enum ClosureReason {
522	/// Closure generated from receiving a peer error message.
523	///
524	/// Our counterparty may have broadcasted their latest commitment state, and we have
525	/// as well.
526	CounterpartyForceClosed {
527		/// The error which the peer sent us.
528		///
529		/// Be careful about printing the peer_msg, a well-crafted message could exploit
530		/// a security vulnerability in the terminal emulator or the logging subsystem.
531		/// To be safe, use `Display` on `UntrustedString`
532		///
533		/// [`UntrustedString`]: crate::types::string::UntrustedString
534		peer_msg: UntrustedString,
535	},
536	/// Closure generated from [`ChannelManager::force_close_broadcasting_latest_txn`] or
537	/// [`ChannelManager::force_close_all_channels_broadcasting_latest_txn`], called by the user.
538	///
539	/// [`ChannelManager::force_close_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_broadcasting_latest_txn
540	/// [`ChannelManager::force_close_all_channels_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_all_channels_broadcasting_latest_txn
541	HolderForceClosed {
542		/// Whether or not the latest transaction was broadcasted when the channel was force
543		/// closed.
544		///
545		/// This will be set to `Some(true)` for any channels closed after their funding
546		/// transaction was (or might have been) broadcasted, and `Some(false)` for any channels
547		/// closed prior to their funding transaction being broadcasted.
548		///
549		/// This will be `None` for objects generated or written by LDK 0.0.123 and
550		/// earlier.
551		broadcasted_latest_txn: Option<bool>,
552		/// The error message provided to [`ChannelManager::force_close_broadcasting_latest_txn`] or
553		/// [`ChannelManager::force_close_all_channels_broadcasting_latest_txn`].
554		///
555		/// This will be the empty string for objects generated or written by LDK 0.1 and earlier.
556		///
557		/// [`ChannelManager::force_close_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_broadcasting_latest_txn
558		/// [`ChannelManager::force_close_all_channels_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_all_channels_broadcasting_latest_txn
559		message: String,
560	},
561	/// The channel was closed after negotiating a cooperative close and we've now broadcasted
562	/// the cooperative close transaction. Note the shutdown may have been initiated by us.
563	///
564	/// This was only set in versions of LDK prior to 0.0.122.
565	// Can be removed once we disallow downgrading to 0.0.121
566	LegacyCooperativeClosure,
567	/// The channel was closed after negotiating a cooperative close and we've now broadcasted
568	/// the cooperative close transaction. This indicates that the shutdown was initiated by our
569	/// counterparty.
570	///
571	/// In rare cases where we initiated closure immediately prior to shutting down without
572	/// persisting, this value may be provided for channels we initiated closure for.
573	CounterpartyInitiatedCooperativeClosure,
574	/// The channel was closed after negotiating a cooperative close and we've now broadcasted
575	/// the cooperative close transaction. This indicates that the shutdown was initiated by us.
576	LocallyInitiatedCooperativeClosure,
577	/// A commitment transaction was confirmed on chain, closing the channel. Most likely this
578	/// commitment transaction came from our counterparty, but it may also have come from
579	/// a copy of our own `ChannelMonitor`.
580	CommitmentTxConfirmed,
581	/// The funding transaction failed to confirm in a timely manner on an inbound channel or the
582	/// counterparty failed to fund the channel in a timely manner.
583	FundingTimedOut,
584	/// Closure generated from processing an event, likely a HTLC forward/relay/reception.
585	ProcessingError {
586		/// A developer-readable error message which we generated.
587		err: String,
588	},
589	/// The peer disconnected prior to funding completing. In this case the spec mandates that we
590	/// forget the channel entirely - we can attempt again if the peer reconnects.
591	///
592	/// This includes cases where we restarted prior to funding completion, including prior to the
593	/// initial [`ChannelMonitor`] persistence completing.
594	///
595	/// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
596	/// peer because of mutual incompatibility between us and our channel counterparty.
597	///
598	/// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
599	DisconnectedPeer,
600	/// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
601	/// the [`ChannelManager`] deserialized.
602	///
603	/// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
604	/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
605	OutdatedChannelManager,
606	/// The counterparty requested a cooperative close of a channel that had not been funded yet.
607	/// The channel has been immediately closed.
608	CounterpartyCoopClosedUnfundedChannel,
609	/// We requested a cooperative close of a channel that had not been funded yet.
610	/// The channel has been immediately closed.
611	///
612	/// Note that events containing this variant will be lost on downgrade to a version of LDK
613	/// prior to 0.2.
614	LocallyCoopClosedUnfundedChannel,
615	/// Another channel in the same funding batch closed before the funding transaction
616	/// was ready to be broadcast.
617	FundingBatchClosure,
618	/// One of our HTLCs timed out in a channel, causing us to force close the channel.
619	HTLCsTimedOut {
620		/// The payment hash of an HTLC that timed out.
621		///
622		/// Will be `None` for any event serialized by LDK prior to 0.2.
623		payment_hash: Option<PaymentHash>,
624	},
625	/// Our peer provided a feerate which violated our required minimum (fetched from our
626	/// [`FeeEstimator`] either as [`ConfirmationTarget::MinAllowedAnchorChannelRemoteFee`] or
627	/// [`ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee`]).
628	///
629	/// [`FeeEstimator`]: crate::chain::chaininterface::FeeEstimator
630	/// [`ConfirmationTarget::MinAllowedAnchorChannelRemoteFee`]: crate::chain::chaininterface::ConfirmationTarget::MinAllowedAnchorChannelRemoteFee
631	/// [`ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee`]: crate::chain::chaininterface::ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee
632	PeerFeerateTooLow {
633		/// The feerate on our channel set by our peer.
634		peer_feerate_sat_per_kw: u32,
635		/// The required feerate we enforce, from our [`FeeEstimator`].
636		///
637		/// [`FeeEstimator`]: crate::chain::chaininterface::FeeEstimator
638		required_feerate_sat_per_kw: u32,
639	},
640}
641
642impl core::fmt::Display for ClosureReason {
643	fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
644		f.write_str("Channel closed because ")?;
645		match self {
646			ClosureReason::CounterpartyForceClosed { peer_msg } => {
647				f.write_fmt(format_args!("counterparty force-closed with message: {}", peer_msg))
648			},
649			ClosureReason::HolderForceClosed { broadcasted_latest_txn, message } => {
650				f.write_str("user force-closed the channel with the message \"")?;
651				f.write_str(message)?;
652				if let Some(brodcasted) = broadcasted_latest_txn {
653					write!(
654						f,
655						"\" and {} the latest transaction",
656						if *brodcasted { "broadcasted" } else { "elected not to broadcast" }
657					)
658				} else {
659					Ok(())
660				}
661			},
662			ClosureReason::LegacyCooperativeClosure => {
663				f.write_str("the channel was cooperatively closed")
664			},
665			ClosureReason::CounterpartyInitiatedCooperativeClosure => {
666				f.write_str("the channel was cooperatively closed by our peer")
667			},
668			ClosureReason::LocallyInitiatedCooperativeClosure => {
669				f.write_str("the channel was cooperatively closed by us")
670			},
671			ClosureReason::CommitmentTxConfirmed => {
672				f.write_str("commitment or closing transaction was confirmed on chain.")
673			},
674			ClosureReason::FundingTimedOut => write!(
675				f,
676				"funding transaction failed to confirm within {} blocks",
677				FUNDING_CONF_DEADLINE_BLOCKS
678			),
679			ClosureReason::ProcessingError { err } => {
680				f.write_str("of an exception: ")?;
681				f.write_str(&err)
682			},
683			ClosureReason::DisconnectedPeer => {
684				f.write_str("the peer disconnected prior to the channel being funded")
685			},
686			ClosureReason::OutdatedChannelManager => f.write_str(
687				"the ChannelManager read from disk was stale compared to ChannelMonitor(s)",
688			),
689			ClosureReason::CounterpartyCoopClosedUnfundedChannel => {
690				f.write_str("the peer requested the unfunded channel be closed")
691			},
692			ClosureReason::LocallyCoopClosedUnfundedChannel => {
693				f.write_str("we requested the unfunded channel be closed")
694			},
695			ClosureReason::FundingBatchClosure => {
696				f.write_str("another channel in the same funding batch closed")
697			},
698			ClosureReason::HTLCsTimedOut { payment_hash: Some(hash) } => f.write_fmt(format_args!(
699				"HTLC(s) on the channel timed out (including the HTLC with payment hash {hash})",
700			)),
701			ClosureReason::HTLCsTimedOut { payment_hash: None } => {
702				f.write_fmt(format_args!("HTLC(s) on the channel timed out"))
703			},
704			ClosureReason::PeerFeerateTooLow {
705				peer_feerate_sat_per_kw,
706				required_feerate_sat_per_kw,
707			} => f.write_fmt(format_args!(
708				"peer provided a feerate ({} sat/kw) which was below our lower bound ({} sat/kw)",
709				peer_feerate_sat_per_kw, required_feerate_sat_per_kw,
710			)),
711		}
712	}
713}
714
715impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
716	(0, CounterpartyForceClosed) => { (1, peer_msg, required) },
717	(1, FundingTimedOut) => {},
718	(2, HolderForceClosed) => {
719		(1, broadcasted_latest_txn, option),
720		(3, message, (default_value, String::new())),
721	},
722	(6, CommitmentTxConfirmed) => {},
723	(4, LegacyCooperativeClosure) => {},
724	(8, ProcessingError) => { (1, err, required) },
725	(10, DisconnectedPeer) => {},
726	(12, OutdatedChannelManager) => {},
727	(13, CounterpartyCoopClosedUnfundedChannel) => {},
728	(15, FundingBatchClosure) => {},
729	(17, CounterpartyInitiatedCooperativeClosure) => {},
730	(19, LocallyInitiatedCooperativeClosure) => {},
731	(21, HTLCsTimedOut) => {
732		(1, payment_hash, option),
733	},
734	(23, PeerFeerateTooLow) => {
735		(0, peer_feerate_sat_per_kw, required),
736		(2, required_feerate_sat_per_kw, required),
737	},
738	(25, LocallyCoopClosedUnfundedChannel) => {},
739);
740
741/// The type of HTLC handling performed in [`Event::HTLCHandlingFailed`].
742#[derive(Clone, Debug, PartialEq, Eq)]
743pub enum HTLCHandlingFailureType {
744	/// We tried forwarding to a channel but failed to do so. An example of such an instance is when
745	/// there is insufficient capacity in our outbound channel.
746	Forward {
747		/// The `node_id` of the next node. For backwards compatibility, this field is
748		/// marked as optional, versions prior to 0.0.110 may not always be able to provide
749		/// counterparty node information.
750		node_id: Option<PublicKey>,
751		/// The outgoing `channel_id` between us and the next node.
752		channel_id: ChannelId,
753	},
754	/// Scenario where we are unsure of the next node to forward the HTLC to.
755	///
756	/// Deprecated: will only be used in versions before LDK v0.2.0. Downgrades will result in
757	/// this type being represented as [`Self::InvalidForward`].
758	UnknownNextHop {
759		/// Short channel id we are requesting to forward an HTLC to.
760		requested_forward_scid: u64,
761	},
762	/// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
763	/// intercept HTLC.
764	///
765	/// In LDK v0.2.0 and greater, this variant replaces [`Self::UnknownNextHop`].
766	InvalidForward {
767		/// Short channel id we are requesting to forward an HTLC to.
768		requested_forward_scid: u64,
769	},
770	/// We couldn't decode the incoming onion to obtain the forwarding details.
771	InvalidOnion,
772	/// Failure scenario where an HTLC may have been forwarded to be intended for us,
773	/// but is invalid for some reason, so we reject it.
774	///
775	/// Some of the reasons may include:
776	/// * HTLC Timeouts
777	/// * Excess HTLCs for a payment that we have already fully received, over-paying for the
778	///   payment,
779	/// * The counterparty node modified the HTLC in transit,
780	/// * A probing attack where an intermediary node is trying to detect if we are the ultimate
781	///   recipient for a payment.
782	Receive {
783		/// The payment hash of the payment we attempted to process.
784		payment_hash: PaymentHash,
785	},
786	/// We were responsible for pathfinding and forwarding of a trampoline payment, but failed to
787	/// do so. An example of such an instance is when we can't find a route to the specified
788	/// trampoline destination.
789	TrampolineForward {},
790}
791
792impl_writeable_tlv_based_enum_upgradable!(HTLCHandlingFailureType,
793	(0, Forward) => {
794		(0, node_id, required),
795		(2, channel_id, required),
796	},
797	(1, InvalidForward) => {
798		(0, requested_forward_scid, required),
799	},
800	(2, UnknownNextHop) => {
801		(0, requested_forward_scid, required),
802	},
803	(3, InvalidOnion) => {},
804	(4, Receive) => {
805		(0, payment_hash, required),
806	},
807	(5, TrampolineForward) => {},
808);
809
810/// The reason for HTLC failures in [`Event::HTLCHandlingFailed`].
811#[derive(Clone, Debug, PartialEq, Eq)]
812pub enum HTLCHandlingFailureReason {
813	/// The forwarded HTLC was failed back by the downstream node with an encrypted error reason.
814	Downstream,
815	/// The HTLC was failed locally by our node.
816	Local {
817		/// The reason that our node chose to fail the HTLC.
818		reason: LocalHTLCFailureReason,
819	},
820}
821
822impl_writeable_tlv_based_enum!(HTLCHandlingFailureReason,
823	(1, Downstream) => {},
824	(3, Local) => {
825		(0, reason, required),
826	},
827);
828
829impl From<LocalHTLCFailureReason> for HTLCHandlingFailureReason {
830	fn from(value: LocalHTLCFailureReason) -> Self {
831		HTLCHandlingFailureReason::Local { reason: value }
832	}
833}
834
835/// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
836/// Currently only used in serialization for the sake of maintaining compatibility. More variants
837/// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
838/// intercepts in upcoming work.
839enum InterceptNextHop {
840	FakeScid { requested_next_hop_scid: u64 },
841}
842
843impl_writeable_tlv_based_enum!(InterceptNextHop,
844	(0, FakeScid) => {
845		(0, requested_next_hop_scid, required),
846	},
847);
848
849/// The reason the payment failed. Used in [`Event::PaymentFailed`].
850#[derive(Clone, Copy, Debug, PartialEq, Eq)]
851pub enum PaymentFailureReason {
852	/// The intended recipient rejected our payment.
853	///
854	/// Also used for [`UnknownRequiredFeatures`] and [`InvoiceRequestRejected`] when downgrading to
855	/// version prior to 0.0.124.
856	///
857	/// [`UnknownRequiredFeatures`]: Self::UnknownRequiredFeatures
858	/// [`InvoiceRequestRejected`]: Self::InvoiceRequestRejected
859	RecipientRejected,
860	/// The user chose to abandon this payment by calling [`ChannelManager::abandon_payment`].
861	///
862	/// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
863	UserAbandoned,
864	#[cfg_attr(
865		feature = "std",
866		doc = "We exhausted all of our retry attempts while trying to send the payment, or we"
867	)]
868	#[cfg_attr(feature = "std", doc = "exhausted the [`Retry::Timeout`] if the user set one.")]
869	#[cfg_attr(
870		not(feature = "std"),
871		doc = "We exhausted all of our retry attempts while trying to send the payment."
872	)]
873	/// If at any point a retry attempt failed while being forwarded along the path, an [`Event::PaymentPathFailed`] will
874	/// have come before this.
875	#[cfg_attr(feature = "std", doc = "")]
876	#[cfg_attr(
877		feature = "std",
878		doc = "[`Retry::Timeout`]: crate::ln::outbound_payment::Retry::Timeout"
879	)]
880	RetriesExhausted,
881	/// Either the BOLT 12 invoice was expired by the time we received it or the payment expired while
882	/// retrying based on the provided [`PaymentParameters::expiry_time`].
883	///
884	/// Also used for [`InvoiceRequestExpired`] when downgrading to version prior to 0.0.124.
885	///
886	/// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
887	/// [`InvoiceRequestExpired`]: Self::InvoiceRequestExpired
888	PaymentExpired,
889	/// We failed to find a route while sending or retrying the payment.
890	///
891	/// Note that this generally indicates that we've exhausted the available set of possible
892	/// routes - we tried the payment over a few routes but were not able to find any further
893	/// candidate routes beyond those.
894	///
895	/// Also used for [`BlindedPathCreationFailed`] when downgrading to versions prior to 0.0.124.
896	///
897	/// [`BlindedPathCreationFailed`]: Self::BlindedPathCreationFailed
898	RouteNotFound,
899	/// This error should generally never happen. This likely means that there is a problem with
900	/// your router.
901	UnexpectedError,
902	/// An invoice was received that required unknown features.
903	UnknownRequiredFeatures,
904	/// A [`Bolt12Invoice`] was not received in a reasonable amount of time.
905	InvoiceRequestExpired,
906	/// An [`InvoiceRequest`] for the payment was rejected by the recipient.
907	///
908	/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
909	InvoiceRequestRejected,
910	/// Failed to create a blinded path back to ourselves.
911	/// We attempted to initiate payment to a static invoice but failed to create a reply path for our
912	/// [`HeldHtlcAvailable`] message.
913	///
914	/// [`HeldHtlcAvailable`]: crate::onion_message::async_payments::HeldHtlcAvailable
915	BlindedPathCreationFailed,
916}
917
918impl_writeable_tlv_based_enum_upgradable!(PaymentFailureReason,
919	(0, RecipientRejected) => {},
920	(1, UnknownRequiredFeatures) => {},
921	(2, UserAbandoned) => {},
922	(3, InvoiceRequestExpired) => {},
923	(4, RetriesExhausted) => {},
924	(5, InvoiceRequestRejected) => {},
925	(6, PaymentExpired) => {},
926	(7, BlindedPathCreationFailed) => {},
927	(8, RouteNotFound) => {},
928	(10, UnexpectedError) => {},
929);
930
931/// Used to indicate the kind of funding for this channel by the channel acceptor (us).
932///
933/// Allows the differentiation between a request for a dual-funded and non-dual-funded channel.
934#[derive(Clone, Debug, PartialEq, Eq)]
935pub enum InboundChannelFunds {
936	/// For a non-dual-funded channel, the `push_msat` value from the channel initiator to us.
937	PushMsat(u64),
938	/// Indicates the open request is for a dual funded channel.
939	///
940	/// Note that these channels do not support starting with initial funds pushed from the counterparty,
941	/// who is the channel opener in this case.
942	DualFunded,
943}
944
945/// Identifies the channel and specific HTLC for the inbound edge of a forwarded payment.
946#[derive(Clone, Debug, PartialEq, Eq)]
947pub struct InboundHTLCLocator {
948	/// The channel that the HTLC was received on.
949	pub channel_id: ChannelId,
950
951	/// The HTLC ID within the channel `channel_id`.
952	///
953	/// This is only `None` for events serialized by versions prior to 0.3.
954	pub htlc_id: Option<u64>,
955
956	/// The amount, in milli-satoshis, of the HTLC that was received, if known.
957	pub amount_msat: Option<u64>,
958
959	/// The `user_channel_id` for `channel_id`.
960	///
961	/// This will be `None` if the payment was settled via an on-chain transaction. It will also
962	/// be `None` for events serialized by versions prior to 0.0.122.
963	pub user_channel_id: Option<u128>,
964
965	/// The public key identity of the node that the HTLC was received from.
966	///
967	/// This is only `None` for HTLCs received prior to 0.1 or for events serialized by versions
968	/// prior to 0.1.
969	pub node_id: Option<PublicKey>,
970}
971
972impl_writeable_tlv_based!(InboundHTLCLocator, {
973	(1, channel_id, required),
974	(3, user_channel_id, option),
975	(5, node_id, option),
976	(7, amount_msat, option),
977	(9, htlc_id, option),
978});
979
980/// Identifies the channel and HTLC for the outbound edge of a forwarded payment.
981#[derive(Clone, Debug, PartialEq, Eq)]
982pub struct OutboundHTLCLocator {
983	/// The channel that the HTLC was sent on.
984	pub channel_id: ChannelId,
985
986	/// The amount, in milli-satoshis, of the HTLC that was sent, if known.
987	pub amount_msat: Option<u64>,
988
989	/// The `user_channel_id` for `channel_id`.
990	///
991	/// This will be `None` if the payment was settled via an on-chain transaction. It will also
992	/// be `None` for events serialized by versions prior to 0.0.122.
993	pub user_channel_id: Option<u128>,
994
995	/// The public key identity of the node that the HTLC was sent to.
996	///
997	/// This is only `None` for events serialized by versions prior to 0.1.
998	pub node_id: Option<PublicKey>,
999}
1000
1001impl_writeable_tlv_based!(OutboundHTLCLocator, {
1002	(1, channel_id, required),
1003	(3, user_channel_id, option),
1004	(5, node_id, option),
1005	(7, amount_msat, option),
1006});
1007
1008/// An Event which you should probably take some action in response to.
1009///
1010/// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
1011/// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
1012/// written as it makes no sense to respond to it after reconnecting to peers).
1013#[derive(Clone, Debug, PartialEq, Eq)]
1014pub enum Event {
1015	/// Used to indicate that the client should generate a funding transaction with the given
1016	/// parameters and then call [`ChannelManager::funding_transaction_generated`].
1017	/// Generated in [`ChannelManager`] message handling.
1018	/// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
1019	/// counterparty can steal your funds!
1020	///
1021	/// # Failure Behavior and Persistence
1022	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1023	/// returning `Err(ReplayEvent ())`), but won't be persisted across restarts.
1024	///
1025	/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1026	/// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
1027	FundingGenerationReady {
1028		/// The random channel_id we picked which you'll need to pass into
1029		/// [`ChannelManager::funding_transaction_generated`].
1030		///
1031		/// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
1032		temporary_channel_id: ChannelId,
1033		/// The counterparty's node_id, which you'll need to pass back into
1034		/// [`ChannelManager::funding_transaction_generated`].
1035		///
1036		/// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
1037		counterparty_node_id: PublicKey,
1038		/// The value, in satoshis, that the output should have.
1039		channel_value_satoshis: u64,
1040		/// The script which should be used in the transaction output.
1041		output_script: ScriptBuf,
1042		/// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1043		/// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels.
1044		///  This may be zero for objects serialized with LDK versions prior to 0.0.113.
1045		///
1046		/// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1047		/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1048		user_channel_id: u128,
1049	},
1050	/// Used to indicate that the counterparty node has provided the signature(s) required to
1051	/// recover our funds in case they go offline.
1052	///
1053	/// It is safe (and your responsibility) to broadcast the funding transaction upon receiving this
1054	/// event.
1055	///
1056	/// This event is only emitted if you called
1057	/// [`ChannelManager::unsafe_manual_funding_transaction_generated`] instead of
1058	/// [`ChannelManager::funding_transaction_generated`].
1059	///
1060	/// [`ChannelManager::unsafe_manual_funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::unsafe_manual_funding_transaction_generated
1061	/// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
1062	FundingTxBroadcastSafe {
1063		/// The `channel_id` indicating which channel has reached this stage.
1064		channel_id: ChannelId,
1065		/// The `user_channel_id` value passed in to [`ChannelManager::create_channel`].
1066		///
1067		/// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1068		user_channel_id: u128,
1069		/// The outpoint of the channel's funding transaction.
1070		funding_txo: OutPoint,
1071		/// The `node_id` of the channel counterparty.
1072		counterparty_node_id: PublicKey,
1073		/// The `temporary_channel_id` this channel used to be known by during channel establishment.
1074		former_temporary_channel_id: ChannelId,
1075	},
1076	/// Indicates that we've been offered a payment and it needs to be claimed via calling
1077	/// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
1078	///
1079	/// Note that if the preimage is not known, you should call
1080	/// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
1081	/// to free up resources for this HTLC and avoid network congestion.
1082	///
1083	/// If [`Event::PaymentClaimable::onion_fields`] is `Some`, and includes custom TLVs with even type
1084	/// numbers, you should use [`ChannelManager::fail_htlc_backwards_with_reason`] with
1085	/// [`FailureCode::InvalidOnionPayload`] if you fail to understand and handle the contents, or
1086	/// [`ChannelManager::claim_funds_with_known_custom_tlvs`] upon successful handling.
1087	/// If you don't intend to check for custom TLVs, you can simply use
1088	/// [`ChannelManager::claim_funds`], which will automatically fail back even custom TLVs.
1089	///
1090	/// If you fail to call [`ChannelManager::claim_funds`],
1091	/// [`ChannelManager::claim_funds_with_known_custom_tlvs`],
1092	/// [`ChannelManager::fail_htlc_backwards`], or
1093	/// [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will
1094	/// be automatically failed.
1095	///
1096	/// # Note
1097	/// LDK will not stop an inbound payment from being paid multiple times, so multiple
1098	/// `PaymentClaimable` events may be generated for the same payment. In such a case it is
1099	/// polite (and required in the lightning specification) to fail the payment the second time
1100	/// and give the sender their money back rather than accepting double payment.
1101	///
1102	/// # Note
1103	/// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
1104	///
1105	/// # Failure Behavior and Persistence
1106	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1107	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1108	///
1109	/// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
1110	/// [`ChannelManager::claim_funds_with_known_custom_tlvs`]: crate::ln::channelmanager::ChannelManager::claim_funds_with_known_custom_tlvs
1111	/// [`FailureCode::InvalidOnionPayload`]: crate::ln::channelmanager::FailureCode::InvalidOnionPayload
1112	/// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
1113	/// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
1114	PaymentClaimable {
1115		/// The node that will receive the payment after it has been claimed.
1116		/// This is useful to identify payments received via [phantom nodes].
1117		/// This field will always be filled in when the event was generated by LDK versions
1118		/// 0.0.113 and above.
1119		///
1120		/// [phantom nodes]: crate::sign::PhantomKeysManager
1121		receiver_node_id: Option<PublicKey>,
1122		/// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
1123		/// not stop you from registering duplicate payment hashes for inbound payments.
1124		payment_hash: PaymentHash,
1125		/// The fields in the onion which were received with each HTLC. Only fields which were
1126		/// identical in each HTLC involved in the payment will be included here.
1127		///
1128		/// Payments received on LDK versions prior to 0.0.115 will have this field unset.
1129		onion_fields: Option<RecipientOnionFields>,
1130		/// The value, in thousandths of a satoshi, that this payment is claimable for. May be greater
1131		/// than the invoice amount.
1132		///
1133		/// May be less than the invoice amount if [`ChannelConfig::accept_underpaying_htlcs`] is set
1134		/// and the previous hop took an extra fee.
1135		///
1136		/// # Note
1137		/// If [`ChannelConfig::accept_underpaying_htlcs`] is set and you claim without verifying this
1138		/// field, you may lose money!
1139		///
1140		/// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
1141		amount_msat: u64,
1142		/// The value, in thousands of a satoshi, that was skimmed off of this payment as an extra fee
1143		/// taken by our channel counterparty.
1144		///
1145		/// Will always be 0 unless [`ChannelConfig::accept_underpaying_htlcs`] is set.
1146		///
1147		/// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
1148		counterparty_skimmed_fee_msat: u64,
1149		/// Information for claiming this received payment, based on whether the purpose of the
1150		/// payment is to pay an invoice or to send a spontaneous payment.
1151		purpose: PaymentPurpose,
1152		/// The `(channel_id, user_channel_id)` pairs over which the payment was received.
1153		///
1154		/// This will be an incomplete vector for MPP payment events created/serialized using LDK version 0.1.0 and prior.
1155		receiving_channel_ids: Vec<(ChannelId, Option<u128>)>,
1156		/// The block height at which this payment will be failed back and will no longer be
1157		/// eligible for claiming.
1158		///
1159		/// Prior to this height, a call to [`ChannelManager::claim_funds`] is guaranteed to
1160		/// succeed, however you should wait for [`Event::PaymentClaimed`] to be sure.
1161		///
1162		/// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
1163		claim_deadline: Option<u32>,
1164		/// A unique ID describing this payment (derived from the list of HTLCs in the payment).
1165		///
1166		/// Payers may pay for the same [`PaymentHash`] multiple times (though this is unsafe and
1167		/// an intermediary node may steal the funds). Thus, in order to accurately track when
1168		/// payments are received and claimed, you should use this identifier.
1169		///
1170		/// Only filled in for payments received on LDK versions 0.1 and higher.
1171		payment_id: Option<PaymentId>,
1172	},
1173	/// Indicates a payment has been claimed and we've received money!
1174	///
1175	/// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
1176	/// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
1177	/// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
1178	/// [`Event::PaymentClaimable`] event.
1179	///
1180	/// # Note
1181	/// LDK will not stop an inbound payment from being paid multiple times, so multiple
1182	/// `PaymentClaimable` events may be generated for the same payment. If you then call
1183	/// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
1184	/// multiple `PaymentClaimed` events.
1185	///
1186	/// # Failure Behavior and Persistence
1187	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1188	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1189	///
1190	/// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
1191	PaymentClaimed {
1192		/// The node that received the payment.
1193		/// This is useful to identify payments which were received via [phantom nodes].
1194		/// This field will always be filled in when the event was generated by LDK versions
1195		/// 0.0.113 and above.
1196		///
1197		/// [phantom nodes]: crate::sign::PhantomKeysManager
1198		receiver_node_id: Option<PublicKey>,
1199		/// The payment hash of the claimed payment. Note that LDK will not stop you from
1200		/// registering duplicate payment hashes for inbound payments.
1201		payment_hash: PaymentHash,
1202		/// The value, in thousandths of a satoshi, that this payment is for. May be greater than the
1203		/// invoice amount.
1204		amount_msat: u64,
1205		/// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
1206		/// spontaneous payment.
1207		purpose: PaymentPurpose,
1208		/// The HTLCs that comprise the claimed payment. This will be empty for events serialized prior
1209		/// to LDK version 0.0.117.
1210		htlcs: Vec<ClaimedHTLC>,
1211		/// The sender-intended sum total of all the MPP parts. This will be `None` for events
1212		/// serialized prior to LDK version 0.0.117.
1213		sender_intended_total_msat: Option<u64>,
1214		/// The fields in the onion which were received with each HTLC. Only fields which were
1215		/// identical in each HTLC involved in the payment will be included here.
1216		///
1217		/// Payments received on LDK versions prior to 0.0.124 will have this field unset.
1218		onion_fields: Option<RecipientOnionFields>,
1219		/// A unique ID describing this payment (derived from the list of HTLCs in the payment).
1220		///
1221		/// Payers may pay for the same [`PaymentHash`] multiple times (though this is unsafe and
1222		/// an intermediary node may steal the funds). Thus, in order to accurately track when
1223		/// payments are received and claimed, you should use this identifier.
1224		///
1225		/// Only filled in for payments received on LDK versions 0.1 and higher.
1226		payment_id: Option<PaymentId>,
1227	},
1228	/// Indicates that a peer connection with a node is needed in order to send an [`OnionMessage`].
1229	///
1230	/// Typically, this happens when a [`MessageRouter`] is unable to find a complete path to a
1231	/// [`Destination`]. Once a connection is established, any messages buffered by an
1232	/// [`OnionMessageHandler`] may be sent.
1233	///
1234	/// This event will not be generated for onion message forwards; only for sends including
1235	/// replies. Handlers should connect to the node otherwise any buffered messages may be lost.
1236	///
1237	/// # Failure Behavior and Persistence
1238	/// This event won't be replayed after failures-to-handle
1239	/// (i.e., the event handler returning `Err(ReplayEvent ())`), and also won't be persisted
1240	/// across restarts.
1241	///
1242	/// [`OnionMessage`]: msgs::OnionMessage
1243	/// [`MessageRouter`]: crate::onion_message::messenger::MessageRouter
1244	/// [`Destination`]: crate::onion_message::messenger::Destination
1245	/// [`OnionMessageHandler`]: crate::ln::msgs::OnionMessageHandler
1246	ConnectionNeeded {
1247		/// The node id for the node needing a connection.
1248		node_id: PublicKey,
1249		/// Sockets for connecting to the node, if available. We don't require these addresses to be
1250		/// present in case the node id corresponds to a known peer that is offline and can be awoken,
1251		/// such as via the LSPS5 protocol.
1252		addresses: Vec<msgs::SocketAddress>,
1253	},
1254	/// Indicates a [`Bolt12Invoice`] in response to an [`InvoiceRequest`] or a [`Refund`] was
1255	/// received.
1256	///
1257	/// This event will only be generated if [`UserConfig::manually_handle_bolt12_invoices`] is set.
1258	/// Use [`ChannelManager::send_payment_for_bolt12_invoice`] to pay the invoice or
1259	/// [`ChannelManager::abandon_payment`] to abandon the associated payment. See those docs for
1260	/// further details.
1261	///
1262	/// # Failure Behavior and Persistence
1263	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1264	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1265	///
1266	/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
1267	/// [`Refund`]: crate::offers::refund::Refund
1268	/// [`UserConfig::manually_handle_bolt12_invoices`]: crate::util::config::UserConfig::manually_handle_bolt12_invoices
1269	/// [`ChannelManager::send_payment_for_bolt12_invoice`]: crate::ln::channelmanager::ChannelManager::send_payment_for_bolt12_invoice
1270	/// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
1271	InvoiceReceived {
1272		/// The `payment_id` associated with payment for the invoice.
1273		payment_id: PaymentId,
1274		/// The invoice to pay.
1275		invoice: Bolt12Invoice,
1276		/// The context of the [`BlindedMessagePath`] used to send the invoice.
1277		///
1278		/// [`BlindedMessagePath`]: crate::blinded_path::message::BlindedMessagePath
1279		context: Option<OffersContext>,
1280		/// A responder for replying with an [`InvoiceError`] if needed.
1281		///
1282		/// `None` if the invoice wasn't sent with a reply path.
1283		///
1284		/// [`InvoiceError`]: crate::offers::invoice_error::InvoiceError
1285		responder: Option<Responder>,
1286	},
1287	/// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
1288	/// and we got back the payment preimage for it).
1289	///
1290	/// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
1291	/// event. In this situation, you SHOULD treat this payment as having succeeded.
1292	///
1293	/// # Failure Behavior and Persistence
1294	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1295	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1296	PaymentSent {
1297		/// The `payment_id` passed to [`ChannelManager::send_payment`].
1298		///
1299		/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1300		payment_id: Option<PaymentId>,
1301		/// The preimage to the hash given to ChannelManager::send_payment.
1302		/// Note that this serves as a payment receipt, if you wish to have such a thing, you must
1303		/// store it somehow!
1304		payment_preimage: PaymentPreimage,
1305		/// The hash that was given to [`ChannelManager::send_payment`].
1306		///
1307		/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1308		payment_hash: PaymentHash,
1309		/// The total amount that was paid, across all paths.
1310		///
1311		/// Note that, like [`Route::get_total_amount`], this does *not* include the paid fees.
1312		///
1313		/// This is only `None` for payments initiated on LDK versions prior to 0.2.
1314		///
1315		/// [`Route::get_total_amount`]: crate::routing::router::Route::get_total_amount
1316		amount_msat: Option<u64>,
1317		/// The total fee which was spent at intermediate hops in this payment, across all paths.
1318		///
1319		/// Note that, like [`Route::get_total_fees`], this does *not* include any potential
1320		/// overpayment to the recipient node.
1321		///
1322		/// If the recipient or an intermediate node misbehaves and gives us free money, this may
1323		/// overstate the amount paid, though this is unlikely.
1324		///
1325		/// This is only `None` for payments abandoned but ultimately claimed when using LDK versions
1326		/// prior to 0.3, 0.2.3, or 0.1.10.
1327		///
1328		/// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
1329		fee_paid_msat: Option<u64>,
1330		/// The paid BOLT 12 invoice bundled with the data needed to construct a
1331		/// [`PayerProof`], which selectively discloses invoice fields to prove payment to a
1332		/// third party.
1333		///
1334		/// `None` for non-BOLT 12 payments.
1335		///
1336		/// [`PayerProof`]: crate::offers::payer_proof::PayerProof
1337		bolt12_invoice: Option<PaidBolt12Invoice>,
1338	},
1339	/// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
1340	/// provide failure information for each path attempt in the payment, including retries.
1341	///
1342	/// This event is provided once there are no further pending HTLCs for the payment and the
1343	/// payment is no longer retryable, due either to the [`Retry`] provided or
1344	/// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
1345	///
1346	/// In exceedingly rare cases, it is possible that an [`Event::PaymentFailed`] is generated for
1347	/// a payment after an [`Event::PaymentSent`] event for this same payment has already been
1348	/// received and processed. In this case, the [`Event::PaymentFailed`] event MUST be ignored,
1349	/// and the payment MUST be treated as having succeeded.
1350	///
1351	/// # Failure Behavior and Persistence
1352	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1353	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1354	///
1355	/// [`Retry`]: crate::ln::outbound_payment::Retry
1356	/// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
1357	PaymentFailed {
1358		/// The `payment_id` passed to [`ChannelManager::send_payment`].
1359		///
1360		/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1361		payment_id: PaymentId,
1362		/// The hash that was given to [`ChannelManager::send_payment`]. `None` if the payment failed
1363		/// before receiving an invoice when paying a BOLT12 [`Offer`].
1364		///
1365		/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1366		/// [`Offer`]: crate::offers::offer::Offer
1367		payment_hash: Option<PaymentHash>,
1368		/// The reason the payment failed. This is only `None` for events generated or serialized
1369		/// by versions prior to 0.0.115, or when downgrading to a version with a reason that was
1370		/// added after.
1371		reason: Option<PaymentFailureReason>,
1372	},
1373	/// Indicates that a path for an outbound payment was successful.
1374	///
1375	/// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
1376	/// [`Event::PaymentSent`] for obtaining the payment preimage.
1377	///
1378	/// # Failure Behavior and Persistence
1379	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1380	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1381	PaymentPathSuccessful {
1382		/// The `payment_id` passed to [`ChannelManager::send_payment`].
1383		///
1384		/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1385		payment_id: PaymentId,
1386		/// The hash that was given to [`ChannelManager::send_payment`].
1387		///
1388		/// This will be `Some` for all payments which completed on LDK 0.0.104 or later.
1389		///
1390		/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1391		payment_hash: Option<PaymentHash>,
1392		/// The payment path that was successful.
1393		///
1394		/// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
1395		path: Path,
1396		/// The time that each hop indicated it held the HTLC.
1397		///
1398		/// The unit in which the hold times are expressed are 100's of milliseconds. So a hop
1399		/// reporting 2 is a hold time that corresponds to between 200 and 299 milliseconds.
1400		///
1401		/// We expect that at each hop the actual hold time will be strictly greater than the hold
1402		/// time of the following hops, as a node along the path shouldn't have completed the HTLC
1403		/// until the next node has completed it. Note that because hold times are in 100's of ms,
1404		/// hold times as reported are likely to often be equal across hops.
1405		///
1406		/// If our peer didn't provide attribution data or the HTLC resolved on chain, the list
1407		/// will be empty.
1408		///
1409		/// Each entry will correspond with one entry in [`Path::hops`], or, thereafter, the
1410		/// [`BlindedTail::trampoline_hops`] in [`Path::blinded_tail`]. Because not all nodes
1411		/// support hold times, the list may be shorter than the number of hops in the path.
1412		hold_times: Vec<u32>,
1413	},
1414	/// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
1415	/// handle the HTLC.
1416	///
1417	/// Note that this does *not* indicate that all paths for an MPP payment have failed, see
1418	/// [`Event::PaymentFailed`].
1419	///
1420	/// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
1421	/// been exhausted.
1422	///
1423	/// # Failure Behavior and Persistence
1424	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1425	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1426	///
1427	/// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
1428	PaymentPathFailed {
1429		/// The `payment_id` passed to [`ChannelManager::send_payment`].
1430		///
1431		/// This will be `Some` for all payment paths which failed on LDK 0.0.103 or later.
1432		///
1433		/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1434		/// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
1435		payment_id: Option<PaymentId>,
1436		/// The hash that was given to [`ChannelManager::send_payment`].
1437		///
1438		/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1439		payment_hash: PaymentHash,
1440		/// Indicates the payment was rejected for some reason by the recipient. This implies that
1441		/// the payment has failed, not just the route in question. If this is not set, the payment may
1442		/// be retried via a different route.
1443		payment_failed_permanently: bool,
1444		/// Extra error details based on the failure type. May contain an update that needs to be
1445		/// applied to the [`NetworkGraph`].
1446		///
1447		/// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1448		failure: PathFailure,
1449		/// The payment path that failed.
1450		path: Path,
1451		/// The channel responsible for the failed payment path.
1452		///
1453		/// Note that for route hints or for the first hop in a path this may be an SCID alias and
1454		/// may not refer to a channel in the public network graph. These aliases may also collide
1455		/// with channels in the public network graph.
1456		///
1457		/// If this is `Some`, then the corresponding channel should be avoided when the payment is
1458		/// retried. May be `None` for older [`Event`] serializations.
1459		short_channel_id: Option<u64>,
1460		#[cfg(any(test, feature = "_test_utils"))]
1461		error_code: Option<u16>,
1462		#[cfg(any(test, feature = "_test_utils"))]
1463		error_data: Option<Vec<u8>>,
1464		/// The time that each hop indicated it held the HTLC.
1465		///
1466		/// The unit in which the hold times are expressed are 100's of milliseconds. So a hop
1467		/// reporting 2 is a hold time that corresponds to between 200 and 299 milliseconds.
1468		///
1469		/// We expect that at each hop the actual hold time will be strictly greater than the hold
1470		/// time of the following hops, as a node along the path shouldn't have completed the HTLC
1471		/// until the next node has completed it. Note that because hold times are in 100's of ms,
1472		/// hold times as reported are likely to often be equal across hops.
1473		///
1474		/// If our peer didn't provide attribution data or the HTLC resolved on chain, the list
1475		/// will be empty.
1476		///
1477		/// Each entry will correspond with one entry in [`Path::hops`], or, thereafter, the
1478		/// [`BlindedTail::trampoline_hops`] in [`Path::blinded_tail`]. Because not all nodes
1479		/// support hold times, the list may be shorter than the number of hops in the path.
1480		hold_times: Vec<u32>,
1481	},
1482	/// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
1483	///
1484	/// # Failure Behavior and Persistence
1485	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1486	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1487	ProbeSuccessful {
1488		/// The id returned by [`ChannelManager::send_probe`].
1489		///
1490		/// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
1491		payment_id: PaymentId,
1492		/// The hash generated by [`ChannelManager::send_probe`].
1493		///
1494		/// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
1495		payment_hash: PaymentHash,
1496		/// The payment path that was successful.
1497		path: Path,
1498	},
1499	/// Indicates that a probe payment we sent failed at an intermediary node on the path.
1500	///
1501	/// # Failure Behavior and Persistence
1502	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1503	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1504	ProbeFailed {
1505		/// The id returned by [`ChannelManager::send_probe`].
1506		///
1507		/// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
1508		payment_id: PaymentId,
1509		/// The hash generated by [`ChannelManager::send_probe`].
1510		///
1511		/// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
1512		payment_hash: PaymentHash,
1513		/// The payment path that failed.
1514		path: Path,
1515		/// The channel responsible for the failed probe.
1516		///
1517		/// Note that for route hints or for the first hop in a path this may be an SCID alias and
1518		/// may not refer to a channel in the public network graph. These aliases may also collide
1519		/// with channels in the public network graph.
1520		short_channel_id: Option<u64>,
1521	},
1522	/// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
1523	/// you've set some flags on [`UserConfig::htlc_interception_flags`].
1524	///
1525	/// [`ChannelManager::forward_intercepted_htlc`] or
1526	/// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event in a
1527	/// timely manner (i.e. within some number of seconds, not minutes). See their docs for more
1528	/// information.
1529	///
1530	/// # Failure Behavior and Persistence
1531	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1532	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1533	///
1534	/// [`UserConfig::htlc_interception_flags`]: crate::util::config::UserConfig::htlc_interception_flags
1535	/// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
1536	/// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
1537	HTLCIntercepted {
1538		/// An id to help LDK identify which HTLC is being forwarded or failed.
1539		intercept_id: InterceptId,
1540		/// The SCID which was selected by the sender as the next hop. It may point to one of our
1541		/// channels, an intercept SCID generated with [`ChannelManager::get_intercept_scid`], or
1542		/// an unknown SCID if [`HTLCInterceptionFlags::ToUnknownSCIDs`] was selected.
1543		///
1544		/// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
1545		/// [`HTLCInterceptionFlags::ToUnknownSCIDs`]: crate::util::config::HTLCInterceptionFlags::ToUnknownSCIDs
1546		requested_next_hop_scid: u64,
1547		/// The payment hash used for this HTLC.
1548		payment_hash: PaymentHash,
1549		/// How many msats were received on the inbound edge of this HTLC.
1550		inbound_amount_msat: u64,
1551		/// How many msats the payer intended to route to the next node. Depending on the reason you are
1552		/// intercepting this payment, you might take a fee by forwarding less than this amount.
1553		/// Forwarding less than this amount may break compatibility with LDK versions prior to 0.0.116.
1554		///
1555		/// Note that LDK will NOT check that expected fees were factored into this value. You MUST
1556		/// check that whatever fee you want has been included here (by comparing with
1557		/// [`Self::HTLCIntercepted::inbound_amount_msat`]) or subtract it as required. Further,
1558		/// LDK will not stop you from forwarding more than you received.
1559		expected_outbound_amount_msat: u64,
1560		/// The block height at which the forwarded HTLC sent to our peer will time out. In
1561		/// practice, LDK will refuse to forward an HTLC several blocks before this height (as if
1562		/// we attempted to forward an HTLC at this height we'd run some risk that our peer
1563		/// force-closes the channel immediately).
1564		///
1565		/// This will only be `None` for events generated or serialized by LDK 0.2 or prior.
1566		outgoing_htlc_expiry_block_height: Option<u32>,
1567	},
1568	/// Used to indicate that an output which you should know how to spend was confirmed on chain
1569	/// and is now spendable.
1570	///
1571	/// Such an output will *never* be spent directly by LDK, and are not at risk of your
1572	/// counterparty spending them due to some kind of timeout. Thus, you need to store them
1573	/// somewhere and spend them when you create on-chain transactions.
1574	///
1575	/// You may hand them to the [`OutputSweeper`] utility which will store and (re-)generate spending
1576	/// transactions for you.
1577	///
1578	/// # Failure Behavior and Persistence
1579	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1580	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1581	///
1582	/// [`OutputSweeper`]: crate::util::sweep::OutputSweeper
1583	SpendableOutputs {
1584		/// The outputs which you should store as spendable by you.
1585		outputs: Vec<SpendableOutputDescriptor>,
1586		/// The `channel_id` indicating which channel the spendable outputs belong to.
1587		///
1588		/// This will always be `Some` for events generated by LDK versions 0.0.117 and above.
1589		channel_id: Option<ChannelId>,
1590		/// The `node_id` of the channel counterparty.
1591		///
1592		/// This will always be `Some` for events generated by LDK versions 0.3 and above.
1593		counterparty_node_id: Option<PublicKey>,
1594	},
1595	/// This event is generated when a payment has been successfully forwarded through us and a
1596	/// forwarding fee earned.
1597	///
1598	/// Note that downgrading from 0.3 and above with pending trampoline forwards that use multipart
1599	/// payments will produce an event that only provides information about the first htlc that was
1600	/// received/dispatched.
1601	///
1602	/// A forward is uniquely identified by the set of [`InboundHTLCLocator::channel_id`] and
1603	/// [`InboundHTLCLocator::htlc_id`] pairs in `prev_htlcs`. As duplicate events may be generated
1604	/// for a single forward (see `total_fee_earned_msat` below), that set should be used as a
1605	/// de-duplication key.
1606	///
1607	/// # Failure Behavior and Persistence
1608	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1609	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1610	PaymentForwarded {
1611		/// The set of HTLCs forwarded to our node that will be claimed by this forward. Contains a
1612		/// single HTLC for source-routed payments, and may contain multiple HTLCs when we acted as
1613		/// a trampoline router, responsible for pathfinding within the route.
1614		prev_htlcs: Vec<InboundHTLCLocator>,
1615		/// The set of HTLCs forwarded by our node that have been claimed by this forward. Contains
1616		/// a single HTLC for regular source-routed payments, and may contain multiple HTLCs when
1617		/// we acted as a trampoline router, responsible for pathfinding within the route.
1618		next_htlcs: Vec<OutboundHTLCLocator>,
1619		/// The total fee, in milli-satoshis, which was earned as a result of the payment.
1620		///
1621		/// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
1622		/// was pending, the amount the next hop claimed will have been rounded down to the nearest
1623		/// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
1624		/// claimed the full value in millisatoshis from the source. In this case,
1625		/// `claim_from_onchain_tx` will be set.
1626		///
1627		/// If the channel which sent us the payment has been force-closed, we will claim the funds
1628		/// via an on-chain transaction. In that case we do not yet know the on-chain transaction
1629		/// fees which we will spend and will instead set this to `None`. It is possible duplicate
1630		/// `PaymentForwarded` events are generated for the same payment iff `total_fee_earned_msat` is
1631		/// `None`.
1632		total_fee_earned_msat: Option<u64>,
1633		/// The share of the total fee, in milli-satoshis, which was withheld in addition to the
1634		/// forwarding fee.
1635		///
1636		/// This will only be `Some` if we forwarded an intercepted HTLC with less than the
1637		/// expected amount. This means our counterparty accepted to receive less than the invoice
1638		/// amount, e.g., by claiming the payment featuring a corresponding
1639		/// [`PaymentClaimable::counterparty_skimmed_fee_msat`].
1640		///
1641		/// Will also always be `None` for events serialized with LDK prior to version 0.0.122.
1642		///
1643		/// The caveat described above the `total_fee_earned_msat` field applies here as well.
1644		///
1645		/// [`PaymentClaimable::counterparty_skimmed_fee_msat`]: Self::PaymentClaimable::counterparty_skimmed_fee_msat
1646		skimmed_fee_msat: Option<u64>,
1647		/// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
1648		/// transaction.
1649		claim_from_onchain_tx: bool,
1650		/// The final amount forwarded, in milli-satoshis, after the fee is deducted.
1651		///
1652		/// The caveat described above the `total_fee_earned_msat` field applies here as well.
1653		outbound_amount_forwarded_msat: u64,
1654	},
1655	/// Used to indicate that a channel with the given `channel_id` is being opened and pending
1656	/// confirmation on-chain.
1657	///
1658	/// This event is emitted when the funding transaction has been signed and is broadcast to the
1659	/// network. For 0conf channels it will be immediately followed by the corresponding
1660	/// [`Event::ChannelReady`] event.
1661	///
1662	/// # Failure Behavior and Persistence
1663	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1664	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1665	ChannelPending {
1666		/// The `channel_id` of the channel that is pending confirmation.
1667		channel_id: ChannelId,
1668		/// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1669		/// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels.
1670		///
1671		/// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1672		/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1673		user_channel_id: u128,
1674		/// The `temporary_channel_id` this channel used to be known by during channel establishment.
1675		///
1676		/// Will be `None` for channels created prior to LDK version 0.0.115.
1677		former_temporary_channel_id: Option<ChannelId>,
1678		/// The `node_id` of the channel counterparty.
1679		counterparty_node_id: PublicKey,
1680		/// The outpoint of the channel's funding transaction.
1681		funding_txo: OutPoint,
1682		/// The features that this channel will operate with.
1683		///
1684		/// Will be `None` for channels created prior to LDK version 0.0.122.
1685		channel_type: Option<ChannelTypeFeatures>,
1686		/// The witness script that is used to lock the channel's funding output to commitment transactions.
1687		///
1688		/// This field will be `None` for objects serialized with LDK versions prior to 0.2.0.
1689		funding_redeem_script: Option<ScriptBuf>,
1690	},
1691	/// Used to indicate that a channel with the given `channel_id` is ready to be used. This event
1692	/// is emitted when
1693	/// - the initial funding transaction has been confirmed on-chain to an acceptable depth
1694	///   according to both parties (i.e., `channel_ready` messages were exchanged),
1695	/// - a splice funding transaction has been confirmed on-chain to an acceptable depth according
1696	///   to both parties (i.e., `splice_locked` messages were exchanged), or,
1697	/// - in case of a 0conf channel, when both parties have confirmed the channel establishment.
1698	///
1699	/// # Failure Behavior and Persistence
1700	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1701	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1702	ChannelReady {
1703		/// The `channel_id` of the channel that is ready.
1704		channel_id: ChannelId,
1705		/// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1706		/// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels.
1707		///
1708		/// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1709		/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1710		user_channel_id: u128,
1711		/// The `node_id` of the channel counterparty.
1712		counterparty_node_id: PublicKey,
1713		/// The outpoint of the channel's funding transaction.
1714		///
1715		/// Will be `None` if the channel's funding transaction reached an acceptable depth prior to
1716		/// version 0.2.
1717		funding_txo: Option<OutPoint>,
1718		/// The features that this channel will operate with.
1719		channel_type: ChannelTypeFeatures,
1720	},
1721	/// Used to indicate that a channel that got past the initial handshake with the given `channel_id` is in the
1722	/// process of closure. This includes previously opened channels, and channels that time out from not being funded.
1723	///
1724	/// Note that this event is only triggered for accepted channels: if the
1725	/// [`Event::OpenChannelRequest`] was rejected, no `ChannelClosed` event will be sent.
1726	///
1727	/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1728	/// [`Event::OpenChannelRequest`]: Event::OpenChannelRequest
1729	///
1730	/// # Failure Behavior and Persistence
1731	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1732	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1733	ChannelClosed {
1734		/// The `channel_id` of the channel which has been closed. Note that on-chain transactions
1735		/// resolving the channel are likely still awaiting confirmation.
1736		channel_id: ChannelId,
1737		/// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1738		/// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels.
1739		/// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
1740		/// zero for objects serialized with LDK versions prior to 0.0.102.
1741		///
1742		/// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1743		/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1744		user_channel_id: u128,
1745		/// The reason the channel was closed.
1746		reason: ClosureReason,
1747		/// Counterparty in the closed channel.
1748		///
1749		/// This field will be `None` for objects serialized prior to LDK 0.0.117.
1750		counterparty_node_id: Option<PublicKey>,
1751		/// Channel capacity of the closing channel (sats).
1752		///
1753		/// This field will be `None` for objects serialized prior to LDK 0.0.117.
1754		channel_capacity_sats: Option<u64>,
1755
1756		/// The original channel funding TXO; this helps checking for the existence and confirmation
1757		/// status of the closing tx.
1758		/// Note that for instances serialized in v0.0.119 or prior this will be missing (None).
1759		channel_funding_txo: Option<transaction::OutPoint>,
1760		/// An upper bound on the our last local balance in msats before the channel was closed.
1761		///
1762		/// Will overstate our balance as it ignores pending outbound HTLCs and transaction fees.
1763		///
1764		/// For more accurate balances including fee information see
1765		/// [`ChainMonitor::get_claimable_balances`].
1766		///
1767		/// This field will be `None` only for objects serialized prior to LDK 0.1.
1768		///
1769		/// [`ChainMonitor::get_claimable_balances`]: crate::chain::chainmonitor::ChainMonitor::get_claimable_balances
1770		last_local_balance_msat: Option<u64>,
1771	},
1772	/// Used to indicate that a splice for the given `channel_id` has been negotiated, its
1773	/// funding transaction may be broadcast, and local inputs or outputs were contributed to it.
1774	/// This also applies when a channel closes with our funding signatures ready to send, even if
1775	/// the counterparty has not provided theirs.
1776	///
1777	/// This event is not emitted if the counterparty negotiated a splice without using a local
1778	/// contribution.
1779	///
1780	/// The splice is then considered pending until both parties have seen enough confirmations to
1781	/// consider the funding locked. Once this occurs, an [`Event::ChannelReady`] will be emitted.
1782	///
1783	/// Any UTXOs spent by the splice cannot be reused except by an RBF attempt for the same channel.
1784	///
1785	/// # Failure Behavior and Persistence
1786	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1787	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1788	SpliceNegotiated {
1789		/// The `channel_id` of the channel with the negotiated splice funding transaction.
1790		channel_id: ChannelId,
1791		/// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1792		/// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels.
1793		///
1794		/// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1795		/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1796		user_channel_id: u128,
1797		/// The `node_id` of the channel counterparty.
1798		counterparty_node_id: PublicKey,
1799		/// The outpoint of the channel's splice funding transaction.
1800		new_funding_txo: OutPoint,
1801		/// The features that this channel will operate with. Currently, these will be the same
1802		/// features that the channel was opened with, but in the future splices may change them.
1803		channel_type: ChannelTypeFeatures,
1804		/// The witness script that is used to lock the channel's funding output to commitment transactions.
1805		new_funding_redeem_script: ScriptBuf,
1806	},
1807	/// Used to indicate that a splice negotiation round for the given `channel_id` has failed.
1808	///
1809	/// Each splice attempt (initial or RBF) resolves to this event on failure, unless the
1810	/// contribution was rejected with an error returned from
1811	/// [`ChannelManager::funding_contributed`], in which case the failure is only reported
1812	/// through the returned [`SpliceContributionError`]. On success, [`Event::SpliceNegotiated`]
1813	/// is emitted if the negotiated transaction includes local inputs or outputs. Prior
1814	/// successfully negotiated splice transactions are unaffected.
1815	///
1816	/// Any UTXOs contributed to the failed round, other than those inherited from a splice attempt
1817	/// that remains pending, will be returned via a preceding [`Event::DiscardFunding`]. This also
1818	/// applies to contributions rejected with an error, though without a corresponding
1819	/// `SpliceNegotiationFailed` event. As that event precedes this one, the returned UTXOs are
1820	/// free again by the time this event is handled; retrying with
1821	/// [`FailedSpliceContribution::contribution`] requires reserving them again first.
1822	///
1823	/// If the channel closes after the counterparty has committed to the splice, funding remains
1824	/// reserved and [`Event::DiscardFunding`] follows once the closing transaction has enough
1825	/// confirmations.
1826	///
1827	/// A channel closing with our funding signatures ready to send instead produces
1828	/// [`Event::SpliceNegotiated`]. Wait for [`Event::DiscardFunding`] before reusing funding.
1829	///
1830	/// # Failure Behavior and Persistence
1831	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1832	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1833	///
1834	/// [`ChannelManager::funding_contributed`]: crate::ln::channelmanager::ChannelManager::funding_contributed
1835	/// [`SpliceContributionError`]: crate::ln::channelmanager::SpliceContributionError
1836	SpliceNegotiationFailed {
1837		/// The `channel_id` of the channel for which the splice negotiation round failed.
1838		channel_id: ChannelId,
1839		/// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1840		/// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels.
1841		///
1842		/// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1843		/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1844		user_channel_id: u128,
1845		/// The `node_id` of the channel counterparty.
1846		counterparty_node_id: PublicKey,
1847		/// The reason the splice negotiation failed.
1848		reason: NegotiationFailureReason,
1849		/// The funding contribution from the failed negotiation round, if available. See
1850		/// [`FailedSpliceContribution::contribution`] for how it can be reused in a subsequent
1851		/// splice attempt.
1852		contribution: Option<FailedSpliceContribution>,
1853	},
1854	/// Used to indicate to the user that they can abandon the funding transaction and recycle the
1855	/// inputs for another purpose.
1856	///
1857	/// When splicing, users can expect to receive an event for each negotiated splice transaction
1858	/// that did not become locked. The negotiated splice transaction that became locked can be
1859	/// obtained via [`Event::ChannelReady::funding_txo`].
1860	///
1861	/// This event is not guaranteed to be generated for channels that are closed due to a restart.
1862	///
1863	/// # Failure Behavior and Persistence
1864	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1865	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1866	DiscardFunding {
1867		/// The channel_id of the channel which has been closed.
1868		channel_id: ChannelId,
1869		/// The full transaction received from the user
1870		funding_info: FundingInfo,
1871	},
1872	/// Indicates a request to open a new channel by a peer.
1873	///
1874	/// This event is triggered for all inbound requests to open a new channel.
1875	/// To accept the request (and in the case of a dual-funded channel, not contribute funds),
1876	/// call [`ChannelManager::accept_inbound_channel`].
1877	/// To reject the request, call [`ChannelManager::force_close_broadcasting_latest_txn`].
1878	/// Note that a [`ChannelClosed`] event will _not_ be triggered if the channel is rejected.
1879	///
1880	/// # Failure Behavior and Persistence
1881	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1882	/// returning `Err(ReplayEvent ())`) and won't be persisted across restarts.
1883	///
1884	/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1885	/// [`ChannelClosed`]: Event::ChannelClosed
1886	/// [`ChannelManager::force_close_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_broadcasting_latest_txn
1887	OpenChannelRequest {
1888		/// The temporary channel ID of the channel requested to be opened.
1889		///
1890		/// When responding to the request, the `temporary_channel_id` should be passed
1891		/// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
1892		/// or through [`ChannelManager::force_close_broadcasting_latest_txn`] to reject.
1893		///
1894		/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1895		/// [`ChannelManager::force_close_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_broadcasting_latest_txn
1896		temporary_channel_id: ChannelId,
1897		/// The node_id of the counterparty requesting to open the channel.
1898		///
1899		/// When responding to the request, the `counterparty_node_id` should be passed
1900		/// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
1901		/// accept the request, or through [`ChannelManager::force_close_broadcasting_latest_txn`]
1902		/// to reject the request.
1903		///
1904		/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1905		/// [`ChannelManager::force_close_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_broadcasting_latest_txn
1906		counterparty_node_id: PublicKey,
1907		/// The channel value of the requested channel.
1908		funding_satoshis: u64,
1909		/// If `channel_negotiation_type` is `InboundChannelFunds::DualFunded`, this indicates that the peer wishes to
1910		/// open a dual-funded channel. Otherwise, this field will be `InboundChannelFunds::PushMsats`,
1911		/// indicating the `push_msats` value our peer is pushing to us for a non-dual-funded channel.
1912		channel_negotiation_type: InboundChannelFunds,
1913		/// The features that this channel will operate with. If you reject the channel, a
1914		/// well-behaved counterparty may automatically re-attempt the channel with a new set of
1915		/// feature flags.
1916		///
1917		/// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
1918		/// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1919		/// 0.0.106.
1920		///
1921		/// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
1922		/// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1923		/// 0.0.107. Channels setting this type also need to get manually accepted via
1924		/// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer`],
1925		/// or will be rejected otherwise.
1926		///
1927		/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1928		channel_type: ChannelTypeFeatures,
1929		/// True if this channel is (or will be) publicly-announced.
1930		is_announced: bool,
1931		/// Channel parameters given by the counterparty.
1932		params: msgs::ChannelParameters,
1933	},
1934	/// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
1935	/// forward it.
1936	///
1937	/// Note that downgrading from 0.3 with pending trampoline forwards that have incoming multipart
1938	/// payments will produce an event that only provides information about the first htlc that was
1939	/// received/dispatched.
1940	///
1941	/// # Failure Behavior and Persistence
1942	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1943	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1944	HTLCHandlingFailed {
1945		/// The channel(s) over which the HTLC(s) was received. May contain multiple entries for
1946		/// trampoline forwards.
1947		prev_channel_ids: Vec<ChannelId>,
1948		/// The type of HTLC handling that failed.
1949		failure_type: HTLCHandlingFailureType,
1950		/// The reason that the HTLC failed.
1951		///
1952		/// This field will be `None` only for objects serialized prior to LDK 0.2.0.
1953		failure_reason: Option<HTLCHandlingFailureReason>,
1954	},
1955	/// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
1956	/// requires confirmed external funds to be readily available to spend.
1957	///
1958	/// LDK does not currently generate this event unless either the
1959	/// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`] or the
1960	/// [`ChannelHandshakeConfig::negotiate_anchor_zero_fee_commitments`] config flags are set to
1961	/// true.
1962	/// It is limited to the scope of channels with anchor outputs.
1963	///
1964	/// # Failure Behavior and Persistence
1965	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1966	/// returning `Err(ReplayEvent ())`), but will only be regenerated as needed after restarts.
1967	///
1968	/// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`]: crate::util::config::ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx
1969	/// [`ChannelHandshakeConfig::negotiate_anchor_zero_fee_commitments`]: crate::util::config::ChannelHandshakeConfig::negotiate_anchor_zero_fee_commitments
1970	BumpTransaction(BumpTransactionEvent),
1971	/// We received an onion message that is intended to be forwarded to a peer
1972	/// that is currently offline *or* that is intended to be forwarded along a channel with an
1973	/// SCID unknown to us.
1974	///
1975	/// This event will only be generated if the `OnionMessenger` was initialized with
1976	/// [`OnionMessenger::new_with_offline_peer_interception`], see its docs. The
1977	/// [`NextMessageHop::ShortChannelId`] variant is only generated if `intercept_for_unknown_scids`
1978	/// was set when constructing the `OnionMessenger`.
1979	///
1980	/// The offline peer should be awoken if possible on receipt of this event, such as via the LSPS5
1981	/// protocol.
1982	///
1983	/// Once they connect, you should handle the generated [`Event::OnionMessagePeerConnected`] and
1984	/// provide the stored message.
1985	///
1986	/// # Failure Behavior and Persistence
1987	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1988	/// returning `Err(ReplayEvent ())`), but won't be persisted across restarts.
1989	///
1990	/// [`OnionMessenger::new_with_offline_peer_interception`]: crate::onion_message::messenger::OnionMessenger::new_with_offline_peer_interception
1991	OnionMessageIntercepted {
1992		/// The node id of the peer that sent the message, if known.
1993		///
1994		/// This is `None` when the message is sent with
1995		/// [`MessageSendInstructions::ForwardedMessage`] (e.g., when calling
1996		/// [`OffersMessageFlow::enqueue_invoice_request_to_forward`]) rather than forwarded
1997		/// internally by the `OnionMessenger`, as well as for events serialized prior to LDK 0.3.
1998		/// Otherwise it is the node we received the message from.
1999		///
2000		/// [`MessageSendInstructions::ForwardedMessage`]: crate::onion_message::messenger::MessageSendInstructions::ForwardedMessage
2001		/// [`OffersMessageFlow::enqueue_invoice_request_to_forward`]: crate::offers::flow::OffersMessageFlow::enqueue_invoice_request_to_forward
2002		prev_hop: Option<PublicKey>,
2003		/// The next hop (offline peer or unknown SCID).
2004		next_hop: NextMessageHop,
2005		/// The onion message intended to be forwarded to the offline peer or via the unknown
2006		/// channel once established.
2007		message: msgs::OnionMessage,
2008	},
2009	/// Indicates that an onion message supporting peer has come online and any messages previously
2010	/// stored for them (from [`Event::OnionMessageIntercepted`]s) should be forwarded to them by
2011	/// calling [`OnionMessenger::forward_onion_message`].
2012	///
2013	/// This event will only be generated if the `OnionMessenger` was initialized with
2014	/// [`OnionMessenger::new_with_offline_peer_interception`], see its docs.
2015	///
2016	/// # Failure Behavior and Persistence
2017	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
2018	/// returning `Err(ReplayEvent ())`), but won't be persisted across restarts.
2019	///
2020	/// [`OnionMessenger::forward_onion_message`]: crate::onion_message::messenger::OnionMessenger::forward_onion_message
2021	/// [`OnionMessenger::new_with_offline_peer_interception`]: crate::onion_message::messenger::OnionMessenger::new_with_offline_peer_interception
2022	OnionMessagePeerConnected {
2023		/// The node id of the peer we just connected to, who advertises support for
2024		/// onion messages.
2025		peer_node_id: PublicKey,
2026	},
2027	/// As a static invoice server, we received a [`StaticInvoice`] from an async recipient that wants
2028	/// us to serve the invoice to payers on their behalf when they are offline. This event will only
2029	/// be generated if we previously created paths using
2030	/// [`ChannelManager::blinded_paths_for_async_recipient`] and the recipient was configured with
2031	/// them via [`ChannelManager::set_paths_to_static_invoice_server`].
2032	///
2033	/// [`ChannelManager::blinded_paths_for_async_recipient`]: crate::ln::channelmanager::ChannelManager::blinded_paths_for_async_recipient
2034	/// [`ChannelManager::set_paths_to_static_invoice_server`]: crate::ln::channelmanager::ChannelManager::set_paths_to_static_invoice_server
2035	PersistStaticInvoice {
2036		/// The invoice that should be persisted and later provided to payers when handling a future
2037		/// [`Event::StaticInvoiceRequested`].
2038		invoice: StaticInvoice,
2039		/// The path to where invoice requests will be forwarded. If we receive an invoice
2040		/// request, we'll forward it to the async recipient over this path in case the
2041		/// recipient is online to provide a new invoice. This path should be persisted and
2042		/// later provided to [`ChannelManager::respond_to_static_invoice_request`].
2043		///
2044		/// This path's [`BlindedMessagePath::introduction_node`] MUST be set to our node or one of our
2045		/// peers. This is because, for DoS protection, invoice requests forwarded over this path are
2046		/// treated by our node like any other onion message forward and will not generate
2047		/// [`Event::ConnectionNeeded`] if the first hop in the path is not our peer.
2048		///
2049		/// If the next-hop peer in the path is offline, if configured to do so we will generate an
2050		/// [`Event::OnionMessageIntercepted`] for the invoice request.
2051		///
2052		/// [`ChannelManager::respond_to_static_invoice_request`]: crate::ln::channelmanager::ChannelManager::respond_to_static_invoice_request
2053		invoice_request_path: BlindedMessagePath,
2054		/// Useful for the recipient to replace a specific invoice stored by us as the static invoice
2055		/// server.
2056		///
2057		/// When this invoice and its metadata are persisted, this slot number should be included so if
2058		/// we receive another [`Event::PersistStaticInvoice`] containing the same slot number we can
2059		/// swap the existing invoice out for the new one.
2060		invoice_slot: u16,
2061		/// An identifier for the recipient, originally provided to
2062		/// [`ChannelManager::blinded_paths_for_async_recipient`].
2063		///
2064		/// When an [`Event::StaticInvoiceRequested`] comes in for the invoice, this id will be surfaced
2065		/// and can be used alongside the `invoice_slot` to retrieve the invoice from the database.
2066		///
2067		///[`ChannelManager::blinded_paths_for_async_recipient`]: crate::ln::channelmanager::ChannelManager::blinded_paths_for_async_recipient
2068		recipient_id: Vec<u8>,
2069		/// Once the [`StaticInvoice`] and `invoice_slot` are persisted,
2070		/// [`ChannelManager::static_invoice_persisted`] should be called with this responder to confirm
2071		/// to the recipient that their [`Offer`] is ready to be used for async payments.
2072		///
2073		/// [`ChannelManager::static_invoice_persisted`]: crate::ln::channelmanager::ChannelManager::static_invoice_persisted
2074		/// [`Offer`]: crate::offers::offer::Offer
2075		invoice_persisted_path: Responder,
2076	},
2077	/// As a static invoice server, we received an [`InvoiceRequest`] on behalf of an often-offline
2078	/// recipient for whom we are serving [`StaticInvoice`]s.
2079	///
2080	/// This event will only be generated if we previously created paths using
2081	/// [`ChannelManager::blinded_paths_for_async_recipient`] and the recipient was configured with
2082	/// them via [`ChannelManager::set_paths_to_static_invoice_server`].
2083	///
2084	/// If we previously persisted a [`StaticInvoice`] from an [`Event::PersistStaticInvoice`] that
2085	/// matches the below `recipient_id` and `invoice_slot`, that invoice should be retrieved now
2086	/// and forwarded to the payer via [`ChannelManager::respond_to_static_invoice_request`].
2087	/// The invoice request path previously persisted from [`Event::PersistStaticInvoice`] should
2088	/// also be provided in [`ChannelManager::respond_to_static_invoice_request`].
2089	///
2090	/// [`ChannelManager::blinded_paths_for_async_recipient`]: crate::ln::channelmanager::ChannelManager::blinded_paths_for_async_recipient
2091	/// [`ChannelManager::set_paths_to_static_invoice_server`]: crate::ln::channelmanager::ChannelManager::set_paths_to_static_invoice_server
2092	/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
2093	/// [`ChannelManager::respond_to_static_invoice_request`]: crate::ln::channelmanager::ChannelManager::respond_to_static_invoice_request
2094	StaticInvoiceRequested {
2095		/// An identifier for the recipient previously surfaced in
2096		/// [`Event::PersistStaticInvoice::recipient_id`]. Useful when paired with the `invoice_slot` to
2097		/// retrieve the [`StaticInvoice`] requested by the payer.
2098		recipient_id: Vec<u8>,
2099		/// The slot number for the invoice being requested, previously surfaced in
2100		/// [`Event::PersistStaticInvoice::invoice_slot`]. Useful when paired with the `recipient_id` to
2101		/// retrieve the [`StaticInvoice`] requested by the payer.
2102		invoice_slot: u16,
2103		/// The path over which the [`StaticInvoice`] will be sent to the payer, which should be
2104		/// provided to [`ChannelManager::respond_to_static_invoice_request`] along with the invoice.
2105		///
2106		/// [`ChannelManager::respond_to_static_invoice_request`]: crate::ln::channelmanager::ChannelManager::respond_to_static_invoice_request
2107		reply_path: Responder,
2108		/// The invoice request that will be forwarded to the async recipient to give the
2109		/// recipient a chance to provide an invoice in case it is online. It should be
2110		/// provided to [`ChannelManager::respond_to_static_invoice_request`].
2111		///
2112		/// [`ChannelManager::respond_to_static_invoice_request`]: crate::ln::channelmanager::ChannelManager::respond_to_static_invoice_request
2113		invoice_request: InvoiceRequest,
2114	},
2115	/// Indicates that a channel funding transaction constructed interactively is ready to be
2116	/// signed. This event will only be triggered if a contribution was made to the transaction.
2117	///
2118	/// The transaction contains all inputs and outputs provided by both parties including the
2119	/// channel's funding output and a change output if applicable.
2120	///
2121	/// No part of the transaction should be changed before signing as the content of the transaction
2122	/// has already been negotiated with the counterparty.
2123	///
2124	/// Each signature MUST use the `SIGHASH_ALL` flag to avoid invalidation of the initial commitment and
2125	/// hence possible loss of funds.
2126	///
2127	/// After signing, call [`ChannelManager::funding_transaction_signed`] with the (partially)
2128	/// signed funding transaction. For splices where you contributed inputs or outputs, call
2129	/// [`ChannelManager::cancel_funding_contributed`] instead if you no longer wish to proceed.
2130	///
2131	/// The funding negotiation may fail while this event is pending, e.g. because the counterparty
2132	/// aborted it or the channel was closed, in which case
2133	/// [`ChannelManager::funding_transaction_signed`] returns an [`APIError::APIMisuseError`] or
2134	/// [`APIError::ChannelUnavailable`] without you having done anything wrong. The negotiated
2135	/// funding transaction will then never be used. For a splice, an [`Event::DiscardFunding`] (for
2136	/// any contributions other than those inherited from a splice attempt that remains pending)
2137	/// and an [`Event::SpliceNegotiationFailed`] follow, whereas for a channel being opened an
2138	/// [`Event::ChannelClosed`] is generated.
2139	///
2140	/// Generated in [`ChannelManager`] message handling.
2141	///
2142	/// # Failure Behavior and Persistence
2143	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
2144	/// returning `Err(ReplayEvent ())`), but will only be regenerated as needed after restarts.
2145	///
2146	/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
2147	/// [`ChannelManager::cancel_funding_contributed`]: crate::ln::channelmanager::ChannelManager::cancel_funding_contributed
2148	/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
2149	FundingTransactionReadyForSigning {
2150		/// The `channel_id` of the channel which you'll need to pass back into
2151		/// [`ChannelManager::funding_transaction_signed`].
2152		///
2153		/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
2154		channel_id: ChannelId,
2155		/// The counterparty's `node_id`, which you'll need to pass back into
2156		/// [`ChannelManager::funding_transaction_signed`].
2157		///
2158		/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
2159		counterparty_node_id: PublicKey,
2160		/// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
2161		/// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels.
2162		///
2163		/// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
2164		/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
2165		user_channel_id: u128,
2166		/// The unsigned transaction to be signed and passed back to
2167		/// [`ChannelManager::funding_transaction_signed`].
2168		///
2169		/// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
2170		unsigned_transaction: Transaction,
2171	},
2172}
2173
2174impl Writeable for Event {
2175	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
2176		match self {
2177			&Event::FundingGenerationReady { .. } => {
2178				0u8.write(writer)?;
2179				// We never write out FundingGenerationReady events as, upon disconnection, peers
2180				// drop any channels which have not yet exchanged funding_signed.
2181			},
2182			&Event::PaymentClaimable {
2183				ref payment_hash,
2184				ref amount_msat,
2185				counterparty_skimmed_fee_msat,
2186				ref purpose,
2187				ref receiver_node_id,
2188				ref receiving_channel_ids,
2189				ref claim_deadline,
2190				ref onion_fields,
2191				ref payment_id,
2192			} => {
2193				1u8.write(writer)?;
2194				let mut payment_secret = None;
2195				let payment_preimage;
2196				let mut payment_context = None;
2197				match &purpose {
2198					PaymentPurpose::Bolt11InvoicePayment {
2199						payment_preimage: preimage,
2200						payment_secret: secret,
2201					} => {
2202						payment_secret = Some(secret);
2203						payment_preimage = *preimage;
2204					},
2205					PaymentPurpose::Bolt12OfferPayment {
2206						payment_preimage: preimage,
2207						payment_secret: secret,
2208						payment_context: context,
2209					} => {
2210						payment_secret = Some(secret);
2211						payment_preimage = *preimage;
2212						payment_context = Some(PaymentContextRef::Bolt12Offer(context));
2213					},
2214					PaymentPurpose::Bolt12RefundPayment {
2215						payment_preimage: preimage,
2216						payment_secret: secret,
2217						payment_context: context,
2218					} => {
2219						payment_secret = Some(secret);
2220						payment_preimage = *preimage;
2221						payment_context = Some(PaymentContextRef::Bolt12Refund(context));
2222					},
2223					PaymentPurpose::SpontaneousPayment(preimage) => {
2224						payment_preimage = Some(*preimage);
2225					},
2226				}
2227				let skimmed_fee_opt = if counterparty_skimmed_fee_msat == 0 {
2228					None
2229				} else {
2230					Some(counterparty_skimmed_fee_msat)
2231				};
2232
2233				let (receiving_channel_id_legacy, receiving_user_channel_id_legacy) =
2234					match receiving_channel_ids.last() {
2235						Some((chan_id, user_chan_id)) => (Some(*chan_id), *user_chan_id),
2236						None => (None, None),
2237					};
2238				write_tlv_fields!(writer, {
2239					(0, payment_hash, required),
2240					(1, receiver_node_id, option),
2241					(2, payment_secret, option),
2242					// Marked as legacy in version 0.2.0; superseded by `receiving_channel_ids`,
2243					// which includes all channel IDs used in the payment instead of only the last
2244					// one.
2245					(3, receiving_channel_id_legacy, option),
2246					(4, amount_msat, required),
2247					// Marked as legacy in version 0.2.0 for the same reason as
2248					// `receiving_channel_id_legacy`; superseded by `receiving_channel_ids`.
2249					(5, receiving_user_channel_id_legacy, option),
2250					// Type 6 was `user_payment_id` on 0.0.103 and earlier
2251					(7, claim_deadline, option),
2252					(8, payment_preimage, option),
2253					(9, onion_fields, option),
2254					(10, skimmed_fee_opt, option),
2255					(11, payment_context, option),
2256					(13, payment_id, option),
2257					(15, *receiving_channel_ids, optional_vec),
2258				});
2259			},
2260			&Event::PaymentSent {
2261				ref payment_id,
2262				ref payment_preimage,
2263				ref payment_hash,
2264				ref amount_msat,
2265				ref fee_paid_msat,
2266				ref bolt12_invoice,
2267			} => {
2268				2u8.write(writer)?;
2269				write_tlv_fields!(writer, {
2270					(0, payment_preimage, required),
2271					(1, payment_hash, required),
2272					(3, payment_id, option),
2273					(5, fee_paid_msat, option),
2274					(7, amount_msat, option),
2275					(9, bolt12_invoice, option),
2276				});
2277			},
2278			&Event::PaymentPathFailed {
2279				ref payment_id,
2280				ref payment_hash,
2281				ref payment_failed_permanently,
2282				ref failure,
2283				ref path,
2284				ref short_channel_id,
2285				#[cfg(any(test, feature = "_test_utils"))]
2286				ref error_code,
2287				#[cfg(any(test, feature = "_test_utils"))]
2288				ref error_data,
2289				ref hold_times,
2290			} => {
2291				3u8.write(writer)?;
2292				#[cfg(any(test, feature = "_test_utils"))]
2293				error_code.write(writer)?;
2294				#[cfg(any(test, feature = "_test_utils"))]
2295				error_data.write(writer)?;
2296				write_tlv_fields!(writer, {
2297					(0, payment_hash, required),
2298					(1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
2299					(2, payment_failed_permanently, required),
2300					(3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
2301					(4, path.blinded_tail, option),
2302					(5, path.hops, required_vec),
2303					(7, short_channel_id, option),
2304					(9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
2305					(11, payment_id, option),
2306					(13, failure, required),
2307					(15, *hold_times, optional_vec),
2308				});
2309			},
2310			// 4u8 used to be `PendingHTLCsForwardable`
2311			&Event::SpendableOutputs { ref outputs, channel_id, counterparty_node_id } => {
2312				5u8.write(writer)?;
2313				write_tlv_fields!(writer, {
2314					(0, WithoutLength(outputs), required),
2315					(1, channel_id, option),
2316					(3, counterparty_node_id, option),
2317				});
2318			},
2319			&Event::HTLCIntercepted {
2320				requested_next_hop_scid,
2321				payment_hash,
2322				inbound_amount_msat,
2323				expected_outbound_amount_msat,
2324				intercept_id,
2325				outgoing_htlc_expiry_block_height,
2326			} => {
2327				6u8.write(writer)?;
2328				let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
2329				write_tlv_fields!(writer, {
2330					(0, intercept_id, required),
2331					(1, outgoing_htlc_expiry_block_height, option),
2332					(2, intercept_scid, required),
2333					(4, payment_hash, required),
2334					(6, inbound_amount_msat, required),
2335					(8, expected_outbound_amount_msat, required),
2336				});
2337			},
2338			&Event::PaymentForwarded {
2339				ref prev_htlcs,
2340				ref next_htlcs,
2341				total_fee_earned_msat,
2342				skimmed_fee_msat,
2343				claim_from_onchain_tx,
2344				outbound_amount_forwarded_msat,
2345			} => {
2346				7u8.write(writer)?;
2347				// Fields 1, 3, 9, 11, 13 and 15 are written for backwards compatibility. We don't
2348				// want to fail writes, so we write garbage data if we don't have at least on htlc.
2349				debug_assert!(
2350					!prev_htlcs.is_empty(),
2351					"at least one prev_htlc required for PaymentForwarded",
2352				);
2353				debug_assert!(
2354					!next_htlcs.is_empty(),
2355					"at least one next_htlc required for PaymentForwarded",
2356				);
2357				let empty_prev = InboundHTLCLocator {
2358					channel_id: ChannelId::new_zero(),
2359					htlc_id: None,
2360					amount_msat: None,
2361					user_channel_id: None,
2362					node_id: None,
2363				};
2364				let empty_next = OutboundHTLCLocator {
2365					channel_id: ChannelId::new_zero(),
2366					amount_msat: None,
2367					user_channel_id: None,
2368					node_id: None,
2369				};
2370				let legacy_prev = prev_htlcs.first().unwrap_or(&empty_prev);
2371				let legacy_next = next_htlcs.first().unwrap_or(&empty_next);
2372				write_tlv_fields!(writer, {
2373					(0, total_fee_earned_msat, option),
2374					(1, Some(legacy_prev.channel_id), option),
2375					(2, claim_from_onchain_tx, required),
2376					(3, Some(legacy_next.channel_id), option),
2377					(5, outbound_amount_forwarded_msat, required),
2378					(7, skimmed_fee_msat, option),
2379					(9, legacy_prev.user_channel_id, option),
2380					(11, legacy_next.user_channel_id, option),
2381					(13, legacy_prev.node_id, option),
2382					(15, legacy_next.node_id, option),
2383					// HTLCs are written as required, rather than required_vec, so that they can be
2384					// deserialized using default_value to fill in legacy fields which expects
2385					// LengthReadable (required_vec is WithoutLength).
2386					(17, *prev_htlcs, required),
2387					(19, *next_htlcs, required),
2388				});
2389			},
2390			&Event::ChannelClosed {
2391				ref channel_id,
2392				ref user_channel_id,
2393				ref reason,
2394				ref counterparty_node_id,
2395				ref channel_capacity_sats,
2396				ref channel_funding_txo,
2397				ref last_local_balance_msat,
2398			} => {
2399				9u8.write(writer)?;
2400				// `user_channel_id` used to be a single u64 value. In order to remain backwards
2401				// compatible with versions prior to 0.0.113, the u128 is serialized as two
2402				// separate u64 values.
2403				let user_channel_id_low = *user_channel_id as u64;
2404				let user_channel_id_high = (*user_channel_id >> 64) as u64;
2405				write_tlv_fields!(writer, {
2406					(0, channel_id, required),
2407					(1, user_channel_id_low, required),
2408					(2, reason, required),
2409					(3, user_channel_id_high, required),
2410					(5, counterparty_node_id, option),
2411					(7, channel_capacity_sats, option),
2412					(9, channel_funding_txo, option),
2413					(11, last_local_balance_msat, option)
2414				});
2415			},
2416			&Event::DiscardFunding { ref channel_id, ref funding_info } => {
2417				if let FundingInfo::Contribution { .. } = funding_info {
2418					// 0.2 requires a transaction or outpoint when reading event type 11, so write
2419					// `FundingInfo::Contribution` under an odd event type it will ignore instead.
2420					53u8.write(writer)?;
2421					write_tlv_fields!(writer, {
2422						(1, channel_id, required),
2423						(3, funding_info, required),
2424					})
2425				} else {
2426					11u8.write(writer)?;
2427
2428					let transaction = if let FundingInfo::Tx { transaction } = funding_info {
2429						Some(transaction)
2430					} else {
2431						None
2432					};
2433					write_tlv_fields!(writer, {
2434						(0, channel_id, required),
2435						(2, transaction, option),
2436						(4, funding_info, required),
2437					})
2438				}
2439			},
2440			&Event::PaymentPathSuccessful {
2441				ref payment_id,
2442				ref payment_hash,
2443				ref path,
2444				ref hold_times,
2445			} => {
2446				13u8.write(writer)?;
2447				write_tlv_fields!(writer, {
2448					(0, payment_id, required),
2449					(1, *hold_times, optional_vec),
2450					(2, payment_hash, option),
2451					(4, path.hops, required_vec),
2452					(6, path.blinded_tail, option),
2453				})
2454			},
2455			&Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
2456				15u8.write(writer)?;
2457				let (payment_hash, invoice_received) = match payment_hash {
2458					Some(payment_hash) => (payment_hash, true),
2459					None => (&PaymentHash([0; 32]), false),
2460				};
2461				let legacy_reason = match reason {
2462					None => &None,
2463					// Variants available prior to version 0.0.124.
2464					Some(PaymentFailureReason::RecipientRejected)
2465					| Some(PaymentFailureReason::UserAbandoned)
2466					| Some(PaymentFailureReason::RetriesExhausted)
2467					| Some(PaymentFailureReason::PaymentExpired)
2468					| Some(PaymentFailureReason::RouteNotFound)
2469					| Some(PaymentFailureReason::UnexpectedError) => reason,
2470					// Variants introduced at version 0.0.124 or later. Prior versions fail to parse
2471					// unknown variants, while versions 0.0.124 or later will use None.
2472					Some(PaymentFailureReason::UnknownRequiredFeatures) => {
2473						&Some(PaymentFailureReason::RecipientRejected)
2474					},
2475					Some(PaymentFailureReason::InvoiceRequestExpired) => {
2476						&Some(PaymentFailureReason::RetriesExhausted)
2477					},
2478					Some(PaymentFailureReason::InvoiceRequestRejected) => {
2479						&Some(PaymentFailureReason::RecipientRejected)
2480					},
2481					Some(PaymentFailureReason::BlindedPathCreationFailed) => {
2482						&Some(PaymentFailureReason::RouteNotFound)
2483					},
2484				};
2485				write_tlv_fields!(writer, {
2486					(0, payment_id, required),
2487					(1, legacy_reason, option),
2488					(2, payment_hash, required),
2489					(3, invoice_received, required),
2490					(5, reason, option),
2491				})
2492			},
2493			&Event::OpenChannelRequest { .. } => {
2494				17u8.write(writer)?;
2495				// We never write the OpenChannelRequest events as, upon disconnection, peers
2496				// drop any channels which have not yet exchanged funding_signed.
2497			},
2498			&Event::PaymentClaimed {
2499				ref payment_hash,
2500				ref amount_msat,
2501				ref purpose,
2502				ref receiver_node_id,
2503				ref htlcs,
2504				ref sender_intended_total_msat,
2505				ref onion_fields,
2506				ref payment_id,
2507			} => {
2508				19u8.write(writer)?;
2509				write_tlv_fields!(writer, {
2510					(0, payment_hash, required),
2511					(1, receiver_node_id, option),
2512					(2, purpose, required),
2513					(4, amount_msat, required),
2514					(5, *htlcs, optional_vec),
2515					(7, sender_intended_total_msat, option),
2516					(9, onion_fields, option),
2517					(11, payment_id, option),
2518				});
2519			},
2520			&Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
2521				21u8.write(writer)?;
2522				write_tlv_fields!(writer, {
2523					(0, payment_id, required),
2524					(2, payment_hash, required),
2525					(4, path.hops, required_vec),
2526					(6, path.blinded_tail, option),
2527				})
2528			},
2529			&Event::ProbeFailed {
2530				ref payment_id,
2531				ref payment_hash,
2532				ref path,
2533				ref short_channel_id,
2534			} => {
2535				23u8.write(writer)?;
2536				write_tlv_fields!(writer, {
2537					(0, payment_id, required),
2538					(2, payment_hash, required),
2539					(4, path.hops, required_vec),
2540					(6, short_channel_id, option),
2541					(8, path.blinded_tail, option),
2542				})
2543			},
2544			&Event::HTLCHandlingFailed {
2545				ref prev_channel_ids,
2546				ref failure_type,
2547				ref failure_reason,
2548			} => {
2549				25u8.write(writer)?;
2550				// Legacy field is written for backwards compatibility. We don't want to fail writes
2551				// so we write garbage data if we don't have the data we expect.
2552				debug_assert!(
2553					!prev_channel_ids.is_empty(),
2554					"at least one prev_channel_id required for HTLCHandlingFailed"
2555				);
2556				let zero_id = ChannelId::new_zero();
2557				let legacy_chan_id = prev_channel_ids.first().unwrap_or(&zero_id);
2558				write_tlv_fields!(writer, {
2559					(0, legacy_chan_id, required),
2560					(1, failure_reason, option),
2561					(2, failure_type, required),
2562					(3, *prev_channel_ids, required),
2563				})
2564			},
2565			&Event::BumpTransaction(ref event) => {
2566				27u8.write(writer)?;
2567				match event {
2568					// We never write the ChannelClose|HTLCResolution events as they'll be replayed
2569					// upon restarting anyway if they remain unresolved.
2570					BumpTransactionEvent::ChannelClose { .. } => {},
2571					BumpTransactionEvent::HTLCResolution { .. } => {},
2572				}
2573				write_tlv_fields!(writer, {}); // Write a length field for forwards compat
2574			},
2575			&Event::ChannelReady {
2576				ref channel_id,
2577				ref user_channel_id,
2578				ref counterparty_node_id,
2579				ref funding_txo,
2580				ref channel_type,
2581			} => {
2582				29u8.write(writer)?;
2583				write_tlv_fields!(writer, {
2584					(0, channel_id, required),
2585					(1, funding_txo, option),
2586					(2, user_channel_id, required),
2587					(4, counterparty_node_id, required),
2588					(6, channel_type, required),
2589				});
2590			},
2591			&Event::ChannelPending {
2592				ref channel_id,
2593				ref user_channel_id,
2594				ref former_temporary_channel_id,
2595				ref counterparty_node_id,
2596				ref funding_txo,
2597				ref channel_type,
2598				ref funding_redeem_script,
2599			} => {
2600				31u8.write(writer)?;
2601				write_tlv_fields!(writer, {
2602					(0, channel_id, required),
2603					(1, channel_type, option),
2604					(2, user_channel_id, required),
2605					(4, former_temporary_channel_id, required),
2606					(6, counterparty_node_id, required),
2607					(8, funding_txo, required),
2608					(9, funding_redeem_script, option),
2609				});
2610			},
2611			&Event::ConnectionNeeded { .. } => {
2612				35u8.write(writer)?;
2613				// Never write ConnectionNeeded events as buffered onion messages aren't serialized.
2614			},
2615			&Event::OnionMessageIntercepted { ref prev_hop, ref next_hop, ref message } => {
2616				37u8.write(writer)?;
2617				// 0 used to be peer_node_id in LDK v0.2 and prior; we keep writing it when the next
2618				// hop is a node id for backwards compatibility.
2619				let legacy_peer_node_id = match next_hop {
2620					NextMessageHop::NodeId(node_id) => Some(node_id),
2621					NextMessageHop::ShortChannelId(_) => None,
2622				};
2623				write_tlv_fields!(writer, {
2624					(0, legacy_peer_node_id, option),
2625					(1, next_hop, required),
2626					(2, message, required),
2627					(3, prev_hop, option),
2628				});
2629			},
2630			&Event::OnionMessagePeerConnected { ref peer_node_id } => {
2631				39u8.write(writer)?;
2632				write_tlv_fields!(writer, {
2633					(0, peer_node_id, required),
2634				});
2635			},
2636			&Event::InvoiceReceived { ref payment_id, ref invoice, ref context, ref responder } => {
2637				41u8.write(writer)?;
2638				write_tlv_fields!(writer, {
2639					(0, payment_id, required),
2640					(2, invoice, required),
2641					(4, context, option),
2642					(6, responder, option),
2643				});
2644			},
2645			&Event::FundingTxBroadcastSafe {
2646				ref channel_id,
2647				ref user_channel_id,
2648				ref funding_txo,
2649				ref counterparty_node_id,
2650				ref former_temporary_channel_id,
2651			} => {
2652				43u8.write(writer)?;
2653				write_tlv_fields!(writer, {
2654					(0, channel_id, required),
2655					(2, user_channel_id, required),
2656					(4, funding_txo, required),
2657					(6, counterparty_node_id, required),
2658					(8, former_temporary_channel_id, required),
2659				});
2660			},
2661			&Event::PersistStaticInvoice { .. } => {
2662				45u8.write(writer)?;
2663				// No need to write these events because we can just restart the static invoice negotiation
2664				// on startup.
2665			},
2666			&Event::StaticInvoiceRequested { .. } => {
2667				47u8.write(writer)?;
2668				// Never write StaticInvoiceRequested events as buffered onion messages aren't serialized.
2669			},
2670			&Event::FundingTransactionReadyForSigning { .. } => {
2671				49u8.write(writer)?;
2672				// We never write out FundingTransactionReadyForSigning events as they will be regenerated when
2673				// necessary.
2674			},
2675			&Event::SpliceNegotiated {
2676				ref channel_id,
2677				ref user_channel_id,
2678				ref counterparty_node_id,
2679				ref new_funding_txo,
2680				ref channel_type,
2681				ref new_funding_redeem_script,
2682			} => {
2683				50u8.write(writer)?;
2684				write_tlv_fields!(writer, {
2685					(1, channel_id, required),
2686					(3, channel_type, required),
2687					(5, user_channel_id, required),
2688					(7, counterparty_node_id, required),
2689					(9, new_funding_txo, required),
2690					(11, new_funding_redeem_script, required),
2691				});
2692			},
2693			&Event::SpliceNegotiationFailed {
2694				ref channel_id,
2695				ref user_channel_id,
2696				ref counterparty_node_id,
2697				ref reason,
2698				ref contribution,
2699			} => {
2700				52u8.write(writer)?;
2701				// 0.2 wrote `contributed_inputs` and `contributed_outputs` at types 11 and 13, so
2702				// write them for its benefit when downgrading. They are also read back to survive
2703				// re-serialization. Types 3 and 9 were `channel_type` and `abandoned_funding_txo`
2704				// in 0.2 and must not be reused.
2705				let contributed_inputs = contribution
2706					.as_ref()
2707					.filter(|contribution| !contribution.contributed_inputs.is_empty())
2708					.map(|contribution| Iterable(contribution.contributed_inputs.iter()));
2709				let contributed_outputs = contribution
2710					.as_ref()
2711					.filter(|contribution| !contribution.contributed_outputs.is_empty())
2712					.map(|contribution| Iterable(contribution.contributed_outputs.iter()));
2713				let funding_contribution =
2714					contribution.as_ref().map(|contribution| &contribution.contribution);
2715				write_tlv_fields!(writer, {
2716					(1, channel_id, required),
2717					(5, user_channel_id, required),
2718					(7, counterparty_node_id, required),
2719					(11, contributed_inputs, option),
2720					(13, contributed_outputs, option),
2721					(15, reason, required),
2722					(17, funding_contribution, option),
2723				});
2724			},
2725			// Note that, going forward, all new events must only write data inside of
2726			// `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
2727			// data via `write_tlv_fields`.
2728		}
2729		Ok(())
2730	}
2731}
2732impl MaybeReadable for Event {
2733	fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
2734		match Readable::read(reader)? {
2735			// Note that we do not write a length-prefixed TLV for FundingGenerationReady events.
2736			0u8 => Ok(None),
2737			1u8 => {
2738				let mut f = || {
2739					let mut payment_hash = PaymentHash([0; 32]);
2740					let mut payment_preimage = None;
2741					let mut payment_secret = None;
2742					let mut amount_msat = 0;
2743					let mut counterparty_skimmed_fee_msat_opt = None;
2744					let mut receiver_node_id = None;
2745					let mut _user_payment_id = None::<u64>; // Used in 0.0.103 and earlier, no longer written in 0.0.116+.
2746					let mut receiving_channel_id_legacy = None;
2747					let mut claim_deadline = None;
2748					let mut receiving_user_channel_id_legacy = None;
2749					let mut onion_fields = None;
2750					let mut payment_context = None;
2751					let mut payment_id = None;
2752					let mut receiving_channel_ids_opt = None;
2753					read_tlv_fields!(reader, {
2754						(0, payment_hash, required),
2755						(1, receiver_node_id, option),
2756						(2, payment_secret, option),
2757						(3, receiving_channel_id_legacy, option),
2758						(4, amount_msat, required),
2759						(5, receiving_user_channel_id_legacy, option),
2760						(6, _user_payment_id, option),
2761						(7, claim_deadline, option),
2762						(8, payment_preimage, option),
2763						(9, onion_fields, (option: ReadableArgs, amount_msat)),
2764						(10, counterparty_skimmed_fee_msat_opt, option),
2765						(11, payment_context, option),
2766						(13, payment_id, option),
2767						(15, receiving_channel_ids_opt, optional_vec),
2768					});
2769					let purpose = match payment_secret {
2770						Some(secret) => {
2771							PaymentPurpose::from_parts(payment_preimage, secret, payment_context)
2772								.map_err(|()| msgs::DecodeError::InvalidValue)?
2773						},
2774						None if payment_preimage.is_some() => {
2775							PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap())
2776						},
2777						None => return Err(msgs::DecodeError::InvalidValue),
2778					};
2779
2780					let receiving_channel_ids = receiving_channel_ids_opt
2781						.or_else(|| {
2782							receiving_channel_id_legacy
2783								.map(|chan_id| vec![(chan_id, receiving_user_channel_id_legacy)])
2784						})
2785						.unwrap_or_default();
2786
2787					Ok(Some(Event::PaymentClaimable {
2788						receiver_node_id,
2789						payment_hash,
2790						amount_msat,
2791						counterparty_skimmed_fee_msat: counterparty_skimmed_fee_msat_opt
2792							.unwrap_or(0),
2793						purpose,
2794						receiving_channel_ids,
2795						claim_deadline,
2796						onion_fields,
2797						payment_id,
2798					}))
2799				};
2800				f()
2801			},
2802			2u8 => {
2803				let mut f = || {
2804					let mut payment_preimage = PaymentPreimage([0; 32]);
2805					let mut payment_hash = None;
2806					let mut payment_id = None;
2807					let mut amount_msat = None;
2808					let mut fee_paid_msat = None;
2809					let mut bolt12_invoice = None;
2810					read_tlv_fields!(reader, {
2811						(0, payment_preimage, required),
2812						(1, payment_hash, option),
2813						(3, payment_id, option),
2814						(5, fee_paid_msat, option),
2815						(7, amount_msat, option),
2816						(9, bolt12_invoice, option),
2817					});
2818					if payment_hash.is_none() {
2819						payment_hash = Some(PaymentHash(
2820							Sha256::hash(&payment_preimage.0[..]).to_byte_array(),
2821						));
2822					}
2823					Ok(Some(Event::PaymentSent {
2824						payment_id,
2825						payment_preimage,
2826						payment_hash: payment_hash.unwrap(),
2827						amount_msat,
2828						fee_paid_msat,
2829						bolt12_invoice,
2830					}))
2831				};
2832				f()
2833			},
2834			3u8 => {
2835				let mut f = || {
2836					#[cfg(any(test, feature = "_test_utils"))]
2837					let error_code = Readable::read(reader)?;
2838					#[cfg(any(test, feature = "_test_utils"))]
2839					let error_data = Readable::read(reader)?;
2840					let mut payment_hash = PaymentHash([0; 32]);
2841					let mut payment_failed_permanently = false;
2842					let mut network_update = None;
2843					let mut blinded_tail: Option<BlindedTail> = None;
2844					let mut path: Option<Vec<RouteHop>> = Some(vec![]);
2845					let mut short_channel_id = None;
2846					let mut payment_id = None;
2847					let mut failure_opt = None;
2848					let mut hold_times = None;
2849					read_tlv_fields!(reader, {
2850						(0, payment_hash, required),
2851						(1, network_update, upgradable_option),
2852						(2, payment_failed_permanently, required),
2853						(4, blinded_tail, option),
2854						// Added as a part of LDK 0.0.101 and always filled in since.
2855						// Defaults to an empty Vec, though likely should have been `Option`al.
2856						(5, path, optional_vec),
2857						(7, short_channel_id, option),
2858						(11, payment_id, option),
2859						(13, failure_opt, upgradable_option),
2860						(15, hold_times, optional_vec),
2861					});
2862					let hold_times = hold_times.unwrap_or(Vec::new());
2863					let failure =
2864						failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
2865					Ok(Some(Event::PaymentPathFailed {
2866						payment_id,
2867						payment_hash,
2868						payment_failed_permanently,
2869						failure,
2870						path: Path { hops: path.unwrap(), blinded_tail },
2871						short_channel_id,
2872						#[cfg(any(test, feature = "_test_utils"))]
2873						error_code,
2874						#[cfg(any(test, feature = "_test_utils"))]
2875						error_data,
2876						hold_times,
2877					}))
2878				};
2879				f()
2880			},
2881			4u8 => Ok(None),
2882			5u8 => {
2883				let mut f = || {
2884					let mut outputs = WithoutLength(Vec::new());
2885					let mut channel_id: Option<ChannelId> = None;
2886					let mut counterparty_node_id: Option<PublicKey> = None;
2887					read_tlv_fields!(reader, {
2888						(0, outputs, required),
2889						(1, channel_id, option),
2890						(3, counterparty_node_id, option),
2891					});
2892					Ok(Some(Event::SpendableOutputs {
2893						outputs: outputs.0,
2894						channel_id,
2895						counterparty_node_id,
2896					}))
2897				};
2898				f()
2899			},
2900			6u8 => {
2901				let mut payment_hash = PaymentHash([0; 32]);
2902				let mut intercept_id = InterceptId([0; 32]);
2903				let mut requested_next_hop_scid =
2904					InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
2905				let mut inbound_amount_msat = 0;
2906				let mut expected_outbound_amount_msat = 0;
2907				let mut outgoing_htlc_expiry_block_height = None;
2908				read_tlv_fields!(reader, {
2909					(0, intercept_id, required),
2910					(1, outgoing_htlc_expiry_block_height, option),
2911					(2, requested_next_hop_scid, required),
2912					(4, payment_hash, required),
2913					(6, inbound_amount_msat, required),
2914					(8, expected_outbound_amount_msat, required),
2915				});
2916				let next_scid = match requested_next_hop_scid {
2917					InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid,
2918				};
2919				Ok(Some(Event::HTLCIntercepted {
2920					payment_hash,
2921					requested_next_hop_scid: next_scid,
2922					inbound_amount_msat,
2923					expected_outbound_amount_msat,
2924					intercept_id,
2925					outgoing_htlc_expiry_block_height,
2926				}))
2927			},
2928			7u8 => {
2929				let mut f = || {
2930					// Legacy values that have been replaced by prev_htlcs and next_htlcs.
2931					let mut prev_channel_id_legacy = None;
2932					let mut next_channel_id_legacy = None;
2933					let mut prev_user_channel_id_legacy = None;
2934					let mut next_user_channel_id_legacy = None;
2935					let mut prev_node_id_legacy = None;
2936					let mut next_node_id_legacy = None;
2937
2938					let mut total_fee_earned_msat = None;
2939					let mut skimmed_fee_msat = None;
2940					let mut claim_from_onchain_tx = false;
2941					let mut outbound_amount_forwarded_msat = 0;
2942					let mut prev_htlcs = vec![];
2943					let mut next_htlcs = vec![];
2944					read_tlv_fields!(reader, {
2945						(0, total_fee_earned_msat, option),
2946						(1, prev_channel_id_legacy, option),
2947						(2, claim_from_onchain_tx, required),
2948						(3, next_channel_id_legacy, option),
2949						(5, outbound_amount_forwarded_msat, required),
2950						(7, skimmed_fee_msat, option),
2951						(9, prev_user_channel_id_legacy, option),
2952						(11, next_user_channel_id_legacy, option),
2953						(13, prev_node_id_legacy, option),
2954						(15, next_node_id_legacy, option),
2955						// We never expect prev/next_channel_id_legacy to be None because this field
2956						// was only None for versions before 0.0.107 and we do not allow upgrades
2957						// with pending forwards to 0.1 for any version 0.0.123 or earlier.
2958						(17, prev_htlcs, (default_value, vec![InboundHTLCLocator{
2959							channel_id: prev_channel_id_legacy.ok_or(DecodeError::InvalidValue)?,
2960							htlc_id: None,
2961							amount_msat: total_fee_earned_msat
2962								.map(|fee| outbound_amount_forwarded_msat + fee),
2963							user_channel_id: prev_user_channel_id_legacy,
2964							node_id: prev_node_id_legacy,
2965						}])),
2966						(19, next_htlcs, (default_value, vec![OutboundHTLCLocator{
2967							channel_id: next_channel_id_legacy.ok_or(DecodeError::InvalidValue)?,
2968							amount_msat: Some(outbound_amount_forwarded_msat),
2969							user_channel_id: next_user_channel_id_legacy,
2970							node_id: next_node_id_legacy,
2971						}])),
2972					});
2973					Ok(Some(Event::PaymentForwarded {
2974						prev_htlcs,
2975						next_htlcs,
2976						total_fee_earned_msat,
2977						skimmed_fee_msat,
2978						claim_from_onchain_tx,
2979						outbound_amount_forwarded_msat,
2980					}))
2981				};
2982				f()
2983			},
2984			9u8 => {
2985				let mut f = || {
2986					let mut channel_id = ChannelId::new_zero();
2987					let mut reason = UpgradableRequired(None);
2988					let mut user_channel_id_low_opt: Option<u64> = None;
2989					let mut user_channel_id_high_opt: Option<u64> = None;
2990					let mut counterparty_node_id = None;
2991					let mut channel_capacity_sats = None;
2992					let mut channel_funding_txo = None;
2993					let mut last_local_balance_msat = None;
2994					read_tlv_fields!(reader, {
2995						(0, channel_id, required),
2996						(1, user_channel_id_low_opt, option),
2997						(2, reason, upgradable_required),
2998						(3, user_channel_id_high_opt, option),
2999						(5, counterparty_node_id, option),
3000						(7, channel_capacity_sats, option),
3001						(9, channel_funding_txo, option),
3002						(11, last_local_balance_msat, option)
3003					});
3004
3005					// `user_channel_id` used to be a single u64 value. In order to remain
3006					// backwards compatible with versions prior to 0.0.113, the u128 is serialized
3007					// as two separate u64 values.
3008					let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128)
3009						+ ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
3010
3011					Ok(Some(Event::ChannelClosed {
3012						channel_id,
3013						user_channel_id,
3014						reason: _init_tlv_based_struct_field!(reason, upgradable_required),
3015						counterparty_node_id,
3016						channel_capacity_sats,
3017						channel_funding_txo,
3018						last_local_balance_msat,
3019					}))
3020				};
3021				f()
3022			},
3023			11u8 => {
3024				let mut f = || {
3025					let mut channel_id = ChannelId::new_zero();
3026					let mut transaction: Option<Transaction> = None;
3027					let mut funding_info: Option<FundingInfo> = None;
3028					read_tlv_fields!(reader, {
3029						(0, channel_id, required),
3030						(2, transaction, option),
3031						(4, funding_info, option),
3032					});
3033
3034					let funding_info = if let Some(tx) = transaction {
3035						FundingInfo::Tx { transaction: tx }
3036					} else {
3037						funding_info.ok_or(msgs::DecodeError::InvalidValue)?
3038					};
3039					Ok(Some(Event::DiscardFunding { channel_id, funding_info }))
3040				};
3041				f()
3042			},
3043			13u8 => {
3044				let mut f = || {
3045					_init_and_read_len_prefixed_tlv_fields!(reader, {
3046						(0, payment_id, required),
3047						(1, hold_times, optional_vec),
3048						(2, payment_hash, option),
3049						(4, path, required_vec),
3050						(6, blinded_tail, option),
3051					});
3052
3053					let hold_times = hold_times.unwrap_or(Vec::new());
3054
3055					Ok(Some(Event::PaymentPathSuccessful {
3056						payment_id: payment_id.0.unwrap(),
3057						payment_hash,
3058						path: Path { hops: path, blinded_tail },
3059						hold_times,
3060					}))
3061				};
3062				f()
3063			},
3064			15u8 => {
3065				let mut f = || {
3066					let mut payment_hash = PaymentHash([0; 32]);
3067					let mut payment_id = PaymentId([0; 32]);
3068					let mut reason = None;
3069					let mut legacy_reason = None;
3070					let mut invoice_received: Option<bool> = None;
3071					read_tlv_fields!(reader, {
3072						(0, payment_id, required),
3073						(1, legacy_reason, upgradable_option),
3074						(2, payment_hash, required),
3075						(3, invoice_received, option),
3076						(5, reason, upgradable_option),
3077					});
3078					let payment_hash = match invoice_received {
3079						Some(invoice_received) => invoice_received.then(|| payment_hash),
3080						None => (payment_hash != PaymentHash([0; 32])).then(|| payment_hash),
3081					};
3082					let reason = reason.or(legacy_reason);
3083					Ok(Some(Event::PaymentFailed {
3084						payment_id,
3085						payment_hash,
3086						reason: _init_tlv_based_struct_field!(reason, upgradable_option),
3087					}))
3088				};
3089				f()
3090			},
3091			17u8 => {
3092				// Value 17 is used for `Event::OpenChannelRequest`.
3093				Ok(None)
3094			},
3095			19u8 => {
3096				let mut f = || {
3097					let mut payment_hash = PaymentHash([0; 32]);
3098					let mut purpose = UpgradableRequired(None);
3099					let mut amount_msat = 0;
3100					let mut receiver_node_id = None;
3101					let mut htlcs: Option<Vec<ClaimedHTLC>> = Some(vec![]);
3102					let mut sender_intended_total_msat: Option<u64> = None;
3103					let mut onion_fields = None;
3104					let mut payment_id = None;
3105					read_tlv_fields!(reader, {
3106						(0, payment_hash, required),
3107						(1, receiver_node_id, option),
3108						(2, purpose, upgradable_required),
3109						(4, amount_msat, required),
3110						(5, htlcs, optional_vec),
3111						(7, sender_intended_total_msat, option),
3112						(9, onion_fields, (option: ReadableArgs,
3113							sender_intended_total_msat.unwrap_or(amount_msat))),
3114						(11, payment_id, option),
3115					});
3116					Ok(Some(Event::PaymentClaimed {
3117						receiver_node_id,
3118						payment_hash,
3119						purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
3120						amount_msat,
3121						htlcs: htlcs.unwrap_or_default(),
3122						sender_intended_total_msat,
3123						onion_fields,
3124						payment_id,
3125					}))
3126				};
3127				f()
3128			},
3129			21u8 => {
3130				let mut f = || {
3131					_init_and_read_len_prefixed_tlv_fields!(reader, {
3132						(0, payment_id, required),
3133						(2, payment_hash, required),
3134						(4, path, required_vec),
3135						(6, blinded_tail, option),
3136					});
3137					Ok(Some(Event::ProbeSuccessful {
3138						payment_id: payment_id.0.unwrap(),
3139						payment_hash: payment_hash.0.unwrap(),
3140						path: Path { hops: path, blinded_tail },
3141					}))
3142				};
3143				f()
3144			},
3145			23u8 => {
3146				let mut f = || {
3147					_init_and_read_len_prefixed_tlv_fields!(reader, {
3148						(0, payment_id, required),
3149						(2, payment_hash, required),
3150						(4, path, required_vec),
3151						(6, short_channel_id, option),
3152						(8, blinded_tail, option),
3153					});
3154					Ok(Some(Event::ProbeFailed {
3155						payment_id: payment_id.0.unwrap(),
3156						payment_hash: payment_hash.0.unwrap(),
3157						path: Path { hops: path, blinded_tail },
3158						short_channel_id,
3159					}))
3160				};
3161				f()
3162			},
3163			25u8 => {
3164				let mut f = || {
3165					let mut prev_channel_id_legacy = ChannelId::new_zero();
3166					let mut failure_reason = None;
3167					let mut failure_type_opt = UpgradableRequired(None);
3168					let mut prev_channel_ids = vec![];
3169					read_tlv_fields!(reader, {
3170						(0, prev_channel_id_legacy, required),
3171						(1, failure_reason, option),
3172						(2, failure_type_opt, upgradable_required),
3173						(3, prev_channel_ids, (default_value, vec![
3174							prev_channel_id_legacy,
3175						])),
3176					});
3177
3178					// If a legacy HTLCHandlingFailureType::UnknownNextHop was written, upgrade
3179					// it to its new representation, otherwise leave unchanged.
3180					if let Some(HTLCHandlingFailureType::UnknownNextHop {
3181						requested_forward_scid,
3182					}) = failure_type_opt.0
3183					{
3184						failure_type_opt.0 = Some(HTLCHandlingFailureType::InvalidForward {
3185							requested_forward_scid,
3186						});
3187						failure_reason = Some(LocalHTLCFailureReason::UnknownNextPeer.into());
3188					}
3189					Ok(Some(Event::HTLCHandlingFailed {
3190						prev_channel_ids,
3191						failure_type: _init_tlv_based_struct_field!(
3192							failure_type_opt,
3193							upgradable_required
3194						),
3195						failure_reason,
3196					}))
3197				};
3198				f()
3199			},
3200			27u8 => Ok(None),
3201			29u8 => {
3202				let mut f = || {
3203					let mut channel_id = ChannelId::new_zero();
3204					let mut user_channel_id: u128 = 0;
3205					let mut counterparty_node_id = RequiredWrapper(None);
3206					let mut funding_txo = None;
3207					let mut channel_type = RequiredWrapper(None);
3208					read_tlv_fields!(reader, {
3209						(0, channel_id, required),
3210						(1, funding_txo, option),
3211						(2, user_channel_id, required),
3212						(4, counterparty_node_id, required),
3213						(6, channel_type, required),
3214					});
3215
3216					Ok(Some(Event::ChannelReady {
3217						channel_id,
3218						user_channel_id,
3219						counterparty_node_id: counterparty_node_id.0.unwrap(),
3220						funding_txo,
3221						channel_type: channel_type.0.unwrap(),
3222					}))
3223				};
3224				f()
3225			},
3226			31u8 => {
3227				let mut f = || {
3228					let mut channel_id = ChannelId::new_zero();
3229					let mut user_channel_id: u128 = 0;
3230					let mut former_temporary_channel_id = None;
3231					let mut counterparty_node_id = RequiredWrapper(None);
3232					let mut funding_txo = RequiredWrapper(None);
3233					let mut channel_type = None;
3234					let mut funding_redeem_script = None;
3235					read_tlv_fields!(reader, {
3236						(0, channel_id, required),
3237						(1, channel_type, option),
3238						(2, user_channel_id, required),
3239						(4, former_temporary_channel_id, required),
3240						(6, counterparty_node_id, required),
3241						(8, funding_txo, required),
3242						(9, funding_redeem_script, option),
3243					});
3244
3245					Ok(Some(Event::ChannelPending {
3246						channel_id,
3247						user_channel_id,
3248						former_temporary_channel_id,
3249						counterparty_node_id: counterparty_node_id.0.unwrap(),
3250						funding_txo: funding_txo.0.unwrap(),
3251						channel_type,
3252						funding_redeem_script,
3253					}))
3254				};
3255				f()
3256			},
3257			// This was Event::InvoiceRequestFailed prior to version 0.0.124.
3258			33u8 => {
3259				let mut f = || {
3260					_init_and_read_len_prefixed_tlv_fields!(reader, {
3261						(0, payment_id, required),
3262					});
3263					Ok(Some(Event::PaymentFailed {
3264						payment_id: payment_id.0.unwrap(),
3265						payment_hash: None,
3266						reason: Some(PaymentFailureReason::InvoiceRequestExpired),
3267					}))
3268				};
3269				f()
3270			},
3271			// Note that we do not write a length-prefixed TLV for ConnectionNeeded events.
3272			35u8 => Ok(None),
3273			37u8 => {
3274				let mut f = || {
3275					_init_and_read_len_prefixed_tlv_fields!(reader, {
3276						(0, peer_node_id, option),
3277						(1, next_hop, option),
3278						(2, message, required),
3279						(3, prev_hop, option),
3280					});
3281
3282					let next_hop = next_hop
3283						.or(peer_node_id.map(NextMessageHop::NodeId))
3284						.ok_or(msgs::DecodeError::InvalidValue)?;
3285					Ok(Some(Event::OnionMessageIntercepted {
3286						prev_hop,
3287						next_hop,
3288						message: message.0.unwrap(),
3289					}))
3290				};
3291				f()
3292			},
3293			39u8 => {
3294				let mut f = || {
3295					_init_and_read_len_prefixed_tlv_fields!(reader, {
3296						(0, peer_node_id, required),
3297					});
3298					Ok(Some(Event::OnionMessagePeerConnected {
3299						peer_node_id: peer_node_id.0.unwrap(),
3300					}))
3301				};
3302				f()
3303			},
3304			41u8 => {
3305				let mut f = || {
3306					_init_and_read_len_prefixed_tlv_fields!(reader, {
3307						(0, payment_id, required),
3308						(2, invoice, required),
3309						(4, context, option),
3310						(6, responder, option),
3311					});
3312					Ok(Some(Event::InvoiceReceived {
3313						payment_id: payment_id.0.unwrap(),
3314						invoice: invoice.0.unwrap(),
3315						context,
3316						responder,
3317					}))
3318				};
3319				f()
3320			},
3321			43u8 => {
3322				let mut channel_id = RequiredWrapper(None);
3323				let mut user_channel_id = RequiredWrapper(None);
3324				let mut funding_txo = RequiredWrapper(None);
3325				let mut counterparty_node_id = RequiredWrapper(None);
3326				let mut former_temporary_channel_id = RequiredWrapper(None);
3327				read_tlv_fields!(reader, {
3328					(0, channel_id, required),
3329					(2, user_channel_id, required),
3330					(4, funding_txo, required),
3331					(6, counterparty_node_id, required),
3332					(8, former_temporary_channel_id, required)
3333				});
3334				Ok(Some(Event::FundingTxBroadcastSafe {
3335					channel_id: channel_id.0.unwrap(),
3336					user_channel_id: user_channel_id.0.unwrap(),
3337					funding_txo: funding_txo.0.unwrap(),
3338					counterparty_node_id: counterparty_node_id.0.unwrap(),
3339					former_temporary_channel_id: former_temporary_channel_id.0.unwrap(),
3340				}))
3341			},
3342			// Note that we do not write a length-prefixed TLV for PersistStaticInvoice events.
3343			45u8 => Ok(None),
3344			// Note that we do not write a length-prefixed TLV for StaticInvoiceRequested events.
3345			47u8 => Ok(None),
3346			// Note that we do not write a length-prefixed TLV for FundingTransactionReadyForSigning events.
3347			49u8 => Ok(None),
3348			50u8 => {
3349				let mut f = || {
3350					_init_and_read_len_prefixed_tlv_fields!(reader, {
3351						(1, channel_id, required),
3352						(3, channel_type, required),
3353						(5, user_channel_id, required),
3354						(7, counterparty_node_id, required),
3355						(9, new_funding_txo, required),
3356						(11, new_funding_redeem_script, required),
3357					});
3358
3359					Ok(Some(Event::SpliceNegotiated {
3360						channel_id: channel_id.0.unwrap(),
3361						user_channel_id: user_channel_id.0.unwrap(),
3362						counterparty_node_id: counterparty_node_id.0.unwrap(),
3363						new_funding_txo: new_funding_txo.0.unwrap(),
3364						channel_type: channel_type.0.unwrap(),
3365						new_funding_redeem_script: new_funding_redeem_script.0.unwrap(),
3366					}))
3367				};
3368				f()
3369			},
3370			52u8 => {
3371				let mut f = || {
3372					// Types 11 and 13 were written by 0.2 with the same encoding. When type 17 is
3373					// absent (an event written by 0.2), they are dropped along with the missing
3374					// contribution. Types 3 and 9 were `channel_type` and `abandoned_funding_txo`
3375					// in 0.2 and must not be reused.
3376					_init_and_read_len_prefixed_tlv_fields!(reader, {
3377						(1, channel_id, required),
3378						(5, user_channel_id, required),
3379						(7, counterparty_node_id, required),
3380						(11, contributed_inputs, optional_vec),
3381						(13, contributed_outputs, optional_vec),
3382						(15, reason, upgradable_option),
3383						(17, contribution, option),
3384					});
3385
3386					let contribution = contribution.map(|contribution| FailedSpliceContribution {
3387						contributed_inputs: contributed_inputs.unwrap_or(Vec::new()),
3388						contributed_outputs: contributed_outputs.unwrap_or(Vec::new()),
3389						contribution,
3390					});
3391					Ok(Some(Event::SpliceNegotiationFailed {
3392						channel_id: channel_id.0.unwrap(),
3393						user_channel_id: user_channel_id.0.unwrap(),
3394						counterparty_node_id: counterparty_node_id.0.unwrap(),
3395						reason: reason.unwrap_or(NegotiationFailureReason::Unknown),
3396						contribution,
3397					}))
3398				};
3399				f()
3400			},
3401			53u8 => {
3402				let mut f = || {
3403					_init_and_read_len_prefixed_tlv_fields!(reader, {
3404						(1, channel_id, required),
3405						(3, funding_info, required),
3406					});
3407
3408					Ok(Some(Event::DiscardFunding {
3409						channel_id: channel_id.0.unwrap(),
3410						funding_info: funding_info.0.unwrap(),
3411					}))
3412				};
3413				f()
3414			},
3415			// Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
3416			// Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
3417			// reads.
3418			x if x % 2 == 1 => {
3419				// If the event is of unknown type, assume it was written with `write_tlv_fields`,
3420				// which prefixes the whole thing with a length BigSize. Because the event is
3421				// odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
3422				// fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
3423				// exactly the number of bytes specified, ignoring them entirely.
3424				let tlv_len: BigSize = Readable::read(reader)?;
3425				FixedLengthReader::new(reader, tlv_len.0)
3426					.eat_remaining()
3427					.map_err(|_| msgs::DecodeError::ShortRead)?;
3428				Ok(None)
3429			},
3430			_ => Err(msgs::DecodeError::InvalidValue),
3431		}
3432	}
3433}
3434
3435#[cfg(test)]
3436mod tests {
3437	use super::*;
3438
3439	#[test]
3440	fn legacy_payment_forwarded_preserves_unknown_inbound_htlc_amount() {
3441		let prev_channel_id = ChannelId::from_bytes([1; 32]);
3442		let next_channel_id = ChannelId::from_bytes([2; 32]);
3443		let mut encoded_legacy_event = vec![
3444			7,  // Event::PaymentForwarded
3445			81, // TLV stream length
3446			1, 32, // prev_channel_id
3447		];
3448		encoded_legacy_event.extend_from_slice(&[1; 32]);
3449		encoded_legacy_event.extend_from_slice(&[2, 1, 0]); // claim_from_onchain_tx
3450		encoded_legacy_event.extend_from_slice(&[3, 32]); // next_channel_id
3451		encoded_legacy_event.extend_from_slice(&[2; 32]);
3452		// outbound_amount_forwarded_msat
3453		encoded_legacy_event.extend_from_slice(&[5, 8, 0, 0, 0, 0, 0, 45, 198, 192]);
3454
3455		match Event::read(&mut &encoded_legacy_event[..]).unwrap().unwrap() {
3456			Event::PaymentForwarded {
3457				prev_htlcs,
3458				next_htlcs,
3459				total_fee_earned_msat,
3460				outbound_amount_forwarded_msat,
3461				..
3462			} => {
3463				assert_eq!(total_fee_earned_msat, None);
3464				assert_eq!(outbound_amount_forwarded_msat, 3_000_000);
3465				assert_eq!(prev_htlcs.len(), 1);
3466				assert_eq!(prev_htlcs[0].channel_id, prev_channel_id);
3467				assert_eq!(prev_htlcs[0].amount_msat, None);
3468				assert_eq!(prev_htlcs[0].htlc_id, None);
3469				assert_eq!(next_htlcs.len(), 1);
3470				assert_eq!(next_htlcs[0].channel_id, next_channel_id);
3471				assert_eq!(next_htlcs[0].amount_msat, Some(3_000_000));
3472			},
3473			_ => panic!("expected PaymentForwarded event"),
3474		}
3475	}
3476}
3477
3478/// A trait indicating an object may generate events.
3479///
3480/// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
3481///
3482/// Implementations of this trait may also feature an async version of event handling, as shown with
3483/// [`ChannelManager::process_pending_events_async`] and
3484/// [`ChainMonitor::process_pending_events_async`].
3485///
3486/// # Requirements
3487///
3488/// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
3489/// event since the last invocation.
3490///
3491/// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
3492/// and replay any unhandled events on startup. An [`Event`] is considered handled when
3493/// [`process_pending_events`] returns `Ok(())`, thus handlers MUST fully handle [`Event`]s and
3494/// persist any relevant changes to disk *before* returning `Ok(())`. In case of an error (e.g.,
3495/// persistence failure) implementors should return `Err(ReplayEvent())`, signalling to the
3496/// [`EventsProvider`] to replay unhandled events on the next invocation (generally immediately).
3497/// Note that some events might not be replayed, please refer to the documentation for
3498/// the individual [`Event`] variants for more detail.
3499///
3500/// Further, because an application may crash between an [`Event`] being handled and the
3501/// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
3502/// effect, [`Event`]s may be replayed.
3503///
3504/// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
3505/// consult the provider's documentation on the implication of processing events and how a handler
3506/// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
3507/// [`ChainMonitor::process_pending_events`]).
3508///
3509/// (C-not implementable) As there is likely no reason for a user to implement this trait on their
3510/// own type(s).
3511///
3512/// [`process_pending_events`]: Self::process_pending_events
3513/// [`handle_event`]: EventHandler::handle_event
3514/// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
3515/// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
3516/// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
3517/// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
3518pub trait EventsProvider {
3519	/// Processes any events generated since the last call using the given event handler.
3520	///
3521	/// See the trait-level documentation for requirements.
3522	fn process_pending_events<H: Deref>(&self, handler: H)
3523	where
3524		H::Target: EventHandler;
3525}
3526
3527/// An error type that may be returned to LDK in order to safely abort event handling if it can't
3528/// currently succeed (e.g., due to a persistence failure).
3529///
3530/// Depending on the type, LDK may ensure the event is persisted and will eventually be replayed.
3531/// Please refer to the documentation of each [`Event`] variant for more details.
3532#[derive(Clone, Copy, Debug)]
3533pub struct ReplayEvent();
3534
3535/// A trait implemented for objects handling events from [`EventsProvider`].
3536///
3537/// An async variation also exists for implementations of [`EventsProvider`] that support async
3538/// event handling. The async event handler should satisfy the generic bounds: `F:
3539/// core::future::Future<Output = Result<(), ReplayEvent>>, H: Fn(Event) -> F`.
3540pub trait EventHandler {
3541	/// Handles the given [`Event`].
3542	///
3543	/// See [`EventsProvider`] for details that must be considered when implementing this method.
3544	fn handle_event(&self, event: Event) -> Result<(), ReplayEvent>;
3545}
3546
3547impl<F> EventHandler for F
3548where
3549	F: Fn(Event) -> Result<(), ReplayEvent>,
3550{
3551	fn handle_event(&self, event: Event) -> Result<(), ReplayEvent> {
3552		self(event)
3553	}
3554}
3555
3556impl<T: EventHandler> EventHandler for Arc<T> {
3557	fn handle_event(&self, event: Event) -> Result<(), ReplayEvent> {
3558		self.deref().handle_event(event)
3559	}
3560}