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