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