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::OffersContext;
22use crate::blinded_path::payment::{Bolt12OfferContext, Bolt12RefundContext, PaymentContext, PaymentContextRef};
23use crate::chain::transaction;
24use crate::ln::channelmanager::{InterceptId, PaymentId, RecipientOnionFields};
25use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
26use crate::types::features::ChannelTypeFeatures;
27use crate::ln::msgs;
28use crate::ln::types::ChannelId;
29use crate::types::payment::{PaymentPreimage, PaymentHash, PaymentSecret};
30use crate::offers::invoice::Bolt12Invoice;
31use crate::onion_message::messenger::Responder;
32use crate::routing::gossip::NetworkUpdate;
33use crate::routing::router::{BlindedTail, Path, RouteHop, RouteParameters};
34use crate::sign::SpendableOutputDescriptor;
35use crate::util::errors::APIError;
36use crate::util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, RequiredWrapper, UpgradableRequired, WithoutLength};
37use crate::util::string::UntrustedString;
38
39use bitcoin::{Transaction, OutPoint};
40use bitcoin::script::ScriptBuf;
41use bitcoin::hashes::Hash;
42use bitcoin::hashes::sha256::Hash as Sha256;
43use bitcoin::secp256k1::PublicKey;
44use crate::io;
45use core::time::Duration;
46use core::ops::Deref;
47use crate::sync::Arc;
48
49#[allow(unused_imports)]
50use crate::prelude::*;
51
52/// `FundingInfo` holds information about a channel's funding transaction.
53///
54/// When LDK is set to manual propagation of the funding transaction
55/// (via [`ChannelManager::unsafe_manual_funding_transaction_generated`),
56/// LDK does not have the full transaction data. Instead, the `OutPoint`
57/// for the funding is provided here.
58///
59/// [`ChannelManager::unsafe_manual_funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::unsafe_manual_funding_transaction_generated
60#[derive(Debug, PartialEq, Eq, Clone)]
61pub enum FundingInfo {
62	/// The full funding `Transaction`.
63	Tx {
64		/// The funding transaction
65		transaction: Transaction
66	},
67	/// The `OutPoint` of the funding.
68	OutPoint {
69		/// The outpoint of the funding
70		outpoint: transaction::OutPoint
71	},
72}
73
74impl_writeable_tlv_based_enum!(FundingInfo,
75	(0, Tx) => {
76		(0, transaction, required)
77	},
78	(1, OutPoint) => {
79		(1, outpoint, required)
80	}
81);
82
83
84/// Some information provided on receipt of payment depends on whether the payment received is a
85/// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
86#[derive(Clone, Debug, PartialEq, Eq)]
87pub enum PaymentPurpose {
88	/// A payment for a BOLT 11 invoice.
89	Bolt11InvoicePayment {
90		/// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
91		/// [`ChannelManager::create_inbound_payment`]. When handling [`Event::PaymentClaimable`],
92		/// this can be passed directly to [`ChannelManager::claim_funds`] to claim the payment. No
93		/// action is needed when seen in [`Event::PaymentClaimed`].
94		///
95		/// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
96		/// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
97		payment_preimage: Option<PaymentPreimage>,
98		/// The "payment secret". This authenticates the sender to the recipient, preventing a
99		/// number of deanonymization attacks during the routing process.
100		/// It is provided here for your reference, however its accuracy is enforced directly by
101		/// [`ChannelManager`] using the values you previously provided to
102		/// [`ChannelManager::create_inbound_payment`] or
103		/// [`ChannelManager::create_inbound_payment_for_hash`].
104		///
105		/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
106		/// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
107		/// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
108		payment_secret: PaymentSecret,
109	},
110	/// A payment for a BOLT 12 [`Offer`].
111	///
112	/// [`Offer`]: crate::offers::offer::Offer
113	Bolt12OfferPayment {
114		/// The preimage to the payment hash. When handling [`Event::PaymentClaimable`], this can be
115		/// passed directly to [`ChannelManager::claim_funds`], if provided. No action is needed
116		/// when seen in [`Event::PaymentClaimed`].
117		///
118		/// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
119		payment_preimage: Option<PaymentPreimage>,
120		/// The secret used to authenticate the sender to the recipient, preventing a number of
121		/// de-anonymization attacks while routing a payment.
122		///
123		/// See [`PaymentPurpose::Bolt11InvoicePayment::payment_secret`] for further details.
124		payment_secret: PaymentSecret,
125		/// The context of the payment such as information about the corresponding [`Offer`] and
126		/// [`InvoiceRequest`].
127		///
128		/// This includes the Human Readable Name which the sender indicated they were paying to,
129		/// for possible recipient disambiguation if you're using a single wildcard DNS entry to
130		/// resolve to many recipients.
131		///
132		/// [`Offer`]: crate::offers::offer::Offer
133		/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
134		payment_context: Bolt12OfferContext,
135	},
136	/// A payment for a BOLT 12 [`Refund`].
137	///
138	/// [`Refund`]: crate::offers::refund::Refund
139	Bolt12RefundPayment {
140		/// The preimage to the payment hash. When handling [`Event::PaymentClaimable`], this can be
141		/// passed directly to [`ChannelManager::claim_funds`], if provided. No action is needed
142		/// when seen in [`Event::PaymentClaimed`].
143		///
144		/// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
145		payment_preimage: Option<PaymentPreimage>,
146		/// The secret used to authenticate the sender to the recipient, preventing a number of
147		/// de-anonymization attacks while routing a payment.
148		///
149		/// See [`PaymentPurpose::Bolt11InvoicePayment::payment_secret`] for further details.
150		payment_secret: PaymentSecret,
151		/// The context of the payment such as information about the corresponding [`Refund`].
152		///
153		/// [`Refund`]: crate::offers::refund::Refund
154		payment_context: Bolt12RefundContext,
155	},
156	/// Because this is a spontaneous payment, the payer generated their own preimage rather than us
157	/// (the payee) providing a preimage.
158	SpontaneousPayment(PaymentPreimage),
159}
160
161impl PaymentPurpose {
162	/// Returns the preimage for this payment, if it is known.
163	pub fn preimage(&self) -> Option<PaymentPreimage> {
164		match self {
165			PaymentPurpose::Bolt11InvoicePayment { payment_preimage, .. } => *payment_preimage,
166			PaymentPurpose::Bolt12OfferPayment { payment_preimage, .. } => *payment_preimage,
167			PaymentPurpose::Bolt12RefundPayment { payment_preimage, .. } => *payment_preimage,
168			PaymentPurpose::SpontaneousPayment(preimage) => Some(*preimage),
169		}
170	}
171
172	pub(crate) fn is_keysend(&self) -> bool {
173		match self {
174			PaymentPurpose::Bolt11InvoicePayment { .. } => false,
175			PaymentPurpose::Bolt12OfferPayment { .. } => false,
176			PaymentPurpose::Bolt12RefundPayment { .. } => false,
177			PaymentPurpose::SpontaneousPayment(..) => true,
178		}
179	}
180
181	pub(crate) fn from_parts(
182		payment_preimage: Option<PaymentPreimage>, payment_secret: PaymentSecret,
183		payment_context: Option<PaymentContext>,
184	) -> Self {
185		match payment_context {
186			None => {
187				PaymentPurpose::Bolt11InvoicePayment {
188					payment_preimage,
189					payment_secret,
190				}
191			},
192			Some(PaymentContext::Bolt12Offer(context)) => {
193				PaymentPurpose::Bolt12OfferPayment {
194					payment_preimage,
195					payment_secret,
196					payment_context: context,
197				}
198			},
199			Some(PaymentContext::Bolt12Refund(context)) => {
200				PaymentPurpose::Bolt12RefundPayment {
201					payment_preimage,
202					payment_secret,
203					payment_context: context,
204				}
205			},
206		}
207	}
208}
209
210impl_writeable_tlv_based_enum_legacy!(PaymentPurpose,
211	(0, Bolt11InvoicePayment) => {
212		(0, payment_preimage, option),
213		(2, payment_secret, required),
214	},
215	(4, Bolt12OfferPayment) => {
216		(0, payment_preimage, option),
217		(2, payment_secret, required),
218		(4, payment_context, required),
219	},
220	(6, Bolt12RefundPayment) => {
221		(0, payment_preimage, option),
222		(2, payment_secret, required),
223		(4, payment_context, required),
224	},
225	;
226	(2, SpontaneousPayment)
227);
228
229/// Information about an HTLC that is part of a payment that can be claimed.
230#[derive(Clone, Debug, PartialEq, Eq)]
231pub struct ClaimedHTLC {
232	/// The `channel_id` of the channel over which the HTLC was received.
233	pub channel_id: ChannelId,
234	/// The `user_channel_id` of the channel over which the HTLC was received. This is the value
235	/// passed in to [`ChannelManager::create_channel`] for outbound channels, or to
236	/// [`ChannelManager::accept_inbound_channel`] for inbound channels if
237	/// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
238	/// `user_channel_id` will be randomized for an inbound channel.
239	///
240	/// This field will be zero for a payment that was serialized prior to LDK version 0.0.117. (This
241	/// should only happen in the case that a payment was claimable prior to LDK version 0.0.117, but
242	/// was not actually claimed until after upgrading.)
243	///
244	/// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
245	/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
246	/// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
247	pub user_channel_id: u128,
248	/// The block height at which this HTLC expires.
249	pub cltv_expiry: u32,
250	/// The amount (in msats) of this part of an MPP.
251	pub value_msat: u64,
252	/// The extra fee our counterparty skimmed off the top of this HTLC, if any.
253	///
254	/// This value will always be 0 for [`ClaimedHTLC`]s serialized with LDK versions prior to
255	/// 0.0.119.
256	pub counterparty_skimmed_fee_msat: u64,
257}
258impl_writeable_tlv_based!(ClaimedHTLC, {
259	(0, channel_id, required),
260	(1, counterparty_skimmed_fee_msat, (default_value, 0u64)),
261	(2, user_channel_id, required),
262	(4, cltv_expiry, required),
263	(6, value_msat, required),
264});
265
266/// When the payment path failure took place and extra details about it. [`PathFailure::OnPath`] may
267/// contain a [`NetworkUpdate`] that needs to be applied to the [`NetworkGraph`].
268///
269/// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
270/// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
271#[derive(Clone, Debug, Eq, PartialEq)]
272pub enum PathFailure {
273	/// We failed to initially send the payment and no HTLC was committed to. Contains the relevant
274	/// error.
275	InitialSend {
276		/// The error surfaced from initial send.
277		err: APIError,
278	},
279	/// A hop on the path failed to forward our payment.
280	OnPath {
281		/// If present, this [`NetworkUpdate`] should be applied to the [`NetworkGraph`] so that routing
282		/// decisions can take into account the update.
283		///
284		/// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
285		/// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
286		network_update: Option<NetworkUpdate>,
287	},
288}
289
290impl_writeable_tlv_based_enum_upgradable!(PathFailure,
291	(0, OnPath) => {
292		(0, network_update, upgradable_option),
293	},
294	(2, InitialSend) => {
295		(0, err, upgradable_required),
296	},
297);
298
299#[derive(Clone, Debug, PartialEq, Eq)]
300/// The reason the channel was closed. See individual variants for more details.
301pub enum ClosureReason {
302	/// Closure generated from receiving a peer error message.
303	///
304	/// Our counterparty may have broadcasted their latest commitment state, and we have
305	/// as well.
306	CounterpartyForceClosed {
307		/// The error which the peer sent us.
308		///
309		/// Be careful about printing the peer_msg, a well-crafted message could exploit
310		/// a security vulnerability in the terminal emulator or the logging subsystem.
311		/// To be safe, use `Display` on `UntrustedString`
312		///
313		/// [`UntrustedString`]: crate::util::string::UntrustedString
314		peer_msg: UntrustedString,
315	},
316	/// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
317	///
318	/// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
319	HolderForceClosed {
320		/// Whether or not the latest transaction was broadcasted when the channel was force
321		/// closed.
322		///
323		/// Channels closed using [`ChannelManager::force_close_broadcasting_latest_txn`] will have
324		/// this field set to true, whereas channels closed using [`ChannelManager::force_close_without_broadcasting_txn`]
325		/// or force-closed prior to being funded will have this field set to false.
326		///
327		/// This will be `None` for objects generated or written by LDK 0.0.123 and
328		/// earlier.
329		///
330		/// [`ChannelManager::force_close_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_broadcasting_latest_txn.
331		/// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn.
332		broadcasted_latest_txn: Option<bool>
333	},
334	/// The channel was closed after negotiating a cooperative close and we've now broadcasted
335	/// the cooperative close transaction. Note the shutdown may have been initiated by us.
336	///
337	/// This was only set in versions of LDK prior to 0.0.122.
338	// Can be removed once we disallow downgrading to 0.0.121
339	LegacyCooperativeClosure,
340	/// The channel was closed after negotiating a cooperative close and we've now broadcasted
341	/// the cooperative close transaction. This indicates that the shutdown was initiated by our
342	/// counterparty.
343	///
344	/// In rare cases where we initiated closure immediately prior to shutting down without
345	/// persisting, this value may be provided for channels we initiated closure for.
346	CounterpartyInitiatedCooperativeClosure,
347	/// The channel was closed after negotiating a cooperative close and we've now broadcasted
348	/// the cooperative close transaction. This indicates that the shutdown was initiated by us.
349	LocallyInitiatedCooperativeClosure,
350	/// A commitment transaction was confirmed on chain, closing the channel. Most likely this
351	/// commitment transaction came from our counterparty, but it may also have come from
352	/// a copy of our own `ChannelMonitor`.
353	CommitmentTxConfirmed,
354	/// The funding transaction failed to confirm in a timely manner on an inbound channel.
355	FundingTimedOut,
356	/// Closure generated from processing an event, likely a HTLC forward/relay/reception.
357	ProcessingError {
358		/// A developer-readable error message which we generated.
359		err: String,
360	},
361	/// The peer disconnected prior to funding completing. In this case the spec mandates that we
362	/// forget the channel entirely - we can attempt again if the peer reconnects.
363	///
364	/// This includes cases where we restarted prior to funding completion, including prior to the
365	/// initial [`ChannelMonitor`] persistence completing.
366	///
367	/// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
368	/// peer because of mutual incompatibility between us and our channel counterparty.
369	///
370	/// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
371	DisconnectedPeer,
372	/// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
373	/// the [`ChannelManager`] deserialized.
374	///
375	/// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
376	/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
377	OutdatedChannelManager,
378	/// The counterparty requested a cooperative close of a channel that had not been funded yet.
379	/// The channel has been immediately closed.
380	CounterpartyCoopClosedUnfundedChannel,
381	/// Another channel in the same funding batch closed before the funding transaction
382	/// was ready to be broadcast.
383	FundingBatchClosure,
384	/// One of our HTLCs timed out in a channel, causing us to force close the channel.
385	HTLCsTimedOut,
386	/// Our peer provided a feerate which violated our required minimum (fetched from our
387	/// [`FeeEstimator`] either as [`ConfirmationTarget::MinAllowedAnchorChannelRemoteFee`] or
388	/// [`ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee`]).
389	///
390	/// [`FeeEstimator`]: crate::chain::chaininterface::FeeEstimator
391	/// [`ConfirmationTarget::MinAllowedAnchorChannelRemoteFee`]: crate::chain::chaininterface::ConfirmationTarget::MinAllowedAnchorChannelRemoteFee
392	/// [`ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee`]: crate::chain::chaininterface::ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee
393	PeerFeerateTooLow {
394		/// The feerate on our channel set by our peer.
395		peer_feerate_sat_per_kw: u32,
396		/// The required feerate we enforce, from our [`FeeEstimator`].
397		///
398		/// [`FeeEstimator`]: crate::chain::chaininterface::FeeEstimator
399		required_feerate_sat_per_kw: u32,
400	},
401}
402
403impl core::fmt::Display for ClosureReason {
404	fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
405		f.write_str("Channel closed because ")?;
406		match self {
407			ClosureReason::CounterpartyForceClosed { peer_msg } => {
408				f.write_fmt(format_args!("counterparty force-closed with message: {}", peer_msg))
409			},
410			ClosureReason::HolderForceClosed { broadcasted_latest_txn } => {
411				f.write_str("user force-closed the channel")?;
412				if let Some(brodcasted) = broadcasted_latest_txn {
413					write!(f, " and {} the latest transaction", if *brodcasted { "broadcasted" } else { "elected not to broadcast" })
414				} else {
415					Ok(())
416				}
417			},
418			ClosureReason::LegacyCooperativeClosure => f.write_str("the channel was cooperatively closed"),
419			ClosureReason::CounterpartyInitiatedCooperativeClosure => f.write_str("the channel was cooperatively closed by our peer"),
420			ClosureReason::LocallyInitiatedCooperativeClosure => f.write_str("the channel was cooperatively closed by us"),
421			ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
422			ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
423			ClosureReason::ProcessingError { err } => {
424				f.write_str("of an exception: ")?;
425				f.write_str(&err)
426			},
427			ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
428			ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
429			ClosureReason::CounterpartyCoopClosedUnfundedChannel => f.write_str("the peer requested the unfunded channel be closed"),
430			ClosureReason::FundingBatchClosure => f.write_str("another channel in the same funding batch closed"),
431			ClosureReason::HTLCsTimedOut => f.write_str("htlcs on the channel timed out"),
432			ClosureReason::PeerFeerateTooLow { peer_feerate_sat_per_kw, required_feerate_sat_per_kw } =>
433				f.write_fmt(format_args!(
434					"peer provided a feerate ({} sat/kw) which was below our lower bound ({} sat/kw)",
435					peer_feerate_sat_per_kw, required_feerate_sat_per_kw,
436				)),
437		}
438	}
439}
440
441impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
442	(0, CounterpartyForceClosed) => { (1, peer_msg, required) },
443	(1, FundingTimedOut) => {},
444	(2, HolderForceClosed) => { (1, broadcasted_latest_txn, option) },
445	(6, CommitmentTxConfirmed) => {},
446	(4, LegacyCooperativeClosure) => {},
447	(8, ProcessingError) => { (1, err, required) },
448	(10, DisconnectedPeer) => {},
449	(12, OutdatedChannelManager) => {},
450	(13, CounterpartyCoopClosedUnfundedChannel) => {},
451	(15, FundingBatchClosure) => {},
452	(17, CounterpartyInitiatedCooperativeClosure) => {},
453	(19, LocallyInitiatedCooperativeClosure) => {},
454	(21, HTLCsTimedOut) => {},
455	(23, PeerFeerateTooLow) => {
456		(0, peer_feerate_sat_per_kw, required),
457		(2, required_feerate_sat_per_kw, required),
458	},
459);
460
461/// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
462#[derive(Clone, Debug, PartialEq, Eq)]
463pub enum HTLCDestination {
464	/// We tried forwarding to a channel but failed to do so. An example of such an instance is when
465	/// there is insufficient capacity in our outbound channel.
466	NextHopChannel {
467		/// The `node_id` of the next node. For backwards compatibility, this field is
468		/// marked as optional, versions prior to 0.0.110 may not always be able to provide
469		/// counterparty node information.
470		node_id: Option<PublicKey>,
471		/// The outgoing `channel_id` between us and the next node.
472		channel_id: ChannelId,
473	},
474	/// Scenario where we are unsure of the next node to forward the HTLC to.
475	UnknownNextHop {
476		/// Short channel id we are requesting to forward an HTLC to.
477		requested_forward_scid: u64,
478	},
479	/// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
480	/// intercept HTLC.
481	InvalidForward {
482		/// Short channel id we are requesting to forward an HTLC to.
483		requested_forward_scid: u64
484	},
485	/// We couldn't decode the incoming onion to obtain the forwarding details.
486	InvalidOnion,
487	/// Failure scenario where an HTLC may have been forwarded to be intended for us,
488	/// but is invalid for some reason, so we reject it.
489	///
490	/// Some of the reasons may include:
491	/// * HTLC Timeouts
492	/// * Excess HTLCs for a payment that we have already fully received, over-paying for the
493	///   payment,
494	/// * The counterparty node modified the HTLC in transit,
495	/// * A probing attack where an intermediary node is trying to detect if we are the ultimate
496	///   recipient for a payment.
497	FailedPayment {
498		/// The payment hash of the payment we attempted to process.
499		payment_hash: PaymentHash
500	},
501}
502
503impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
504	(0, NextHopChannel) => {
505		(0, node_id, required),
506		(2, channel_id, required),
507	},
508	(1, InvalidForward) => {
509		(0, requested_forward_scid, required),
510	},
511	(2, UnknownNextHop) => {
512		(0, requested_forward_scid, required),
513	},
514	(3, InvalidOnion) => {},
515	(4, FailedPayment) => {
516		(0, payment_hash, required),
517	},
518);
519
520/// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
521/// Currently only used in serialization for the sake of maintaining compatibility. More variants
522/// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
523/// intercepts in upcoming work.
524enum InterceptNextHop {
525	FakeScid {
526		requested_next_hop_scid: u64,
527	},
528}
529
530impl_writeable_tlv_based_enum!(InterceptNextHop,
531	(0, FakeScid) => {
532		(0, requested_next_hop_scid, required),
533	},
534);
535
536/// The reason the payment failed. Used in [`Event::PaymentFailed`].
537#[derive(Clone, Copy, Debug, PartialEq, Eq)]
538pub enum PaymentFailureReason {
539	/// The intended recipient rejected our payment.
540	///
541	/// Also used for [`UnknownRequiredFeatures`] and [`InvoiceRequestRejected`] when downgrading to
542	/// version prior to 0.0.124.
543	///
544	/// [`UnknownRequiredFeatures`]: Self::UnknownRequiredFeatures
545	/// [`InvoiceRequestRejected`]: Self::InvoiceRequestRejected
546	RecipientRejected,
547	/// The user chose to abandon this payment by calling [`ChannelManager::abandon_payment`].
548	///
549	/// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
550	UserAbandoned,
551	#[cfg_attr(feature = "std", doc = "We exhausted all of our retry attempts while trying to send the payment, or we")]
552	#[cfg_attr(feature = "std", doc = "exhausted the [`Retry::Timeout`] if the user set one.")]
553	#[cfg_attr(not(feature = "std"), doc = "We exhausted all of our retry attempts while trying to send the payment.")]
554	/// If at any point a retry attempt failed while being forwarded along the path, an [`Event::PaymentPathFailed`] will
555	/// have come before this.
556	#[cfg_attr(feature = "std", doc = "")]
557	#[cfg_attr(feature = "std", doc = "[`Retry::Timeout`]: crate::ln::channelmanager::Retry::Timeout")]
558	RetriesExhausted,
559	/// The payment expired while retrying, based on the provided
560	/// [`PaymentParameters::expiry_time`].
561	///
562	/// Also used for [`InvoiceRequestExpired`] when downgrading to version prior to 0.0.124.
563	///
564	/// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
565	/// [`InvoiceRequestExpired`]: Self::InvoiceRequestExpired
566	PaymentExpired,
567	/// We failed to find a route while sending or retrying the payment.
568	///
569	/// Note that this generally indicates that we've exhausted the available set of possible
570	/// routes - we tried the payment over a few routes but were not able to find any further
571	/// candidate routes beyond those.
572	///
573	/// Also used for [`BlindedPathCreationFailed`] when downgrading to versions prior to 0.0.124.
574	///
575	/// [`BlindedPathCreationFailed`]: Self::BlindedPathCreationFailed
576	RouteNotFound,
577	/// This error should generally never happen. This likely means that there is a problem with
578	/// your router.
579	UnexpectedError,
580	/// An invoice was received that required unknown features.
581	UnknownRequiredFeatures,
582	/// A [`Bolt12Invoice`] was not received in a reasonable amount of time.
583	InvoiceRequestExpired,
584	/// An [`InvoiceRequest`] for the payment was rejected by the recipient.
585	///
586	/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
587	InvoiceRequestRejected,
588	/// Failed to create a blinded path back to ourselves.
589	/// We attempted to initiate payment to a static invoice but failed to create a reply path for our
590	/// [`HeldHtlcAvailable`] message.
591	///
592	/// [`HeldHtlcAvailable`]: crate::onion_message::async_payments::HeldHtlcAvailable
593	BlindedPathCreationFailed,
594}
595
596impl_writeable_tlv_based_enum_upgradable!(PaymentFailureReason,
597	(0, RecipientRejected) => {},
598	(1, UnknownRequiredFeatures) => {},
599	(2, UserAbandoned) => {},
600	(3, InvoiceRequestExpired) => {},
601	(4, RetriesExhausted) => {},
602	(5, InvoiceRequestRejected) => {},
603	(6, PaymentExpired) => {},
604	(7, BlindedPathCreationFailed) => {},
605	(8, RouteNotFound) => {},
606	(10, UnexpectedError) => {},
607);
608
609/// Used to indicate the kind of funding for this channel by the channel acceptor (us).
610///
611/// Allows the differentiation between a request for a dual-funded and non-dual-funded channel.
612#[derive(Clone, Debug, PartialEq, Eq)]
613pub enum InboundChannelFunds {
614	/// For a non-dual-funded channel, the `push_msat` value from the channel initiator to us.
615	PushMsat(u64),
616	/// Indicates the open request is for a dual funded channel.
617	///
618	/// Note that these channels do not support starting with initial funds pushed from the counterparty,
619	/// who is the channel opener in this case.
620	DualFunded,
621}
622
623/// An Event which you should probably take some action in response to.
624///
625/// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
626/// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
627/// written as it makes no sense to respond to it after reconnecting to peers).
628#[derive(Clone, Debug, PartialEq, Eq)]
629pub enum Event {
630	/// Used to indicate that the client should generate a funding transaction with the given
631	/// parameters and then call [`ChannelManager::funding_transaction_generated`].
632	/// Generated in [`ChannelManager`] message handling.
633	/// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
634	/// counterparty can steal your funds!
635	///
636	/// # Failure Behavior and Persistence
637	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
638	/// returning `Err(ReplayEvent ())`), but won't be persisted across restarts.
639	///
640	/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
641	/// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
642	FundingGenerationReady {
643		/// The random channel_id we picked which you'll need to pass into
644		/// [`ChannelManager::funding_transaction_generated`].
645		///
646		/// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
647		temporary_channel_id: ChannelId,
648		/// The counterparty's node_id, which you'll need to pass back into
649		/// [`ChannelManager::funding_transaction_generated`].
650		///
651		/// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
652		counterparty_node_id: PublicKey,
653		/// The value, in satoshis, that the output should have.
654		channel_value_satoshis: u64,
655		/// The script which should be used in the transaction output.
656		output_script: ScriptBuf,
657		/// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
658		/// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
659		/// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
660		/// `user_channel_id` will be randomized for an inbound channel.  This may be zero for objects
661		/// serialized with LDK versions prior to 0.0.113.
662		///
663		/// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
664		/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
665		/// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
666		user_channel_id: u128,
667	},
668	/// Used to indicate that the counterparty node has provided the signature(s) required to
669	/// recover our funds in case they go offline.
670	///
671	/// It is safe (and your responsibility) to broadcast the funding transaction upon receiving this
672	/// event.
673	///
674	/// This event is only emitted if you called
675	/// [`ChannelManager::unsafe_manual_funding_transaction_generated`] instead of
676	/// [`ChannelManager::funding_transaction_generated`].
677	///
678	/// [`ChannelManager::unsafe_manual_funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::unsafe_manual_funding_transaction_generated
679	/// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
680	FundingTxBroadcastSafe {
681		/// The `channel_id` indicating which channel has reached this stage.
682		channel_id: ChannelId,
683		/// The `user_channel_id` value passed in to [`ChannelManager::create_channel`].
684		///
685		/// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
686		user_channel_id: u128,
687		/// The outpoint of the channel's funding transaction.
688		funding_txo: OutPoint,
689		/// The `node_id` of the channel counterparty.
690		counterparty_node_id: PublicKey,
691		/// The `temporary_channel_id` this channel used to be known by during channel establishment.
692		former_temporary_channel_id: ChannelId,
693	},
694	/// Indicates that we've been offered a payment and it needs to be claimed via calling
695	/// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
696	///
697	/// Note that if the preimage is not known, you should call
698	/// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
699	/// to free up resources for this HTLC and avoid network congestion.
700	///
701	/// If [`Event::PaymentClaimable::onion_fields`] is `Some`, and includes custom TLVs with even type
702	/// numbers, you should use [`ChannelManager::fail_htlc_backwards_with_reason`] with
703	/// [`FailureCode::InvalidOnionPayload`] if you fail to understand and handle the contents, or
704	/// [`ChannelManager::claim_funds_with_known_custom_tlvs`] upon successful handling.
705	/// If you don't intend to check for custom TLVs, you can simply use
706	/// [`ChannelManager::claim_funds`], which will automatically fail back even custom TLVs.
707	///
708	/// If you fail to call [`ChannelManager::claim_funds`],
709	/// [`ChannelManager::claim_funds_with_known_custom_tlvs`],
710	/// [`ChannelManager::fail_htlc_backwards`], or
711	/// [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will
712	/// be automatically failed.
713	///
714	/// # Note
715	/// LDK will not stop an inbound payment from being paid multiple times, so multiple
716	/// `PaymentClaimable` events may be generated for the same payment. In such a case it is
717	/// polite (and required in the lightning specification) to fail the payment the second time
718	/// and give the sender their money back rather than accepting double payment.
719	///
720	/// # Note
721	/// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
722	///
723	/// # Failure Behavior and Persistence
724	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
725	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
726	///
727	/// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
728	/// [`ChannelManager::claim_funds_with_known_custom_tlvs`]: crate::ln::channelmanager::ChannelManager::claim_funds_with_known_custom_tlvs
729	/// [`FailureCode::InvalidOnionPayload`]: crate::ln::channelmanager::FailureCode::InvalidOnionPayload
730	/// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
731	/// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
732	PaymentClaimable {
733		/// The node that will receive the payment after it has been claimed.
734		/// This is useful to identify payments received via [phantom nodes].
735		/// This field will always be filled in when the event was generated by LDK versions
736		/// 0.0.113 and above.
737		///
738		/// [phantom nodes]: crate::sign::PhantomKeysManager
739		receiver_node_id: Option<PublicKey>,
740		/// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
741		/// not stop you from registering duplicate payment hashes for inbound payments.
742		payment_hash: PaymentHash,
743		/// The fields in the onion which were received with each HTLC. Only fields which were
744		/// identical in each HTLC involved in the payment will be included here.
745		///
746		/// Payments received on LDK versions prior to 0.0.115 will have this field unset.
747		onion_fields: Option<RecipientOnionFields>,
748		/// The value, in thousandths of a satoshi, that this payment is claimable for. May be greater
749		/// than the invoice amount.
750		///
751		/// May be less than the invoice amount if [`ChannelConfig::accept_underpaying_htlcs`] is set
752		/// and the previous hop took an extra fee.
753		///
754		/// # Note
755		/// If [`ChannelConfig::accept_underpaying_htlcs`] is set and you claim without verifying this
756		/// field, you may lose money!
757		///
758		/// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
759		amount_msat: u64,
760		/// The value, in thousands of a satoshi, that was skimmed off of this payment as an extra fee
761		/// taken by our channel counterparty.
762		///
763		/// Will always be 0 unless [`ChannelConfig::accept_underpaying_htlcs`] is set.
764		///
765		/// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
766		counterparty_skimmed_fee_msat: u64,
767		/// Information for claiming this received payment, based on whether the purpose of the
768		/// payment is to pay an invoice or to send a spontaneous payment.
769		purpose: PaymentPurpose,
770		/// The `channel_id` indicating over which channel we received the payment.
771		via_channel_id: Option<ChannelId>,
772		/// The `user_channel_id` indicating over which channel we received the payment.
773		via_user_channel_id: Option<u128>,
774		/// The block height at which this payment will be failed back and will no longer be
775		/// eligible for claiming.
776		///
777		/// Prior to this height, a call to [`ChannelManager::claim_funds`] is guaranteed to
778		/// succeed, however you should wait for [`Event::PaymentClaimed`] to be sure.
779		///
780		/// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
781		claim_deadline: Option<u32>,
782		/// A unique ID describing this payment (derived from the list of HTLCs in the payment).
783		///
784		/// Payers may pay for the same [`PaymentHash`] multiple times (though this is unsafe and
785		/// an intermediary node may steal the funds). Thus, in order to accurately track when
786		/// payments are received and claimed, you should use this identifier.
787		///
788		/// Only filled in for payments received on LDK versions 0.1 and higher.
789		payment_id: Option<PaymentId>,
790	},
791	/// Indicates a payment has been claimed and we've received money!
792	///
793	/// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
794	/// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
795	/// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
796	/// [`Event::PaymentClaimable`] event.
797	///
798	/// # Note
799	/// LDK will not stop an inbound payment from being paid multiple times, so multiple
800	/// `PaymentClaimable` events may be generated for the same payment. If you then call
801	/// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
802	/// multiple `PaymentClaimed` events.
803	///
804	/// # Failure Behavior and Persistence
805	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
806	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
807	///
808	/// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
809	PaymentClaimed {
810		/// The node that received the payment.
811		/// This is useful to identify payments which were received via [phantom nodes].
812		/// This field will always be filled in when the event was generated by LDK versions
813		/// 0.0.113 and above.
814		///
815		/// [phantom nodes]: crate::sign::PhantomKeysManager
816		receiver_node_id: Option<PublicKey>,
817		/// The payment hash of the claimed payment. Note that LDK will not stop you from
818		/// registering duplicate payment hashes for inbound payments.
819		payment_hash: PaymentHash,
820		/// The value, in thousandths of a satoshi, that this payment is for. May be greater than the
821		/// invoice amount.
822		amount_msat: u64,
823		/// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
824		/// spontaneous payment.
825		purpose: PaymentPurpose,
826		/// The HTLCs that comprise the claimed payment. This will be empty for events serialized prior
827		/// to LDK version 0.0.117.
828		htlcs: Vec<ClaimedHTLC>,
829		/// The sender-intended sum total of all the MPP parts. This will be `None` for events
830		/// serialized prior to LDK version 0.0.117.
831		sender_intended_total_msat: Option<u64>,
832		/// The fields in the onion which were received with each HTLC. Only fields which were
833		/// identical in each HTLC involved in the payment will be included here.
834		///
835		/// Payments received on LDK versions prior to 0.0.124 will have this field unset.
836		onion_fields: Option<RecipientOnionFields>,
837		/// A unique ID describing this payment (derived from the list of HTLCs in the payment).
838		///
839		/// Payers may pay for the same [`PaymentHash`] multiple times (though this is unsafe and
840		/// an intermediary node may steal the funds). Thus, in order to accurately track when
841		/// payments are received and claimed, you should use this identifier.
842		///
843		/// Only filled in for payments received on LDK versions 0.1 and higher.
844		payment_id: Option<PaymentId>,
845	},
846	/// Indicates that a peer connection with a node is needed in order to send an [`OnionMessage`].
847	///
848	/// Typically, this happens when a [`MessageRouter`] is unable to find a complete path to a
849	/// [`Destination`]. Once a connection is established, any messages buffered by an
850	/// [`OnionMessageHandler`] may be sent.
851	///
852	/// This event will not be generated for onion message forwards; only for sends including
853	/// replies. Handlers should connect to the node otherwise any buffered messages may be lost.
854	///
855	/// # Failure Behavior and Persistence
856	/// This event won't be replayed after failures-to-handle
857	/// (i.e., the event handler returning `Err(ReplayEvent ())`), and also won't be persisted
858	/// across restarts.
859	///
860	/// [`OnionMessage`]: msgs::OnionMessage
861	/// [`MessageRouter`]: crate::onion_message::messenger::MessageRouter
862	/// [`Destination`]: crate::onion_message::messenger::Destination
863	/// [`OnionMessageHandler`]: crate::ln::msgs::OnionMessageHandler
864	ConnectionNeeded {
865		/// The node id for the node needing a connection.
866		node_id: PublicKey,
867		/// Sockets for connecting to the node.
868		addresses: Vec<msgs::SocketAddress>,
869	},
870	/// Indicates a [`Bolt12Invoice`] in response to an [`InvoiceRequest`] or a [`Refund`] was
871	/// received.
872	///
873	/// This event will only be generated if [`UserConfig::manually_handle_bolt12_invoices`] is set.
874	/// Use [`ChannelManager::send_payment_for_bolt12_invoice`] to pay the invoice or
875	/// [`ChannelManager::abandon_payment`] to abandon the associated payment. See those docs for
876	/// further details.
877	///
878	/// # Failure Behavior and Persistence
879	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
880	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
881	///
882	/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
883	/// [`Refund`]: crate::offers::refund::Refund
884	/// [`UserConfig::manually_handle_bolt12_invoices`]: crate::util::config::UserConfig::manually_handle_bolt12_invoices
885	/// [`ChannelManager::send_payment_for_bolt12_invoice`]: crate::ln::channelmanager::ChannelManager::send_payment_for_bolt12_invoice
886	/// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
887	InvoiceReceived {
888		/// The `payment_id` associated with payment for the invoice.
889		payment_id: PaymentId,
890		/// The invoice to pay.
891		invoice: Bolt12Invoice,
892		/// The context of the [`BlindedMessagePath`] used to send the invoice.
893		///
894		/// [`BlindedMessagePath`]: crate::blinded_path::message::BlindedMessagePath
895		context: Option<OffersContext>,
896		/// A responder for replying with an [`InvoiceError`] if needed.
897		///
898		/// `None` if the invoice wasn't sent with a reply path.
899		///
900		/// [`InvoiceError`]: crate::offers::invoice_error::InvoiceError
901		responder: Option<Responder>,
902	},
903	/// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
904	/// and we got back the payment preimage for it).
905	///
906	/// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
907	/// event. In this situation, you SHOULD treat this payment as having succeeded.
908	///
909	/// # Failure Behavior and Persistence
910	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
911	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
912	PaymentSent {
913		/// The `payment_id` passed to [`ChannelManager::send_payment`].
914		///
915		/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
916		payment_id: Option<PaymentId>,
917		/// The preimage to the hash given to ChannelManager::send_payment.
918		/// Note that this serves as a payment receipt, if you wish to have such a thing, you must
919		/// store it somehow!
920		payment_preimage: PaymentPreimage,
921		/// The hash that was given to [`ChannelManager::send_payment`].
922		///
923		/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
924		payment_hash: PaymentHash,
925		/// The total fee which was spent at intermediate hops in this payment, across all paths.
926		///
927		/// Note that, like [`Route::get_total_fees`] this does *not* include any potential
928		/// overpayment to the recipient node.
929		///
930		/// If the recipient or an intermediate node misbehaves and gives us free money, this may
931		/// overstate the amount paid, though this is unlikely.
932		///
933		/// This is only `None` for payments initiated on LDK versions prior to 0.0.103.
934		///
935		/// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
936		fee_paid_msat: Option<u64>,
937	},
938	/// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
939	/// provide failure information for each path attempt in the payment, including retries.
940	///
941	/// This event is provided once there are no further pending HTLCs for the payment and the
942	/// payment is no longer retryable, due either to the [`Retry`] provided or
943	/// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
944	///
945	/// In exceedingly rare cases, it is possible that an [`Event::PaymentFailed`] is generated for
946	/// a payment after an [`Event::PaymentSent`] event for this same payment has already been
947	/// received and processed. In this case, the [`Event::PaymentFailed`] event MUST be ignored,
948	/// and the payment MUST be treated as having succeeded.
949	///
950	/// # Failure Behavior and Persistence
951	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
952	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
953	///
954	/// [`Retry`]: crate::ln::channelmanager::Retry
955	/// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
956	PaymentFailed {
957		/// The `payment_id` passed to [`ChannelManager::send_payment`].
958		///
959		/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
960		payment_id: PaymentId,
961		/// The hash that was given to [`ChannelManager::send_payment`]. `None` if the payment failed
962		/// before receiving an invoice when paying a BOLT12 [`Offer`].
963		///
964		/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
965		/// [`Offer`]: crate::offers::offer::Offer
966		payment_hash: Option<PaymentHash>,
967		/// The reason the payment failed. This is only `None` for events generated or serialized
968		/// by versions prior to 0.0.115, or when downgrading to a version with a reason that was
969		/// added after.
970		reason: Option<PaymentFailureReason>,
971	},
972	/// Indicates that a path for an outbound payment was successful.
973	///
974	/// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
975	/// [`Event::PaymentSent`] for obtaining the payment preimage.
976	///
977	/// # Failure Behavior and Persistence
978	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
979	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
980	PaymentPathSuccessful {
981		/// The `payment_id` passed to [`ChannelManager::send_payment`].
982		///
983		/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
984		payment_id: PaymentId,
985		/// The hash that was given to [`ChannelManager::send_payment`].
986		///
987		/// This will be `Some` for all payments which completed on LDK 0.0.104 or later.
988		///
989		/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
990		payment_hash: Option<PaymentHash>,
991		/// The payment path that was successful.
992		///
993		/// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
994		path: Path,
995	},
996	/// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
997	/// handle the HTLC.
998	///
999	/// Note that this does *not* indicate that all paths for an MPP payment have failed, see
1000	/// [`Event::PaymentFailed`].
1001	///
1002	/// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
1003	/// been exhausted.
1004	///
1005	/// # Failure Behavior and Persistence
1006	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1007	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1008	///
1009	/// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
1010	PaymentPathFailed {
1011		/// The `payment_id` passed to [`ChannelManager::send_payment`].
1012		///
1013		/// This will be `Some` for all payment paths which failed on LDK 0.0.103 or later.
1014		///
1015		/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1016		/// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
1017		payment_id: Option<PaymentId>,
1018		/// The hash that was given to [`ChannelManager::send_payment`].
1019		///
1020		/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1021		payment_hash: PaymentHash,
1022		/// Indicates the payment was rejected for some reason by the recipient. This implies that
1023		/// the payment has failed, not just the route in question. If this is not set, the payment may
1024		/// be retried via a different route.
1025		payment_failed_permanently: bool,
1026		/// Extra error details based on the failure type. May contain an update that needs to be
1027		/// applied to the [`NetworkGraph`].
1028		///
1029		/// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1030		failure: PathFailure,
1031		/// The payment path that failed.
1032		path: Path,
1033		/// The channel responsible for the failed payment path.
1034		///
1035		/// Note that for route hints or for the first hop in a path this may be an SCID alias and
1036		/// may not refer to a channel in the public network graph. These aliases may also collide
1037		/// with channels in the public network graph.
1038		///
1039		/// If this is `Some`, then the corresponding channel should be avoided when the payment is
1040		/// retried. May be `None` for older [`Event`] serializations.
1041		short_channel_id: Option<u64>,
1042#[cfg(test)]
1043		error_code: Option<u16>,
1044#[cfg(test)]
1045		error_data: Option<Vec<u8>>,
1046	},
1047	/// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
1048	///
1049	/// # Failure Behavior and Persistence
1050	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1051	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1052	ProbeSuccessful {
1053		/// The id returned by [`ChannelManager::send_probe`].
1054		///
1055		/// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
1056		payment_id: PaymentId,
1057		/// The hash generated by [`ChannelManager::send_probe`].
1058		///
1059		/// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
1060		payment_hash: PaymentHash,
1061		/// The payment path that was successful.
1062		path: Path,
1063	},
1064	/// Indicates that a probe payment we sent failed at an intermediary node on the path.
1065	///
1066	/// # Failure Behavior and Persistence
1067	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1068	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1069	ProbeFailed {
1070		/// The id returned by [`ChannelManager::send_probe`].
1071		///
1072		/// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
1073		payment_id: PaymentId,
1074		/// The hash generated by [`ChannelManager::send_probe`].
1075		///
1076		/// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
1077		payment_hash: PaymentHash,
1078		/// The payment path that failed.
1079		path: Path,
1080		/// The channel responsible for the failed probe.
1081		///
1082		/// Note that for route hints or for the first hop in a path this may be an SCID alias and
1083		/// may not refer to a channel in the public network graph. These aliases may also collide
1084		/// with channels in the public network graph.
1085		short_channel_id: Option<u64>,
1086	},
1087	/// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
1088	/// a time in the future.
1089	///
1090	/// # Failure Behavior and Persistence
1091	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1092	/// returning `Err(ReplayEvent ())`) and will be regenerated after restarts.
1093	///
1094	/// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1095	PendingHTLCsForwardable {
1096		/// The minimum amount of time that should be waited prior to calling
1097		/// process_pending_htlc_forwards. To increase the effort required to correlate payments,
1098		/// you should wait a random amount of time in roughly the range (now + time_forwardable,
1099		/// now + 5*time_forwardable).
1100		time_forwardable: Duration,
1101	},
1102	/// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
1103	/// you've encoded an intercept scid in the receiver's invoice route hints using
1104	/// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
1105	///
1106	/// [`ChannelManager::forward_intercepted_htlc`] or
1107	/// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
1108	/// their docs for more information.
1109	///
1110	/// # Failure Behavior and Persistence
1111	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1112	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1113	///
1114	/// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
1115	/// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
1116	/// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
1117	/// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
1118	HTLCIntercepted {
1119		/// An id to help LDK identify which HTLC is being forwarded or failed.
1120		intercept_id: InterceptId,
1121		/// The fake scid that was programmed as the next hop's scid, generated using
1122		/// [`ChannelManager::get_intercept_scid`].
1123		///
1124		/// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
1125		requested_next_hop_scid: u64,
1126		/// The payment hash used for this HTLC.
1127		payment_hash: PaymentHash,
1128		/// How many msats were received on the inbound edge of this HTLC.
1129		inbound_amount_msat: u64,
1130		/// How many msats the payer intended to route to the next node. Depending on the reason you are
1131		/// intercepting this payment, you might take a fee by forwarding less than this amount.
1132		/// Forwarding less than this amount may break compatibility with LDK versions prior to 0.0.116.
1133		///
1134		/// Note that LDK will NOT check that expected fees were factored into this value. You MUST
1135		/// check that whatever fee you want has been included here or subtract it as required. Further,
1136		/// LDK will not stop you from forwarding more than you received.
1137		expected_outbound_amount_msat: u64,
1138	},
1139	/// Used to indicate that an output which you should know how to spend was confirmed on chain
1140	/// and is now spendable.
1141	///
1142	/// Such an output will *never* be spent directly by LDK, and are not at risk of your
1143	/// counterparty spending them due to some kind of timeout. Thus, you need to store them
1144	/// somewhere and spend them when you create on-chain transactions.
1145	///
1146	/// You may hand them to the [`OutputSweeper`] utility which will store and (re-)generate spending
1147	/// transactions for you.
1148	///
1149	/// # Failure Behavior and Persistence
1150	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1151	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1152	///
1153	/// [`OutputSweeper`]: crate::util::sweep::OutputSweeper
1154	SpendableOutputs {
1155		/// The outputs which you should store as spendable by you.
1156		outputs: Vec<SpendableOutputDescriptor>,
1157		/// The `channel_id` indicating which channel the spendable outputs belong to.
1158		///
1159		/// This will always be `Some` for events generated by LDK versions 0.0.117 and above.
1160		channel_id: Option<ChannelId>,
1161	},
1162	/// This event is generated when a payment has been successfully forwarded through us and a
1163	/// forwarding fee earned.
1164	///
1165	/// # Failure Behavior and Persistence
1166	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1167	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1168	PaymentForwarded {
1169		/// The channel id of the incoming channel between the previous node and us.
1170		///
1171		/// This is only `None` for events generated or serialized by versions prior to 0.0.107.
1172		prev_channel_id: Option<ChannelId>,
1173		/// The channel id of the outgoing channel between the next node and us.
1174		///
1175		/// This is only `None` for events generated or serialized by versions prior to 0.0.107.
1176		next_channel_id: Option<ChannelId>,
1177		/// The `user_channel_id` of the incoming channel between the previous node and us.
1178		///
1179		/// This is only `None` for events generated or serialized by versions prior to 0.0.122.
1180		prev_user_channel_id: Option<u128>,
1181		/// The `user_channel_id` of the outgoing channel between the next node and us.
1182		///
1183		/// This will be `None` if the payment was settled via an on-chain transaction. See the
1184		/// caveat described for the `total_fee_earned_msat` field. Moreover it will be `None` for
1185		/// events generated or serialized by versions prior to 0.0.122.
1186		next_user_channel_id: Option<u128>,
1187		/// The node id of the previous node.
1188		/// 
1189		/// This is only `None` for HTLCs received prior to 0.1 or for events serialized by
1190		/// versions prior to 0.1
1191		prev_node_id: Option<PublicKey>,
1192		/// The node id of the next node.
1193		/// 
1194		/// This is only `None` for HTLCs received prior to 0.1 or for events serialized by
1195		/// versions prior to 0.1
1196		next_node_id: Option<PublicKey>,
1197		/// The total fee, in milli-satoshis, which was earned as a result of the payment.
1198		///
1199		/// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
1200		/// was pending, the amount the next hop claimed will have been rounded down to the nearest
1201		/// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
1202		/// claimed the full value in millisatoshis from the source. In this case,
1203		/// `claim_from_onchain_tx` will be set.
1204		///
1205		/// If the channel which sent us the payment has been force-closed, we will claim the funds
1206		/// via an on-chain transaction. In that case we do not yet know the on-chain transaction
1207		/// fees which we will spend and will instead set this to `None`. It is possible duplicate
1208		/// `PaymentForwarded` events are generated for the same payment iff `total_fee_earned_msat` is
1209		/// `None`.
1210		total_fee_earned_msat: Option<u64>,
1211		/// The share of the total fee, in milli-satoshis, which was withheld in addition to the
1212		/// forwarding fee.
1213		///
1214		/// This will only be `Some` if we forwarded an intercepted HTLC with less than the
1215		/// expected amount. This means our counterparty accepted to receive less than the invoice
1216		/// amount, e.g., by claiming the payment featuring a corresponding
1217		/// [`PaymentClaimable::counterparty_skimmed_fee_msat`].
1218		///
1219		/// Will also always be `None` for events serialized with LDK prior to version 0.0.122.
1220		///
1221		/// The caveat described above the `total_fee_earned_msat` field applies here as well.
1222		///
1223		/// [`PaymentClaimable::counterparty_skimmed_fee_msat`]: Self::PaymentClaimable::counterparty_skimmed_fee_msat
1224		skimmed_fee_msat: Option<u64>,
1225		/// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
1226		/// transaction.
1227		claim_from_onchain_tx: bool,
1228		/// The final amount forwarded, in milli-satoshis, after the fee is deducted.
1229		///
1230		/// The caveat described above the `total_fee_earned_msat` field applies here as well.
1231		outbound_amount_forwarded_msat: Option<u64>,
1232	},
1233	/// Used to indicate that a channel with the given `channel_id` is being opened and pending
1234	/// confirmation on-chain.
1235	///
1236	/// This event is emitted when the funding transaction has been signed and is broadcast to the
1237	/// network. For 0conf channels it will be immediately followed by the corresponding
1238	/// [`Event::ChannelReady`] event.
1239	///
1240	/// # Failure Behavior and Persistence
1241	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1242	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1243	ChannelPending {
1244		/// The `channel_id` of the channel that is pending confirmation.
1245		channel_id: ChannelId,
1246		/// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1247		/// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1248		/// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1249		/// `user_channel_id` will be randomized for an inbound channel.
1250		///
1251		/// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1252		/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1253		/// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1254		user_channel_id: u128,
1255		/// The `temporary_channel_id` this channel used to be known by during channel establishment.
1256		///
1257		/// Will be `None` for channels created prior to LDK version 0.0.115.
1258		former_temporary_channel_id: Option<ChannelId>,
1259		/// The `node_id` of the channel counterparty.
1260		counterparty_node_id: PublicKey,
1261		/// The outpoint of the channel's funding transaction.
1262		funding_txo: OutPoint,
1263		/// The features that this channel will operate with.
1264		///
1265		/// Will be `None` for channels created prior to LDK version 0.0.122.
1266		channel_type: Option<ChannelTypeFeatures>,
1267	},
1268	/// Used to indicate that a channel with the given `channel_id` is ready to
1269	/// be used. This event is emitted either when the funding transaction has been confirmed
1270	/// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
1271	/// establishment.
1272	///
1273	/// # Failure Behavior and Persistence
1274	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1275	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1276	ChannelReady {
1277		/// The `channel_id` of the channel that is ready.
1278		channel_id: ChannelId,
1279		/// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1280		/// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1281		/// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1282		/// `user_channel_id` will be randomized for an inbound channel.
1283		///
1284		/// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1285		/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1286		/// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1287		user_channel_id: u128,
1288		/// The `node_id` of the channel counterparty.
1289		counterparty_node_id: PublicKey,
1290		/// The features that this channel will operate with.
1291		channel_type: ChannelTypeFeatures,
1292	},
1293	/// Used to indicate that a channel that got past the initial handshake with the given `channel_id` is in the
1294	/// process of closure. This includes previously opened channels, and channels that time out from not being funded.
1295	///
1296	/// Note that this event is only triggered for accepted channels: if the
1297	/// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true and the channel is
1298	/// rejected, no `ChannelClosed` event will be sent.
1299	///
1300	/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1301	/// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1302	///
1303	/// # Failure Behavior and Persistence
1304	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1305	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1306	ChannelClosed {
1307		/// The `channel_id` of the channel which has been closed. Note that on-chain transactions
1308		/// resolving the channel are likely still awaiting confirmation.
1309		channel_id: ChannelId,
1310		/// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1311		/// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1312		/// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1313		/// `user_channel_id` will be randomized for inbound channels.
1314		/// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
1315		/// zero for objects serialized with LDK versions prior to 0.0.102.
1316		///
1317		/// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1318		/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1319		/// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1320		user_channel_id: u128,
1321		/// The reason the channel was closed.
1322		reason: ClosureReason,
1323		/// Counterparty in the closed channel.
1324		///
1325		/// This field will be `None` for objects serialized prior to LDK 0.0.117.
1326		counterparty_node_id: Option<PublicKey>,
1327		/// Channel capacity of the closing channel (sats).
1328		///
1329		/// This field will be `None` for objects serialized prior to LDK 0.0.117.
1330		channel_capacity_sats: Option<u64>,
1331
1332		/// The original channel funding TXO; this helps checking for the existence and confirmation
1333		/// status of the closing tx.
1334		/// Note that for instances serialized in v0.0.119 or prior this will be missing (None).
1335		channel_funding_txo: Option<transaction::OutPoint>,
1336		/// An upper bound on the our last local balance in msats before the channel was closed.
1337		///
1338		/// Will overstate our balance as it ignores pending outbound HTLCs and transaction fees.
1339		///
1340		/// For more accurate balances including fee information see
1341		/// [`ChainMonitor::get_claimable_balances`].
1342		///
1343		/// This field will be `None` only for objects serialized prior to LDK 0.1.
1344		///
1345		/// [`ChainMonitor::get_claimable_balances`]: crate::chain::chainmonitor::ChainMonitor::get_claimable_balances
1346		last_local_balance_msat: Option<u64>,
1347	},
1348	/// Used to indicate to the user that they can abandon the funding transaction and recycle the
1349	/// inputs for another purpose.
1350	///
1351	/// This event is not guaranteed to be generated for channels that are closed due to a restart.
1352	///
1353	/// # Failure Behavior and Persistence
1354	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1355	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1356	DiscardFunding {
1357		/// The channel_id of the channel which has been closed.
1358		channel_id: ChannelId,
1359		/// The full transaction received from the user
1360		funding_info: FundingInfo,
1361	},
1362	/// Indicates a request to open a new channel by a peer.
1363	///
1364	/// To accept the request (and in the case of a dual-funded channel, not contribute funds),
1365	/// call [`ChannelManager::accept_inbound_channel`].
1366	/// To reject the request, call [`ChannelManager::force_close_without_broadcasting_txn`].
1367	/// Note that a ['ChannelClosed`] event will _not_ be triggered if the channel is rejected.
1368	///
1369	/// The event is only triggered when a new open channel request is received and the
1370	/// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
1371	///
1372	/// # Failure Behavior and Persistence
1373	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1374	/// returning `Err(ReplayEvent ())`) and won't be persisted across restarts.
1375	///
1376	/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1377	/// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1378	/// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1379	OpenChannelRequest {
1380		/// The temporary channel ID of the channel requested to be opened.
1381		///
1382		/// When responding to the request, the `temporary_channel_id` should be passed
1383		/// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
1384		/// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
1385		///
1386		/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1387		/// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1388		temporary_channel_id: ChannelId,
1389		/// The node_id of the counterparty requesting to open the channel.
1390		///
1391		/// When responding to the request, the `counterparty_node_id` should be passed
1392		/// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
1393		/// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
1394		/// request.
1395		///
1396		/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1397		/// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1398		counterparty_node_id: PublicKey,
1399		/// The channel value of the requested channel.
1400		funding_satoshis: u64,
1401		/// If `channel_negotiation_type` is `InboundChannelFunds::DualFunded`, this indicates that the peer wishes to
1402		/// open a dual-funded channel. Otherwise, this field will be `InboundChannelFunds::PushMsats`,
1403		/// indicating the `push_msats` value our peer is pushing to us for a non-dual-funded channel.
1404		channel_negotiation_type: InboundChannelFunds,
1405		/// The features that this channel will operate with. If you reject the channel, a
1406		/// well-behaved counterparty may automatically re-attempt the channel with a new set of
1407		/// feature flags.
1408		///
1409		/// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
1410		/// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1411		/// 0.0.106.
1412		///
1413		/// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
1414		/// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1415		/// 0.0.107. Channels setting this type also need to get manually accepted via
1416		/// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
1417		/// or will be rejected otherwise.
1418		///
1419		/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1420		channel_type: ChannelTypeFeatures,
1421		/// True if this channel is (or will be) publicly-announced.
1422		is_announced: bool,
1423		/// Channel parameters given by the counterparty.
1424		params: msgs::ChannelParameters,
1425	},
1426	/// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
1427	/// forward it.
1428	///
1429	/// Some scenarios where this event may be sent include:
1430	/// * Insufficient capacity in the outbound channel
1431	/// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
1432	/// * When an unknown SCID is requested for forwarding a payment.
1433	/// * Expected MPP amount has already been reached
1434	/// * The HTLC has timed out
1435	///
1436	/// This event, however, does not get generated if an HTLC fails to meet the forwarding
1437	/// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
1438	///
1439	/// # Failure Behavior and Persistence
1440	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1441	/// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1442	HTLCHandlingFailed {
1443		/// The channel over which the HTLC was received.
1444		prev_channel_id: ChannelId,
1445		/// Destination of the HTLC that failed to be processed.
1446		failed_next_destination: HTLCDestination,
1447	},
1448	/// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
1449	/// requires confirmed external funds to be readily available to spend.
1450	///
1451	/// LDK does not currently generate this event unless the
1452	/// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`] config flag is set to true.
1453	/// It is limited to the scope of channels with anchor outputs.
1454	///
1455	/// # Failure Behavior and Persistence
1456	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1457	/// returning `Err(ReplayEvent ())`), but will only be regenerated as needed after restarts.
1458	///
1459	/// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`]: crate::util::config::ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx
1460	BumpTransaction(BumpTransactionEvent),
1461	/// We received an onion message that is intended to be forwarded to a peer
1462	/// that is currently offline. This event will only be generated if the
1463	/// `OnionMessenger` was initialized with
1464	/// [`OnionMessenger::new_with_offline_peer_interception`], see its docs.
1465	///
1466	/// # Failure Behavior and Persistence
1467	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1468	/// returning `Err(ReplayEvent ())`), but won't be persisted across restarts.
1469	///
1470	/// [`OnionMessenger::new_with_offline_peer_interception`]: crate::onion_message::messenger::OnionMessenger::new_with_offline_peer_interception
1471	OnionMessageIntercepted {
1472		/// The node id of the offline peer.
1473		peer_node_id: PublicKey,
1474		/// The onion message intended to be forwarded to `peer_node_id`.
1475		message: msgs::OnionMessage,
1476	},
1477	/// Indicates that an onion message supporting peer has come online and it may
1478	/// be time to forward any onion messages that were previously intercepted for
1479	/// them. This event will only be generated if the `OnionMessenger` was
1480	/// initialized with
1481	/// [`OnionMessenger::new_with_offline_peer_interception`], see its docs.
1482	///
1483	/// # Failure Behavior and Persistence
1484	/// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1485	/// returning `Err(ReplayEvent ())`), but won't be persisted across restarts.
1486	///
1487	/// [`OnionMessenger::new_with_offline_peer_interception`]: crate::onion_message::messenger::OnionMessenger::new_with_offline_peer_interception
1488	OnionMessagePeerConnected {
1489		/// The node id of the peer we just connected to, who advertises support for
1490		/// onion messages.
1491		peer_node_id: PublicKey,
1492	}
1493}
1494
1495impl Writeable for Event {
1496	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1497		match self {
1498			&Event::FundingGenerationReady { .. } => {
1499				0u8.write(writer)?;
1500				// We never write out FundingGenerationReady events as, upon disconnection, peers
1501				// drop any channels which have not yet exchanged funding_signed.
1502			},
1503			&Event::PaymentClaimable { ref payment_hash, ref amount_msat, counterparty_skimmed_fee_msat,
1504				ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id,
1505				ref claim_deadline, ref onion_fields, ref payment_id,
1506			} => {
1507				1u8.write(writer)?;
1508				let mut payment_secret = None;
1509				let payment_preimage;
1510				let mut payment_context = None;
1511				match &purpose {
1512					PaymentPurpose::Bolt11InvoicePayment {
1513						payment_preimage: preimage, payment_secret: secret
1514					} => {
1515						payment_secret = Some(secret);
1516						payment_preimage = *preimage;
1517					},
1518					PaymentPurpose::Bolt12OfferPayment {
1519						payment_preimage: preimage, payment_secret: secret, payment_context: context
1520					} => {
1521						payment_secret = Some(secret);
1522						payment_preimage = *preimage;
1523						payment_context = Some(PaymentContextRef::Bolt12Offer(context));
1524					},
1525					PaymentPurpose::Bolt12RefundPayment {
1526						payment_preimage: preimage, payment_secret: secret, payment_context: context
1527					} => {
1528						payment_secret = Some(secret);
1529						payment_preimage = *preimage;
1530						payment_context = Some(PaymentContextRef::Bolt12Refund(context));
1531					},
1532					PaymentPurpose::SpontaneousPayment(preimage) => {
1533						payment_preimage = Some(*preimage);
1534					}
1535				}
1536				let skimmed_fee_opt = if counterparty_skimmed_fee_msat == 0 { None }
1537					else { Some(counterparty_skimmed_fee_msat) };
1538				write_tlv_fields!(writer, {
1539					(0, payment_hash, required),
1540					(1, receiver_node_id, option),
1541					(2, payment_secret, option),
1542					(3, via_channel_id, option),
1543					(4, amount_msat, required),
1544					(5, via_user_channel_id, option),
1545					// Type 6 was `user_payment_id` on 0.0.103 and earlier
1546					(7, claim_deadline, option),
1547					(8, payment_preimage, option),
1548					(9, onion_fields, option),
1549					(10, skimmed_fee_opt, option),
1550					(11, payment_context, option),
1551					(13, payment_id, option),
1552				});
1553			},
1554			&Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
1555				2u8.write(writer)?;
1556				write_tlv_fields!(writer, {
1557					(0, payment_preimage, required),
1558					(1, payment_hash, required),
1559					(3, payment_id, option),
1560					(5, fee_paid_msat, option),
1561				});
1562			},
1563			&Event::PaymentPathFailed {
1564				ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
1565				ref path, ref short_channel_id,
1566				#[cfg(test)]
1567				ref error_code,
1568				#[cfg(test)]
1569				ref error_data,
1570			} => {
1571				3u8.write(writer)?;
1572				#[cfg(test)]
1573				error_code.write(writer)?;
1574				#[cfg(test)]
1575				error_data.write(writer)?;
1576				write_tlv_fields!(writer, {
1577					(0, payment_hash, required),
1578					(1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
1579					(2, payment_failed_permanently, required),
1580					(3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
1581					(4, path.blinded_tail, option),
1582					(5, path.hops, required_vec),
1583					(7, short_channel_id, option),
1584					(9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
1585					(11, payment_id, option),
1586					(13, failure, required),
1587				});
1588			},
1589			&Event::PendingHTLCsForwardable { time_forwardable: _ } => {
1590				4u8.write(writer)?;
1591				// Note that we now ignore these on the read end as we'll re-generate them in
1592				// ChannelManager, we write them here only for backwards compatibility.
1593			},
1594			&Event::SpendableOutputs { ref outputs, channel_id } => {
1595				5u8.write(writer)?;
1596				write_tlv_fields!(writer, {
1597					(0, WithoutLength(outputs), required),
1598					(1, channel_id, option),
1599				});
1600			},
1601			&Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1602				6u8.write(writer)?;
1603				let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1604				write_tlv_fields!(writer, {
1605					(0, intercept_id, required),
1606					(2, intercept_scid, required),
1607					(4, payment_hash, required),
1608					(6, inbound_amount_msat, required),
1609					(8, expected_outbound_amount_msat, required),
1610				});
1611			}
1612			&Event::PaymentForwarded {
1613				prev_channel_id, next_channel_id, prev_user_channel_id, next_user_channel_id,
1614				prev_node_id, next_node_id, total_fee_earned_msat, skimmed_fee_msat,
1615				claim_from_onchain_tx, outbound_amount_forwarded_msat,
1616			} => {
1617				7u8.write(writer)?;
1618				write_tlv_fields!(writer, {
1619					(0, total_fee_earned_msat, option),
1620					(1, prev_channel_id, option),
1621					(2, claim_from_onchain_tx, required),
1622					(3, next_channel_id, option),
1623					(5, outbound_amount_forwarded_msat, option),
1624					(7, skimmed_fee_msat, option),
1625					(9, prev_user_channel_id, option),
1626					(11, next_user_channel_id, option),
1627					(13, prev_node_id, option),
1628					(15, next_node_id, option),
1629				});
1630			},
1631			&Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason,
1632				ref counterparty_node_id, ref channel_capacity_sats, ref channel_funding_txo,
1633				ref last_local_balance_msat,
1634			} => {
1635				9u8.write(writer)?;
1636				// `user_channel_id` used to be a single u64 value. In order to remain backwards
1637				// compatible with versions prior to 0.0.113, the u128 is serialized as two
1638				// separate u64 values.
1639				let user_channel_id_low = *user_channel_id as u64;
1640				let user_channel_id_high = (*user_channel_id >> 64) as u64;
1641				write_tlv_fields!(writer, {
1642					(0, channel_id, required),
1643					(1, user_channel_id_low, required),
1644					(2, reason, required),
1645					(3, user_channel_id_high, required),
1646					(5, counterparty_node_id, option),
1647					(7, channel_capacity_sats, option),
1648					(9, channel_funding_txo, option),
1649					(11, last_local_balance_msat, option)
1650				});
1651			},
1652			&Event::DiscardFunding { ref channel_id, ref funding_info } => {
1653				11u8.write(writer)?;
1654
1655				let transaction = if let FundingInfo::Tx { transaction } = funding_info {
1656					Some(transaction)
1657				} else {
1658					None
1659				};
1660				write_tlv_fields!(writer, {
1661					(0, channel_id, required),
1662					(2, transaction, option),
1663					(4, funding_info, required),
1664				})
1665			},
1666			&Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1667				13u8.write(writer)?;
1668				write_tlv_fields!(writer, {
1669					(0, payment_id, required),
1670					(2, payment_hash, option),
1671					(4, path.hops, required_vec),
1672					(6, path.blinded_tail, option),
1673				})
1674			},
1675			&Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
1676				15u8.write(writer)?;
1677				let (payment_hash, invoice_received) = match payment_hash {
1678					Some(payment_hash) => (payment_hash, true),
1679					None => (&PaymentHash([0; 32]), false),
1680				};
1681				let legacy_reason = match reason {
1682					None => &None,
1683					// Variants available prior to version 0.0.124.
1684					Some(PaymentFailureReason::RecipientRejected)
1685						| Some(PaymentFailureReason::UserAbandoned)
1686						| Some(PaymentFailureReason::RetriesExhausted)
1687						| Some(PaymentFailureReason::PaymentExpired)
1688						| Some(PaymentFailureReason::RouteNotFound)
1689						| Some(PaymentFailureReason::UnexpectedError) => reason,
1690					// Variants introduced at version 0.0.124 or later. Prior versions fail to parse
1691					// unknown variants, while versions 0.0.124 or later will use None.
1692					Some(PaymentFailureReason::UnknownRequiredFeatures) =>
1693						&Some(PaymentFailureReason::RecipientRejected),
1694					Some(PaymentFailureReason::InvoiceRequestExpired) =>
1695						&Some(PaymentFailureReason::RetriesExhausted),
1696					Some(PaymentFailureReason::InvoiceRequestRejected) =>
1697						&Some(PaymentFailureReason::RecipientRejected),
1698					Some(PaymentFailureReason::BlindedPathCreationFailed) =>
1699						&Some(PaymentFailureReason::RouteNotFound)
1700				};
1701				write_tlv_fields!(writer, {
1702					(0, payment_id, required),
1703					(1, legacy_reason, option),
1704					(2, payment_hash, required),
1705					(3, invoice_received, required),
1706					(5, reason, option),
1707				})
1708			},
1709			&Event::OpenChannelRequest { .. } => {
1710				17u8.write(writer)?;
1711				// We never write the OpenChannelRequest events as, upon disconnection, peers
1712				// drop any channels which have not yet exchanged funding_signed.
1713			},
1714			&Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose,
1715				ref receiver_node_id, ref htlcs, ref sender_intended_total_msat, ref onion_fields,
1716				ref payment_id,
1717			} => {
1718				19u8.write(writer)?;
1719				write_tlv_fields!(writer, {
1720					(0, payment_hash, required),
1721					(1, receiver_node_id, option),
1722					(2, purpose, required),
1723					(4, amount_msat, required),
1724					(5, *htlcs, optional_vec),
1725					(7, sender_intended_total_msat, option),
1726					(9, onion_fields, option),
1727					(11, payment_id, option),
1728				});
1729			},
1730			&Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1731				21u8.write(writer)?;
1732				write_tlv_fields!(writer, {
1733					(0, payment_id, required),
1734					(2, payment_hash, required),
1735					(4, path.hops, required_vec),
1736					(6, path.blinded_tail, option),
1737				})
1738			},
1739			&Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1740				23u8.write(writer)?;
1741				write_tlv_fields!(writer, {
1742					(0, payment_id, required),
1743					(2, payment_hash, required),
1744					(4, path.hops, required_vec),
1745					(6, short_channel_id, option),
1746					(8, path.blinded_tail, option),
1747				})
1748			},
1749			&Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1750				25u8.write(writer)?;
1751				write_tlv_fields!(writer, {
1752					(0, prev_channel_id, required),
1753					(2, failed_next_destination, required),
1754				})
1755			},
1756			&Event::BumpTransaction(ref event)=> {
1757				27u8.write(writer)?;
1758				match event {
1759					// We never write the ChannelClose|HTLCResolution events as they'll be replayed
1760					// upon restarting anyway if they remain unresolved.
1761					BumpTransactionEvent::ChannelClose { .. } => {}
1762					BumpTransactionEvent::HTLCResolution { .. } => {}
1763				}
1764				write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1765			}
1766			&Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1767				29u8.write(writer)?;
1768				write_tlv_fields!(writer, {
1769					(0, channel_id, required),
1770					(2, user_channel_id, required),
1771					(4, counterparty_node_id, required),
1772					(6, channel_type, required),
1773				});
1774			},
1775			&Event::ChannelPending { ref channel_id, ref user_channel_id,
1776				ref former_temporary_channel_id, ref counterparty_node_id, ref funding_txo,
1777				ref channel_type
1778			} => {
1779				31u8.write(writer)?;
1780				write_tlv_fields!(writer, {
1781					(0, channel_id, required),
1782					(1, channel_type, option),
1783					(2, user_channel_id, required),
1784					(4, former_temporary_channel_id, required),
1785					(6, counterparty_node_id, required),
1786					(8, funding_txo, required),
1787				});
1788			},
1789			&Event::ConnectionNeeded { .. } => {
1790				35u8.write(writer)?;
1791				// Never write ConnectionNeeded events as buffered onion messages aren't serialized.
1792			},
1793			&Event::OnionMessageIntercepted { ref peer_node_id, ref message } => {
1794				37u8.write(writer)?;
1795				write_tlv_fields!(writer, {
1796					(0, peer_node_id, required),
1797					(2, message, required),
1798				});
1799			},
1800			&Event::OnionMessagePeerConnected { ref peer_node_id } => {
1801				39u8.write(writer)?;
1802				write_tlv_fields!(writer, {
1803					(0, peer_node_id, required),
1804				});
1805			},
1806			&Event::InvoiceReceived { ref payment_id, ref invoice, ref context, ref responder } => {
1807				41u8.write(writer)?;
1808				write_tlv_fields!(writer, {
1809					(0, payment_id, required),
1810					(2, invoice, required),
1811					(4, context, option),
1812					(6, responder, option),
1813				});
1814			},
1815			&Event::FundingTxBroadcastSafe { ref channel_id, ref user_channel_id, ref funding_txo, ref counterparty_node_id, ref former_temporary_channel_id} => {
1816				43u8.write(writer)?;
1817				write_tlv_fields!(writer, {
1818					(0, channel_id, required),
1819					(2, user_channel_id, required),
1820					(4, funding_txo, required),
1821					(6, counterparty_node_id, required),
1822					(8, former_temporary_channel_id, required),
1823				});
1824			},
1825			// Note that, going forward, all new events must only write data inside of
1826			// `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1827			// data via `write_tlv_fields`.
1828		}
1829		Ok(())
1830	}
1831}
1832impl MaybeReadable for Event {
1833	fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1834		match Readable::read(reader)? {
1835			// Note that we do not write a length-prefixed TLV for FundingGenerationReady events.
1836			0u8 => Ok(None),
1837			1u8 => {
1838				let mut f = || {
1839					let mut payment_hash = PaymentHash([0; 32]);
1840					let mut payment_preimage = None;
1841					let mut payment_secret = None;
1842					let mut amount_msat = 0;
1843					let mut counterparty_skimmed_fee_msat_opt = None;
1844					let mut receiver_node_id = None;
1845					let mut _user_payment_id = None::<u64>; // Used in 0.0.103 and earlier, no longer written in 0.0.116+.
1846					let mut via_channel_id = None;
1847					let mut claim_deadline = None;
1848					let mut via_user_channel_id = None;
1849					let mut onion_fields = None;
1850					let mut payment_context = None;
1851					let mut payment_id = None;
1852					read_tlv_fields!(reader, {
1853						(0, payment_hash, required),
1854						(1, receiver_node_id, option),
1855						(2, payment_secret, option),
1856						(3, via_channel_id, option),
1857						(4, amount_msat, required),
1858						(5, via_user_channel_id, option),
1859						(6, _user_payment_id, option),
1860						(7, claim_deadline, option),
1861						(8, payment_preimage, option),
1862						(9, onion_fields, option),
1863						(10, counterparty_skimmed_fee_msat_opt, option),
1864						(11, payment_context, option),
1865						(13, payment_id, option),
1866					});
1867					let purpose = match payment_secret {
1868						Some(secret) => PaymentPurpose::from_parts(payment_preimage, secret, payment_context),
1869						None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1870						None => return Err(msgs::DecodeError::InvalidValue),
1871					};
1872					Ok(Some(Event::PaymentClaimable {
1873						receiver_node_id,
1874						payment_hash,
1875						amount_msat,
1876						counterparty_skimmed_fee_msat: counterparty_skimmed_fee_msat_opt.unwrap_or(0),
1877						purpose,
1878						via_channel_id,
1879						via_user_channel_id,
1880						claim_deadline,
1881						onion_fields,
1882						payment_id,
1883					}))
1884				};
1885				f()
1886			},
1887			2u8 => {
1888				let mut f = || {
1889					let mut payment_preimage = PaymentPreimage([0; 32]);
1890					let mut payment_hash = None;
1891					let mut payment_id = None;
1892					let mut fee_paid_msat = None;
1893					read_tlv_fields!(reader, {
1894						(0, payment_preimage, required),
1895						(1, payment_hash, option),
1896						(3, payment_id, option),
1897						(5, fee_paid_msat, option),
1898					});
1899					if payment_hash.is_none() {
1900						payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()));
1901					}
1902					Ok(Some(Event::PaymentSent {
1903						payment_id,
1904						payment_preimage,
1905						payment_hash: payment_hash.unwrap(),
1906						fee_paid_msat,
1907					}))
1908				};
1909				f()
1910			},
1911			3u8 => {
1912				let mut f = || {
1913					#[cfg(test)]
1914					let error_code = Readable::read(reader)?;
1915					#[cfg(test)]
1916					let error_data = Readable::read(reader)?;
1917					let mut payment_hash = PaymentHash([0; 32]);
1918					let mut payment_failed_permanently = false;
1919					let mut network_update = None;
1920					let mut blinded_tail: Option<BlindedTail> = None;
1921					let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1922					let mut short_channel_id = None;
1923					let mut payment_id = None;
1924					let mut failure_opt = None;
1925					read_tlv_fields!(reader, {
1926						(0, payment_hash, required),
1927						(1, network_update, upgradable_option),
1928						(2, payment_failed_permanently, required),
1929						(4, blinded_tail, option),
1930						// Added as a part of LDK 0.0.101 and always filled in since.
1931						// Defaults to an empty Vec, though likely should have been `Option`al.
1932						(5, path, optional_vec),
1933						(7, short_channel_id, option),
1934						(11, payment_id, option),
1935						(13, failure_opt, upgradable_option),
1936					});
1937					let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1938					Ok(Some(Event::PaymentPathFailed {
1939						payment_id,
1940						payment_hash,
1941						payment_failed_permanently,
1942						failure,
1943						path: Path { hops: path.unwrap(), blinded_tail },
1944						short_channel_id,
1945						#[cfg(test)]
1946						error_code,
1947						#[cfg(test)]
1948						error_data,
1949					}))
1950				};
1951				f()
1952			},
1953			4u8 => Ok(None),
1954			5u8 => {
1955				let mut f = || {
1956					let mut outputs = WithoutLength(Vec::new());
1957					let mut channel_id: Option<ChannelId> = None;
1958					read_tlv_fields!(reader, {
1959						(0, outputs, required),
1960						(1, channel_id, option),
1961					});
1962					Ok(Some(Event::SpendableOutputs { outputs: outputs.0, channel_id }))
1963				};
1964				f()
1965			},
1966			6u8 => {
1967				let mut payment_hash = PaymentHash([0; 32]);
1968				let mut intercept_id = InterceptId([0; 32]);
1969				let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1970				let mut inbound_amount_msat = 0;
1971				let mut expected_outbound_amount_msat = 0;
1972				read_tlv_fields!(reader, {
1973					(0, intercept_id, required),
1974					(2, requested_next_hop_scid, required),
1975					(4, payment_hash, required),
1976					(6, inbound_amount_msat, required),
1977					(8, expected_outbound_amount_msat, required),
1978				});
1979				let next_scid = match requested_next_hop_scid {
1980					InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1981				};
1982				Ok(Some(Event::HTLCIntercepted {
1983					payment_hash,
1984					requested_next_hop_scid: next_scid,
1985					inbound_amount_msat,
1986					expected_outbound_amount_msat,
1987					intercept_id,
1988				}))
1989			},
1990			7u8 => {
1991				let mut f = || {
1992					let mut prev_channel_id = None;
1993					let mut next_channel_id = None;
1994					let mut prev_user_channel_id = None;
1995					let mut next_user_channel_id = None;
1996					let mut prev_node_id = None;
1997					let mut next_node_id = None;
1998					let mut total_fee_earned_msat = None;
1999					let mut skimmed_fee_msat = None;
2000					let mut claim_from_onchain_tx = false;
2001					let mut outbound_amount_forwarded_msat = None;
2002					read_tlv_fields!(reader, {
2003						(0, total_fee_earned_msat, option),
2004						(1, prev_channel_id, option),
2005						(2, claim_from_onchain_tx, required),
2006						(3, next_channel_id, option),
2007						(5, outbound_amount_forwarded_msat, option),
2008						(7, skimmed_fee_msat, option),
2009						(9, prev_user_channel_id, option),
2010						(11, next_user_channel_id, option),
2011						(13, prev_node_id, option),
2012						(15, next_node_id, option),
2013					});
2014					Ok(Some(Event::PaymentForwarded {
2015						prev_channel_id, next_channel_id, prev_user_channel_id,
2016						next_user_channel_id, prev_node_id, next_node_id,
2017						total_fee_earned_msat, skimmed_fee_msat, claim_from_onchain_tx,
2018						outbound_amount_forwarded_msat,
2019					}))
2020				};
2021				f()
2022			},
2023			9u8 => {
2024				let mut f = || {
2025					let mut channel_id = ChannelId::new_zero();
2026					let mut reason = UpgradableRequired(None);
2027					let mut user_channel_id_low_opt: Option<u64> = None;
2028					let mut user_channel_id_high_opt: Option<u64> = None;
2029					let mut counterparty_node_id = None;
2030					let mut channel_capacity_sats = None;
2031					let mut channel_funding_txo = None;
2032					let mut last_local_balance_msat = None;
2033					read_tlv_fields!(reader, {
2034						(0, channel_id, required),
2035						(1, user_channel_id_low_opt, option),
2036						(2, reason, upgradable_required),
2037						(3, user_channel_id_high_opt, option),
2038						(5, counterparty_node_id, option),
2039						(7, channel_capacity_sats, option),
2040						(9, channel_funding_txo, option),
2041						(11, last_local_balance_msat, option)
2042					});
2043
2044					// `user_channel_id` used to be a single u64 value. In order to remain
2045					// backwards compatible with versions prior to 0.0.113, the u128 is serialized
2046					// as two separate u64 values.
2047					let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
2048						((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
2049
2050					Ok(Some(Event::ChannelClosed {
2051						channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required),
2052						counterparty_node_id, channel_capacity_sats, channel_funding_txo, last_local_balance_msat,
2053					}))
2054				};
2055				f()
2056			},
2057			11u8 => {
2058				let mut f = || {
2059					let mut channel_id = ChannelId::new_zero();
2060					let mut transaction: Option<Transaction> = None;
2061					let mut funding_info: Option<FundingInfo> = None;
2062					read_tlv_fields!(reader, {
2063						(0, channel_id, required),
2064						(2, transaction, option),
2065						(4, funding_info, option),
2066					});
2067
2068					let funding_info = if let Some(tx) = transaction {
2069						FundingInfo::Tx { transaction: tx }
2070					} else {
2071						funding_info.ok_or(msgs::DecodeError::InvalidValue)?
2072					};
2073					Ok(Some(Event::DiscardFunding { channel_id, funding_info } ))
2074				};
2075				f()
2076			},
2077			13u8 => {
2078				let mut f = || {
2079					_init_and_read_len_prefixed_tlv_fields!(reader, {
2080						(0, payment_id, required),
2081						(2, payment_hash, option),
2082						(4, path, required_vec),
2083						(6, blinded_tail, option),
2084					});
2085					Ok(Some(Event::PaymentPathSuccessful {
2086						payment_id: payment_id.0.unwrap(),
2087						payment_hash,
2088						path: Path { hops: path, blinded_tail },
2089					}))
2090				};
2091				f()
2092			},
2093			15u8 => {
2094				let mut f = || {
2095					let mut payment_hash = PaymentHash([0; 32]);
2096					let mut payment_id = PaymentId([0; 32]);
2097					let mut reason = None;
2098					let mut legacy_reason = None;
2099					let mut invoice_received: Option<bool> = None;
2100					read_tlv_fields!(reader, {
2101						(0, payment_id, required),
2102						(1, legacy_reason, upgradable_option),
2103						(2, payment_hash, required),
2104						(3, invoice_received, option),
2105						(5, reason, upgradable_option),
2106					});
2107					let payment_hash = match invoice_received {
2108						Some(invoice_received) => invoice_received.then(|| payment_hash),
2109						None => (payment_hash != PaymentHash([0; 32])).then(|| payment_hash),
2110					};
2111					let reason = reason.or(legacy_reason);
2112					Ok(Some(Event::PaymentFailed {
2113						payment_id,
2114						payment_hash,
2115						reason: _init_tlv_based_struct_field!(reason, upgradable_option),
2116					}))
2117				};
2118				f()
2119			},
2120			17u8 => {
2121				// Value 17 is used for `Event::OpenChannelRequest`.
2122				Ok(None)
2123			},
2124			19u8 => {
2125				let mut f = || {
2126					let mut payment_hash = PaymentHash([0; 32]);
2127					let mut purpose = UpgradableRequired(None);
2128					let mut amount_msat = 0;
2129					let mut receiver_node_id = None;
2130					let mut htlcs: Option<Vec<ClaimedHTLC>> = Some(vec![]);
2131					let mut sender_intended_total_msat: Option<u64> = None;
2132					let mut onion_fields = None;
2133					let mut payment_id = None;
2134					read_tlv_fields!(reader, {
2135						(0, payment_hash, required),
2136						(1, receiver_node_id, option),
2137						(2, purpose, upgradable_required),
2138						(4, amount_msat, required),
2139						(5, htlcs, optional_vec),
2140						(7, sender_intended_total_msat, option),
2141						(9, onion_fields, option),
2142						(11, payment_id, option),
2143					});
2144					Ok(Some(Event::PaymentClaimed {
2145						receiver_node_id,
2146						payment_hash,
2147						purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
2148						amount_msat,
2149						htlcs: htlcs.unwrap_or_default(),
2150						sender_intended_total_msat,
2151						onion_fields,
2152						payment_id,
2153					}))
2154				};
2155				f()
2156			},
2157			21u8 => {
2158				let mut f = || {
2159					_init_and_read_len_prefixed_tlv_fields!(reader, {
2160						(0, payment_id, required),
2161						(2, payment_hash, required),
2162						(4, path, required_vec),
2163						(6, blinded_tail, option),
2164					});
2165					Ok(Some(Event::ProbeSuccessful {
2166						payment_id: payment_id.0.unwrap(),
2167						payment_hash: payment_hash.0.unwrap(),
2168						path: Path { hops: path, blinded_tail },
2169					}))
2170				};
2171				f()
2172			},
2173			23u8 => {
2174				let mut f = || {
2175					_init_and_read_len_prefixed_tlv_fields!(reader, {
2176						(0, payment_id, required),
2177						(2, payment_hash, required),
2178						(4, path, required_vec),
2179						(6, short_channel_id, option),
2180						(8, blinded_tail, option),
2181					});
2182					Ok(Some(Event::ProbeFailed {
2183						payment_id: payment_id.0.unwrap(),
2184						payment_hash: payment_hash.0.unwrap(),
2185						path: Path { hops: path, blinded_tail },
2186						short_channel_id,
2187					}))
2188				};
2189				f()
2190			},
2191			25u8 => {
2192				let mut f = || {
2193					let mut prev_channel_id = ChannelId::new_zero();
2194					let mut failed_next_destination_opt = UpgradableRequired(None);
2195					read_tlv_fields!(reader, {
2196						(0, prev_channel_id, required),
2197						(2, failed_next_destination_opt, upgradable_required),
2198					});
2199					Ok(Some(Event::HTLCHandlingFailed {
2200						prev_channel_id,
2201						failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
2202					}))
2203				};
2204				f()
2205			},
2206			27u8 => Ok(None),
2207			29u8 => {
2208				let mut f = || {
2209					let mut channel_id = ChannelId::new_zero();
2210					let mut user_channel_id: u128 = 0;
2211					let mut counterparty_node_id = RequiredWrapper(None);
2212					let mut channel_type = RequiredWrapper(None);
2213					read_tlv_fields!(reader, {
2214						(0, channel_id, required),
2215						(2, user_channel_id, required),
2216						(4, counterparty_node_id, required),
2217						(6, channel_type, required),
2218					});
2219
2220					Ok(Some(Event::ChannelReady {
2221						channel_id,
2222						user_channel_id,
2223						counterparty_node_id: counterparty_node_id.0.unwrap(),
2224						channel_type: channel_type.0.unwrap()
2225					}))
2226				};
2227				f()
2228			},
2229			31u8 => {
2230				let mut f = || {
2231					let mut channel_id = ChannelId::new_zero();
2232					let mut user_channel_id: u128 = 0;
2233					let mut former_temporary_channel_id = None;
2234					let mut counterparty_node_id = RequiredWrapper(None);
2235					let mut funding_txo = RequiredWrapper(None);
2236					let mut channel_type = None;
2237					read_tlv_fields!(reader, {
2238						(0, channel_id, required),
2239						(1, channel_type, option),
2240						(2, user_channel_id, required),
2241						(4, former_temporary_channel_id, required),
2242						(6, counterparty_node_id, required),
2243						(8, funding_txo, required),
2244					});
2245
2246					Ok(Some(Event::ChannelPending {
2247						channel_id,
2248						user_channel_id,
2249						former_temporary_channel_id,
2250						counterparty_node_id: counterparty_node_id.0.unwrap(),
2251						funding_txo: funding_txo.0.unwrap(),
2252						channel_type,
2253					}))
2254				};
2255				f()
2256			},
2257			// This was Event::InvoiceRequestFailed prior to version 0.0.124.
2258			33u8 => {
2259				let mut f = || {
2260					_init_and_read_len_prefixed_tlv_fields!(reader, {
2261						(0, payment_id, required),
2262					});
2263					Ok(Some(Event::PaymentFailed {
2264						payment_id: payment_id.0.unwrap(),
2265						payment_hash: None,
2266						reason: Some(PaymentFailureReason::InvoiceRequestExpired),
2267					}))
2268				};
2269				f()
2270			},
2271			// Note that we do not write a length-prefixed TLV for ConnectionNeeded events.
2272			35u8 => Ok(None),
2273			37u8 => {
2274				let mut f = || {
2275					_init_and_read_len_prefixed_tlv_fields!(reader, {
2276						(0, peer_node_id, required),
2277						(2, message, required),
2278					});
2279					Ok(Some(Event::OnionMessageIntercepted {
2280						peer_node_id: peer_node_id.0.unwrap(), message: message.0.unwrap()
2281					}))
2282				};
2283				f()
2284			},
2285			39u8 => {
2286				let mut f = || {
2287					_init_and_read_len_prefixed_tlv_fields!(reader, {
2288						(0, peer_node_id, required),
2289					});
2290					Ok(Some(Event::OnionMessagePeerConnected {
2291						peer_node_id: peer_node_id.0.unwrap()
2292					}))
2293				};
2294				f()
2295			},
2296			41u8 => {
2297				let mut f = || {
2298					_init_and_read_len_prefixed_tlv_fields!(reader, {
2299						(0, payment_id, required),
2300						(2, invoice, required),
2301						(4, context, option),
2302						(6, responder, option),
2303					});
2304					Ok(Some(Event::InvoiceReceived {
2305						payment_id: payment_id.0.unwrap(),
2306						invoice: invoice.0.unwrap(),
2307						context,
2308						responder,
2309					}))
2310				};
2311				f()
2312			},
2313			43u8 => {
2314				let mut channel_id = RequiredWrapper(None);
2315				let mut user_channel_id = RequiredWrapper(None);
2316				let mut funding_txo = RequiredWrapper(None);
2317				let mut counterparty_node_id = RequiredWrapper(None);
2318				let mut former_temporary_channel_id = RequiredWrapper(None);
2319				read_tlv_fields!(reader, {
2320					(0, channel_id, required),
2321					(2, user_channel_id, required),
2322					(4, funding_txo, required),
2323					(6, counterparty_node_id, required),
2324					(8, former_temporary_channel_id, required)
2325				});
2326				Ok(Some(Event::FundingTxBroadcastSafe {
2327					channel_id: channel_id.0.unwrap(),
2328					user_channel_id: user_channel_id.0.unwrap(),
2329					funding_txo: funding_txo.0.unwrap(),
2330					counterparty_node_id: counterparty_node_id.0.unwrap(),
2331					former_temporary_channel_id: former_temporary_channel_id.0.unwrap(),
2332				}))
2333			},
2334			// Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
2335			// Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
2336			// reads.
2337			x if x % 2 == 1 => {
2338				// If the event is of unknown type, assume it was written with `write_tlv_fields`,
2339				// which prefixes the whole thing with a length BigSize. Because the event is
2340				// odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
2341				// fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
2342				// exactly the number of bytes specified, ignoring them entirely.
2343				let tlv_len: BigSize = Readable::read(reader)?;
2344				FixedLengthReader::new(reader, tlv_len.0)
2345					.eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
2346				Ok(None)
2347			},
2348			_ => Err(msgs::DecodeError::InvalidValue)
2349		}
2350	}
2351}
2352
2353/// An event generated by ChannelManager which indicates a message should be sent to a peer (or
2354/// broadcast to most peers).
2355/// These events are handled by PeerManager::process_events if you are using a PeerManager.
2356#[derive(Clone, Debug)]
2357#[cfg_attr(test, derive(PartialEq))]
2358pub enum MessageSendEvent {
2359	/// Used to indicate that we've accepted a channel open and should send the accept_channel
2360	/// message provided to the given peer.
2361	SendAcceptChannel {
2362		/// The node_id of the node which should receive this message
2363		node_id: PublicKey,
2364		/// The message which should be sent.
2365		msg: msgs::AcceptChannel,
2366	},
2367	/// Used to indicate that we've accepted a V2 channel open and should send the accept_channel2
2368	/// message provided to the given peer.
2369	SendAcceptChannelV2 {
2370		/// The node_id of the node which should receive this message
2371		node_id: PublicKey,
2372		/// The message which should be sent.
2373		msg: msgs::AcceptChannelV2,
2374	},
2375	/// Used to indicate that we've initiated a channel open and should send the open_channel
2376	/// message provided to the given peer.
2377	SendOpenChannel {
2378		/// The node_id of the node which should receive this message
2379		node_id: PublicKey,
2380		/// The message which should be sent.
2381		msg: msgs::OpenChannel,
2382	},
2383	/// Used to indicate that we've initiated a V2 channel open and should send the open_channel2
2384	/// message provided to the given peer.
2385	SendOpenChannelV2 {
2386		/// The node_id of the node which should receive this message
2387		node_id: PublicKey,
2388		/// The message which should be sent.
2389		msg: msgs::OpenChannelV2,
2390	},
2391	/// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
2392	SendFundingCreated {
2393		/// The node_id of the node which should receive this message
2394		node_id: PublicKey,
2395		/// The message which should be sent.
2396		msg: msgs::FundingCreated,
2397	},
2398	/// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
2399	SendFundingSigned {
2400		/// The node_id of the node which should receive this message
2401		node_id: PublicKey,
2402		/// The message which should be sent.
2403		msg: msgs::FundingSigned,
2404	},
2405	/// Used to indicate that a stfu message should be sent to the peer with the given node id.
2406	SendStfu {
2407		/// The node_id of the node which should receive this message
2408		node_id: PublicKey,
2409		/// The message which should be sent.
2410		msg: msgs::Stfu,
2411	},
2412	/// Used to indicate that a splice_init message should be sent to the peer with the given node id.
2413	SendSpliceInit {
2414		/// The node_id of the node which should receive this message
2415		node_id: PublicKey,
2416		/// The message which should be sent.
2417		msg: msgs::SpliceInit,
2418	},
2419	/// Used to indicate that a splice_ack message should be sent to the peer with the given node id.
2420	SendSpliceAck {
2421		/// The node_id of the node which should receive this message
2422		node_id: PublicKey,
2423		/// The message which should be sent.
2424		msg: msgs::SpliceAck,
2425	},
2426	/// Used to indicate that a splice_locked message should be sent to the peer with the given node id.
2427	SendSpliceLocked {
2428		/// The node_id of the node which should receive this message
2429		node_id: PublicKey,
2430		/// The message which should be sent.
2431		msg: msgs::SpliceLocked,
2432	},
2433	/// Used to indicate that a tx_add_input message should be sent to the peer with the given node_id.
2434	SendTxAddInput {
2435		/// The node_id of the node which should receive this message
2436		node_id: PublicKey,
2437		/// The message which should be sent.
2438		msg: msgs::TxAddInput,
2439	},
2440	/// Used to indicate that a tx_add_output message should be sent to the peer with the given node_id.
2441	SendTxAddOutput {
2442		/// The node_id of the node which should receive this message
2443		node_id: PublicKey,
2444		/// The message which should be sent.
2445		msg: msgs::TxAddOutput,
2446	},
2447	/// Used to indicate that a tx_remove_input message should be sent to the peer with the given node_id.
2448	SendTxRemoveInput {
2449		/// The node_id of the node which should receive this message
2450		node_id: PublicKey,
2451		/// The message which should be sent.
2452		msg: msgs::TxRemoveInput,
2453	},
2454	/// Used to indicate that a tx_remove_output message should be sent to the peer with the given node_id.
2455	SendTxRemoveOutput {
2456		/// The node_id of the node which should receive this message
2457		node_id: PublicKey,
2458		/// The message which should be sent.
2459		msg: msgs::TxRemoveOutput,
2460	},
2461	/// Used to indicate that a tx_complete message should be sent to the peer with the given node_id.
2462	SendTxComplete {
2463		/// The node_id of the node which should receive this message
2464		node_id: PublicKey,
2465		/// The message which should be sent.
2466		msg: msgs::TxComplete,
2467	},
2468	/// Used to indicate that a tx_signatures message should be sent to the peer with the given node_id.
2469	SendTxSignatures {
2470		/// The node_id of the node which should receive this message
2471		node_id: PublicKey,
2472		/// The message which should be sent.
2473		msg: msgs::TxSignatures,
2474	},
2475	/// Used to indicate that a tx_init_rbf message should be sent to the peer with the given node_id.
2476	SendTxInitRbf {
2477		/// The node_id of the node which should receive this message
2478		node_id: PublicKey,
2479		/// The message which should be sent.
2480		msg: msgs::TxInitRbf,
2481	},
2482	/// Used to indicate that a tx_ack_rbf message should be sent to the peer with the given node_id.
2483	SendTxAckRbf {
2484		/// The node_id of the node which should receive this message
2485		node_id: PublicKey,
2486		/// The message which should be sent.
2487		msg: msgs::TxAckRbf,
2488	},
2489	/// Used to indicate that a tx_abort message should be sent to the peer with the given node_id.
2490	SendTxAbort {
2491		/// The node_id of the node which should receive this message
2492		node_id: PublicKey,
2493		/// The message which should be sent.
2494		msg: msgs::TxAbort,
2495	},
2496	/// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
2497	SendChannelReady {
2498		/// The node_id of the node which should receive these message(s)
2499		node_id: PublicKey,
2500		/// The channel_ready message which should be sent.
2501		msg: msgs::ChannelReady,
2502	},
2503	/// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
2504	SendAnnouncementSignatures {
2505		/// The node_id of the node which should receive these message(s)
2506		node_id: PublicKey,
2507		/// The announcement_signatures message which should be sent.
2508		msg: msgs::AnnouncementSignatures,
2509	},
2510	/// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
2511	/// message should be sent to the peer with the given node_id.
2512	UpdateHTLCs {
2513		/// The node_id of the node which should receive these message(s)
2514		node_id: PublicKey,
2515		/// The update messages which should be sent. ALL messages in the struct should be sent!
2516		updates: msgs::CommitmentUpdate,
2517	},
2518	/// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
2519	SendRevokeAndACK {
2520		/// The node_id of the node which should receive this message
2521		node_id: PublicKey,
2522		/// The message which should be sent.
2523		msg: msgs::RevokeAndACK,
2524	},
2525	/// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
2526	SendClosingSigned {
2527		/// The node_id of the node which should receive this message
2528		node_id: PublicKey,
2529		/// The message which should be sent.
2530		msg: msgs::ClosingSigned,
2531	},
2532	/// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
2533	SendShutdown {
2534		/// The node_id of the node which should receive this message
2535		node_id: PublicKey,
2536		/// The message which should be sent.
2537		msg: msgs::Shutdown,
2538	},
2539	/// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
2540	SendChannelReestablish {
2541		/// The node_id of the node which should receive this message
2542		node_id: PublicKey,
2543		/// The message which should be sent.
2544		msg: msgs::ChannelReestablish,
2545	},
2546	/// Used to send a channel_announcement and channel_update to a specific peer, likely on
2547	/// initial connection to ensure our peers know about our channels.
2548	SendChannelAnnouncement {
2549		/// The node_id of the node which should receive this message
2550		node_id: PublicKey,
2551		/// The channel_announcement which should be sent.
2552		msg: msgs::ChannelAnnouncement,
2553		/// The followup channel_update which should be sent.
2554		update_msg: msgs::ChannelUpdate,
2555	},
2556	/// Used to indicate that a channel_announcement and channel_update should be broadcast to all
2557	/// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
2558	///
2559	/// Note that after doing so, you very likely (unless you did so very recently) want to
2560	/// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
2561	/// ensures that any nodes which see our channel_announcement also have a relevant
2562	/// node_announcement, including relevant feature flags which may be important for routing
2563	/// through or to us.
2564	///
2565	/// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
2566	BroadcastChannelAnnouncement {
2567		/// The channel_announcement which should be sent.
2568		msg: msgs::ChannelAnnouncement,
2569		/// The followup channel_update which should be sent.
2570		update_msg: Option<msgs::ChannelUpdate>,
2571	},
2572	/// Used to indicate that a channel_update should be broadcast to all peers.
2573	BroadcastChannelUpdate {
2574		/// The channel_update which should be sent.
2575		msg: msgs::ChannelUpdate,
2576	},
2577	/// Used to indicate that a node_announcement should be broadcast to all peers.
2578	BroadcastNodeAnnouncement {
2579		/// The node_announcement which should be sent.
2580		msg: msgs::NodeAnnouncement,
2581	},
2582	/// Used to indicate that a channel_update should be sent to a single peer.
2583	/// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
2584	/// private channel and we shouldn't be informing all of our peers of channel parameters.
2585	SendChannelUpdate {
2586		/// The node_id of the node which should receive this message
2587		node_id: PublicKey,
2588		/// The channel_update which should be sent.
2589		msg: msgs::ChannelUpdate,
2590	},
2591	/// Broadcast an error downstream to be handled
2592	HandleError {
2593		/// The node_id of the node which should receive this message
2594		node_id: PublicKey,
2595		/// The action which should be taken.
2596		action: msgs::ErrorAction
2597	},
2598	/// Query a peer for channels with funding transaction UTXOs in a block range.
2599	SendChannelRangeQuery {
2600		/// The node_id of this message recipient
2601		node_id: PublicKey,
2602		/// The query_channel_range which should be sent.
2603		msg: msgs::QueryChannelRange,
2604	},
2605	/// Request routing gossip messages from a peer for a list of channels identified by
2606	/// their short_channel_ids.
2607	SendShortIdsQuery {
2608		/// The node_id of this message recipient
2609		node_id: PublicKey,
2610		/// The query_short_channel_ids which should be sent.
2611		msg: msgs::QueryShortChannelIds,
2612	},
2613	/// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
2614	/// emitted during processing of the query.
2615	SendReplyChannelRange {
2616		/// The node_id of this message recipient
2617		node_id: PublicKey,
2618		/// The reply_channel_range which should be sent.
2619		msg: msgs::ReplyChannelRange,
2620	},
2621	/// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
2622	/// enable receiving gossip messages from the peer.
2623	SendGossipTimestampFilter {
2624		/// The node_id of this message recipient
2625		node_id: PublicKey,
2626		/// The gossip_timestamp_filter which should be sent.
2627		msg: msgs::GossipTimestampFilter,
2628	},
2629}
2630
2631/// A trait indicating an object may generate message send events
2632pub trait MessageSendEventsProvider {
2633	/// Gets the list of pending events which were generated by previous actions, clearing the list
2634	/// in the process.
2635	fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
2636}
2637
2638/// A trait indicating an object may generate events.
2639///
2640/// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
2641///
2642/// Implementations of this trait may also feature an async version of event handling, as shown with
2643/// [`ChannelManager::process_pending_events_async`] and
2644/// [`ChainMonitor::process_pending_events_async`].
2645///
2646/// # Requirements
2647///
2648/// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
2649/// event since the last invocation.
2650///
2651/// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
2652/// and replay any unhandled events on startup. An [`Event`] is considered handled when
2653/// [`process_pending_events`] returns `Ok(())`, thus handlers MUST fully handle [`Event`]s and
2654/// persist any relevant changes to disk *before* returning `Ok(())`. In case of an error (e.g.,
2655/// persistence failure) implementors should return `Err(ReplayEvent())`, signalling to the
2656/// [`EventsProvider`] to replay unhandled events on the next invocation (generally immediately).
2657/// Note that some events might not be replayed, please refer to the documentation for
2658/// the individual [`Event`] variants for more detail.
2659///
2660/// Further, because an application may crash between an [`Event`] being handled and the
2661/// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
2662/// effect, [`Event`]s may be replayed.
2663///
2664/// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
2665/// consult the provider's documentation on the implication of processing events and how a handler
2666/// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
2667/// [`ChainMonitor::process_pending_events`]).
2668///
2669/// (C-not implementable) As there is likely no reason for a user to implement this trait on their
2670/// own type(s).
2671///
2672/// [`process_pending_events`]: Self::process_pending_events
2673/// [`handle_event`]: EventHandler::handle_event
2674/// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
2675/// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
2676/// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
2677/// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
2678pub trait EventsProvider {
2679	/// Processes any events generated since the last call using the given event handler.
2680	///
2681	/// See the trait-level documentation for requirements.
2682	fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
2683}
2684
2685/// An error type that may be returned to LDK in order to safely abort event handling if it can't
2686/// currently succeed (e.g., due to a persistence failure).
2687///
2688/// Depending on the type, LDK may ensure the event is persisted and will eventually be replayed.
2689/// Please refer to the documentation of each [`Event`] variant for more details.
2690#[derive(Clone, Copy, Debug)]
2691pub struct ReplayEvent();
2692
2693/// A trait implemented for objects handling events from [`EventsProvider`].
2694///
2695/// An async variation also exists for implementations of [`EventsProvider`] that support async
2696/// event handling. The async event handler should satisfy the generic bounds: `F:
2697/// core::future::Future<Output = Result<(), ReplayEvent>>, H: Fn(Event) -> F`.
2698pub trait EventHandler {
2699	/// Handles the given [`Event`].
2700	///
2701	/// See [`EventsProvider`] for details that must be considered when implementing this method.
2702	fn handle_event(&self, event: Event) -> Result<(), ReplayEvent>;
2703}
2704
2705impl<F> EventHandler for F where F: Fn(Event) -> Result<(), ReplayEvent> {
2706	fn handle_event(&self, event: Event) -> Result<(), ReplayEvent> {
2707		self(event)
2708	}
2709}
2710
2711impl<T: EventHandler> EventHandler for Arc<T> {
2712	fn handle_event(&self, event: Event) -> Result<(), ReplayEvent> {
2713		self.deref().handle_event(event)
2714	}
2715}