Update PaymentPurpose's payment_preimage docs
[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         /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
890         /// counterparty spending them due to some kind of timeout. Thus, you need to store them
891         /// somewhere and spend them when you create on-chain transactions.
892         SpendableOutputs {
893                 /// The outputs which you should store as spendable by you.
894                 outputs: Vec<SpendableOutputDescriptor>,
895                 /// The `channel_id` indicating which channel the spendable outputs belong to.
896                 ///
897                 /// This will always be `Some` for events generated by LDK versions 0.0.117 and above.
898                 channel_id: Option<ChannelId>,
899         },
900         /// This event is generated when a payment has been successfully forwarded through us and a
901         /// forwarding fee earned.
902         PaymentForwarded {
903                 /// The channel id of the incoming channel between the previous node and us.
904                 ///
905                 /// This is only `None` for events generated or serialized by versions prior to 0.0.107.
906                 prev_channel_id: Option<ChannelId>,
907                 /// The channel id of the outgoing channel between the next node and us.
908                 ///
909                 /// This is only `None` for events generated or serialized by versions prior to 0.0.107.
910                 next_channel_id: Option<ChannelId>,
911                 /// The `user_channel_id` of the incoming channel between the previous node and us.
912                 ///
913                 /// This is only `None` for events generated or serialized by versions prior to 0.0.122.
914                 prev_user_channel_id: Option<u128>,
915                 /// The `user_channel_id` of the outgoing channel between the next node and us.
916                 ///
917                 /// This will be `None` if the payment was settled via an on-chain transaction. See the
918                 /// caveat described for the `total_fee_earned_msat` field. Moreover it will be `None` for
919                 /// events generated or serialized by versions prior to 0.0.122.
920                 next_user_channel_id: Option<u128>,
921                 /// The total fee, in milli-satoshis, which was earned as a result of the payment.
922                 ///
923                 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
924                 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
925                 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
926                 /// claimed the full value in millisatoshis from the source. In this case,
927                 /// `claim_from_onchain_tx` will be set.
928                 ///
929                 /// If the channel which sent us the payment has been force-closed, we will claim the funds
930                 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
931                 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
932                 /// `PaymentForwarded` events are generated for the same payment iff `total_fee_earned_msat` is
933                 /// `None`.
934                 total_fee_earned_msat: Option<u64>,
935                 /// The share of the total fee, in milli-satoshis, which was withheld in addition to the
936                 /// forwarding fee.
937                 ///
938                 /// This will only be `Some` if we forwarded an intercepted HTLC with less than the
939                 /// expected amount. This means our counterparty accepted to receive less than the invoice
940                 /// amount, e.g., by claiming the payment featuring a corresponding
941                 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`].
942                 ///
943                 /// Will also always be `None` for events serialized with LDK prior to version 0.0.122.
944                 ///
945                 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
946                 ///
947                 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`]: Self::PaymentClaimable::counterparty_skimmed_fee_msat
948                 skimmed_fee_msat: Option<u64>,
949                 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
950                 /// transaction.
951                 claim_from_onchain_tx: bool,
952                 /// The final amount forwarded, in milli-satoshis, after the fee is deducted.
953                 ///
954                 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
955                 outbound_amount_forwarded_msat: Option<u64>,
956         },
957         /// Used to indicate that a channel with the given `channel_id` is being opened and pending
958         /// confirmation on-chain.
959         ///
960         /// This event is emitted when the funding transaction has been signed and is broadcast to the
961         /// network. For 0conf channels it will be immediately followed by the corresponding
962         /// [`Event::ChannelReady`] event.
963         ChannelPending {
964                 /// The `channel_id` of the channel that is pending confirmation.
965                 channel_id: ChannelId,
966                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
967                 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
968                 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
969                 /// `user_channel_id` will be randomized for an inbound channel.
970                 ///
971                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
972                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
973                 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
974                 user_channel_id: u128,
975                 /// The `temporary_channel_id` this channel used to be known by during channel establishment.
976                 ///
977                 /// Will be `None` for channels created prior to LDK version 0.0.115.
978                 former_temporary_channel_id: Option<ChannelId>,
979                 /// The `node_id` of the channel counterparty.
980                 counterparty_node_id: PublicKey,
981                 /// The outpoint of the channel's funding transaction.
982                 funding_txo: OutPoint,
983                 /// The features that this channel will operate with.
984                 ///
985                 /// Will be `None` for channels created prior to LDK version 0.0.122.
986                 channel_type: Option<ChannelTypeFeatures>,
987         },
988         /// Used to indicate that a channel with the given `channel_id` is ready to
989         /// be used. This event is emitted either when the funding transaction has been confirmed
990         /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
991         /// establishment.
992         ChannelReady {
993                 /// The `channel_id` of the channel that is ready.
994                 channel_id: ChannelId,
995                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
996                 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
997                 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
998                 /// `user_channel_id` will be randomized for an inbound channel.
999                 ///
1000                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1001                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1002                 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1003                 user_channel_id: u128,
1004                 /// The `node_id` of the channel counterparty.
1005                 counterparty_node_id: PublicKey,
1006                 /// The features that this channel will operate with.
1007                 channel_type: ChannelTypeFeatures,
1008         },
1009         /// Used to indicate that a previously opened channel with the given `channel_id` is in the
1010         /// process of closure.
1011         ///
1012         /// Note that this event is only triggered for accepted channels: if the
1013         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true and the channel is
1014         /// rejected, no `ChannelClosed` event will be sent.
1015         ///
1016         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1017         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1018         ChannelClosed {
1019                 /// The `channel_id` of the channel which has been closed. Note that on-chain transactions
1020                 /// resolving the channel are likely still awaiting confirmation.
1021                 channel_id: ChannelId,
1022                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1023                 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1024                 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1025                 /// `user_channel_id` will be randomized for inbound channels.
1026                 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
1027                 /// zero for objects serialized with LDK versions prior to 0.0.102.
1028                 ///
1029                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1030                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1031                 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1032                 user_channel_id: u128,
1033                 /// The reason the channel was closed.
1034                 reason: ClosureReason,
1035                 /// Counterparty in the closed channel.
1036                 ///
1037                 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
1038                 counterparty_node_id: Option<PublicKey>,
1039                 /// Channel capacity of the closing channel (sats).
1040                 ///
1041                 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
1042                 channel_capacity_sats: Option<u64>,
1043                 /// The original channel funding TXO; this helps checking for the existence and confirmation
1044                 /// status of the closing tx.
1045                 /// Note that for instances serialized in v0.0.119 or prior this will be missing (None).
1046                 channel_funding_txo: Option<transaction::OutPoint>,
1047         },
1048         /// Used to indicate to the user that they can abandon the funding transaction and recycle the
1049         /// inputs for another purpose.
1050         ///
1051         /// This event is not guaranteed to be generated for channels that are closed due to a restart.
1052         DiscardFunding {
1053                 /// The channel_id of the channel which has been closed.
1054                 channel_id: ChannelId,
1055                 /// The full transaction received from the user
1056                 transaction: Transaction
1057         },
1058         /// Indicates a request to open a new channel by a peer.
1059         ///
1060         /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the request,
1061         /// call [`ChannelManager::force_close_without_broadcasting_txn`]. Note that a ['ChannelClosed`]
1062         /// event will _not_ be triggered if the channel is rejected.
1063         ///
1064         /// The event is only triggered when a new open channel request is received and the
1065         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
1066         ///
1067         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1068         /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1069         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1070         OpenChannelRequest {
1071                 /// The temporary channel ID of the channel requested to be opened.
1072                 ///
1073                 /// When responding to the request, the `temporary_channel_id` should be passed
1074                 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
1075                 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
1076                 ///
1077                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1078                 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1079                 temporary_channel_id: ChannelId,
1080                 /// The node_id of the counterparty requesting to open the channel.
1081                 ///
1082                 /// When responding to the request, the `counterparty_node_id` should be passed
1083                 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
1084                 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
1085                 /// request.
1086                 ///
1087                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1088                 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1089                 counterparty_node_id: PublicKey,
1090                 /// The channel value of the requested channel.
1091                 funding_satoshis: u64,
1092                 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
1093                 push_msat: u64,
1094                 /// The features that this channel will operate with. If you reject the channel, a
1095                 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
1096                 /// feature flags.
1097                 ///
1098                 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
1099                 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1100                 /// 0.0.106.
1101                 ///
1102                 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
1103                 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1104                 /// 0.0.107. Channels setting this type also need to get manually accepted via
1105                 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
1106                 /// or will be rejected otherwise.
1107                 ///
1108                 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1109                 channel_type: ChannelTypeFeatures,
1110         },
1111         /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
1112         /// forward it.
1113         ///
1114         /// Some scenarios where this event may be sent include:
1115         /// * Insufficient capacity in the outbound channel
1116         /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
1117         /// * When an unknown SCID is requested for forwarding a payment.
1118         /// * Expected MPP amount has already been reached
1119         /// * The HTLC has timed out
1120         ///
1121         /// This event, however, does not get generated if an HTLC fails to meet the forwarding
1122         /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
1123         HTLCHandlingFailed {
1124                 /// The channel over which the HTLC was received.
1125                 prev_channel_id: ChannelId,
1126                 /// Destination of the HTLC that failed to be processed.
1127                 failed_next_destination: HTLCDestination,
1128         },
1129         /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
1130         /// requires confirmed external funds to be readily available to spend.
1131         ///
1132         /// LDK does not currently generate this event unless the
1133         /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`] config flag is set to true.
1134         /// It is limited to the scope of channels with anchor outputs.
1135         ///
1136         /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`]: crate::util::config::ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx
1137         BumpTransaction(BumpTransactionEvent),
1138 }
1139
1140 impl Writeable for Event {
1141         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1142                 match self {
1143                         &Event::FundingGenerationReady { .. } => {
1144                                 0u8.write(writer)?;
1145                                 // We never write out FundingGenerationReady events as, upon disconnection, peers
1146                                 // drop any channels which have not yet exchanged funding_signed.
1147                         },
1148                         &Event::PaymentClaimable { ref payment_hash, ref amount_msat, counterparty_skimmed_fee_msat,
1149                                 ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id,
1150                                 ref claim_deadline, ref onion_fields
1151                         } => {
1152                                 1u8.write(writer)?;
1153                                 let mut payment_secret = None;
1154                                 let payment_preimage;
1155                                 let mut payment_context = None;
1156                                 match &purpose {
1157                                         PaymentPurpose::Bolt11InvoicePayment {
1158                                                 payment_preimage: preimage, payment_secret: secret
1159                                         } => {
1160                                                 payment_secret = Some(secret);
1161                                                 payment_preimage = *preimage;
1162                                         },
1163                                         PaymentPurpose::Bolt12OfferPayment {
1164                                                 payment_preimage: preimage, payment_secret: secret, payment_context: context
1165                                         } => {
1166                                                 payment_secret = Some(secret);
1167                                                 payment_preimage = *preimage;
1168                                                 payment_context = Some(PaymentContextRef::Bolt12Offer(context));
1169                                         },
1170                                         PaymentPurpose::Bolt12RefundPayment {
1171                                                 payment_preimage: preimage, payment_secret: secret, payment_context: context
1172                                         } => {
1173                                                 payment_secret = Some(secret);
1174                                                 payment_preimage = *preimage;
1175                                                 payment_context = Some(PaymentContextRef::Bolt12Refund(context));
1176                                         },
1177                                         PaymentPurpose::SpontaneousPayment(preimage) => {
1178                                                 payment_preimage = Some(*preimage);
1179                                         }
1180                                 }
1181                                 let skimmed_fee_opt = if counterparty_skimmed_fee_msat == 0 { None }
1182                                         else { Some(counterparty_skimmed_fee_msat) };
1183                                 write_tlv_fields!(writer, {
1184                                         (0, payment_hash, required),
1185                                         (1, receiver_node_id, option),
1186                                         (2, payment_secret, option),
1187                                         (3, via_channel_id, option),
1188                                         (4, amount_msat, required),
1189                                         (5, via_user_channel_id, option),
1190                                         // Type 6 was `user_payment_id` on 0.0.103 and earlier
1191                                         (7, claim_deadline, option),
1192                                         (8, payment_preimage, option),
1193                                         (9, onion_fields, option),
1194                                         (10, skimmed_fee_opt, option),
1195                                         (11, payment_context, option),
1196                                 });
1197                         },
1198                         &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
1199                                 2u8.write(writer)?;
1200                                 write_tlv_fields!(writer, {
1201                                         (0, payment_preimage, required),
1202                                         (1, payment_hash, required),
1203                                         (3, payment_id, option),
1204                                         (5, fee_paid_msat, option),
1205                                 });
1206                         },
1207                         &Event::PaymentPathFailed {
1208                                 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
1209                                 ref path, ref short_channel_id,
1210                                 #[cfg(test)]
1211                                 ref error_code,
1212                                 #[cfg(test)]
1213                                 ref error_data,
1214                         } => {
1215                                 3u8.write(writer)?;
1216                                 #[cfg(test)]
1217                                 error_code.write(writer)?;
1218                                 #[cfg(test)]
1219                                 error_data.write(writer)?;
1220                                 write_tlv_fields!(writer, {
1221                                         (0, payment_hash, required),
1222                                         (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
1223                                         (2, payment_failed_permanently, required),
1224                                         (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
1225                                         (4, path.blinded_tail, option),
1226                                         (5, path.hops, required_vec),
1227                                         (7, short_channel_id, option),
1228                                         (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
1229                                         (11, payment_id, option),
1230                                         (13, failure, required),
1231                                 });
1232                         },
1233                         &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
1234                                 4u8.write(writer)?;
1235                                 // Note that we now ignore these on the read end as we'll re-generate them in
1236                                 // ChannelManager, we write them here only for backwards compatibility.
1237                         },
1238                         &Event::SpendableOutputs { ref outputs, channel_id } => {
1239                                 5u8.write(writer)?;
1240                                 write_tlv_fields!(writer, {
1241                                         (0, WithoutLength(outputs), required),
1242                                         (1, channel_id, option),
1243                                 });
1244                         },
1245                         &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1246                                 6u8.write(writer)?;
1247                                 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1248                                 write_tlv_fields!(writer, {
1249                                         (0, intercept_id, required),
1250                                         (2, intercept_scid, required),
1251                                         (4, payment_hash, required),
1252                                         (6, inbound_amount_msat, required),
1253                                         (8, expected_outbound_amount_msat, required),
1254                                 });
1255                         }
1256                         &Event::PaymentForwarded {
1257                                 prev_channel_id, next_channel_id, prev_user_channel_id, next_user_channel_id,
1258                                 total_fee_earned_msat, skimmed_fee_msat, claim_from_onchain_tx,
1259                                 outbound_amount_forwarded_msat,
1260                         } => {
1261                                 7u8.write(writer)?;
1262                                 write_tlv_fields!(writer, {
1263                                         (0, total_fee_earned_msat, option),
1264                                         (1, prev_channel_id, option),
1265                                         (2, claim_from_onchain_tx, required),
1266                                         (3, next_channel_id, option),
1267                                         (5, outbound_amount_forwarded_msat, option),
1268                                         (7, skimmed_fee_msat, option),
1269                                         (9, prev_user_channel_id, option),
1270                                         (11, next_user_channel_id, option),
1271                                 });
1272                         },
1273                         &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason,
1274                                 ref counterparty_node_id, ref channel_capacity_sats, ref channel_funding_txo
1275                         } => {
1276                                 9u8.write(writer)?;
1277                                 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1278                                 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1279                                 // separate u64 values.
1280                                 let user_channel_id_low = *user_channel_id as u64;
1281                                 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1282                                 write_tlv_fields!(writer, {
1283                                         (0, channel_id, required),
1284                                         (1, user_channel_id_low, required),
1285                                         (2, reason, required),
1286                                         (3, user_channel_id_high, required),
1287                                         (5, counterparty_node_id, option),
1288                                         (7, channel_capacity_sats, option),
1289                                         (9, channel_funding_txo, option),
1290                                 });
1291                         },
1292                         &Event::DiscardFunding { ref channel_id, ref transaction } => {
1293                                 11u8.write(writer)?;
1294                                 write_tlv_fields!(writer, {
1295                                         (0, channel_id, required),
1296                                         (2, transaction, required)
1297                                 })
1298                         },
1299                         &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1300                                 13u8.write(writer)?;
1301                                 write_tlv_fields!(writer, {
1302                                         (0, payment_id, required),
1303                                         (2, payment_hash, option),
1304                                         (4, path.hops, required_vec),
1305                                         (6, path.blinded_tail, option),
1306                                 })
1307                         },
1308                         &Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
1309                                 15u8.write(writer)?;
1310                                 write_tlv_fields!(writer, {
1311                                         (0, payment_id, required),
1312                                         (1, reason, option),
1313                                         (2, payment_hash, required),
1314                                 })
1315                         },
1316                         &Event::OpenChannelRequest { .. } => {
1317                                 17u8.write(writer)?;
1318                                 // We never write the OpenChannelRequest events as, upon disconnection, peers
1319                                 // drop any channels which have not yet exchanged funding_signed.
1320                         },
1321                         &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref htlcs, ref sender_intended_total_msat } => {
1322                                 19u8.write(writer)?;
1323                                 write_tlv_fields!(writer, {
1324                                         (0, payment_hash, required),
1325                                         (1, receiver_node_id, option),
1326                                         (2, purpose, required),
1327                                         (4, amount_msat, required),
1328                                         (5, *htlcs, optional_vec),
1329                                         (7, sender_intended_total_msat, option),
1330                                 });
1331                         },
1332                         &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1333                                 21u8.write(writer)?;
1334                                 write_tlv_fields!(writer, {
1335                                         (0, payment_id, required),
1336                                         (2, payment_hash, required),
1337                                         (4, path.hops, required_vec),
1338                                         (6, path.blinded_tail, option),
1339                                 })
1340                         },
1341                         &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1342                                 23u8.write(writer)?;
1343                                 write_tlv_fields!(writer, {
1344                                         (0, payment_id, required),
1345                                         (2, payment_hash, required),
1346                                         (4, path.hops, required_vec),
1347                                         (6, short_channel_id, option),
1348                                         (8, path.blinded_tail, option),
1349                                 })
1350                         },
1351                         &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1352                                 25u8.write(writer)?;
1353                                 write_tlv_fields!(writer, {
1354                                         (0, prev_channel_id, required),
1355                                         (2, failed_next_destination, required),
1356                                 })
1357                         },
1358                         &Event::BumpTransaction(ref event)=> {
1359                                 27u8.write(writer)?;
1360                                 match event {
1361                                         // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1362                                         // upon restarting anyway if they remain unresolved.
1363                                         BumpTransactionEvent::ChannelClose { .. } => {}
1364                                         BumpTransactionEvent::HTLCResolution { .. } => {}
1365                                 }
1366                                 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1367                         }
1368                         &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1369                                 29u8.write(writer)?;
1370                                 write_tlv_fields!(writer, {
1371                                         (0, channel_id, required),
1372                                         (2, user_channel_id, required),
1373                                         (4, counterparty_node_id, required),
1374                                         (6, channel_type, required),
1375                                 });
1376                         },
1377                         &Event::ChannelPending { ref channel_id, ref user_channel_id,
1378                                 ref former_temporary_channel_id, ref counterparty_node_id, ref funding_txo,
1379                                 ref channel_type
1380                         } => {
1381                                 31u8.write(writer)?;
1382                                 write_tlv_fields!(writer, {
1383                                         (0, channel_id, required),
1384                                         (1, channel_type, option),
1385                                         (2, user_channel_id, required),
1386                                         (4, former_temporary_channel_id, required),
1387                                         (6, counterparty_node_id, required),
1388                                         (8, funding_txo, required),
1389                                 });
1390                         },
1391                         &Event::InvoiceRequestFailed { ref payment_id } => {
1392                                 33u8.write(writer)?;
1393                                 write_tlv_fields!(writer, {
1394                                         (0, payment_id, required),
1395                                 })
1396                         },
1397                         &Event::ConnectionNeeded { .. } => {
1398                                 35u8.write(writer)?;
1399                                 // Never write ConnectionNeeded events as buffered onion messages aren't serialized.
1400                         },
1401                         // Note that, going forward, all new events must only write data inside of
1402                         // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1403                         // data via `write_tlv_fields`.
1404                 }
1405                 Ok(())
1406         }
1407 }
1408 impl MaybeReadable for Event {
1409         fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1410                 match Readable::read(reader)? {
1411                         // Note that we do not write a length-prefixed TLV for FundingGenerationReady events.
1412                         0u8 => Ok(None),
1413                         1u8 => {
1414                                 let mut f = || {
1415                                         let mut payment_hash = PaymentHash([0; 32]);
1416                                         let mut payment_preimage = None;
1417                                         let mut payment_secret = None;
1418                                         let mut amount_msat = 0;
1419                                         let mut counterparty_skimmed_fee_msat_opt = None;
1420                                         let mut receiver_node_id = None;
1421                                         let mut _user_payment_id = None::<u64>; // Used in 0.0.103 and earlier, no longer written in 0.0.116+.
1422                                         let mut via_channel_id = None;
1423                                         let mut claim_deadline = None;
1424                                         let mut via_user_channel_id = None;
1425                                         let mut onion_fields = None;
1426                                         let mut payment_context = None;
1427                                         read_tlv_fields!(reader, {
1428                                                 (0, payment_hash, required),
1429                                                 (1, receiver_node_id, option),
1430                                                 (2, payment_secret, option),
1431                                                 (3, via_channel_id, option),
1432                                                 (4, amount_msat, required),
1433                                                 (5, via_user_channel_id, option),
1434                                                 (6, _user_payment_id, option),
1435                                                 (7, claim_deadline, option),
1436                                                 (8, payment_preimage, option),
1437                                                 (9, onion_fields, option),
1438                                                 (10, counterparty_skimmed_fee_msat_opt, option),
1439                                                 (11, payment_context, option),
1440                                         });
1441                                         let purpose = match payment_secret {
1442                                                 Some(secret) => PaymentPurpose::from_parts(payment_preimage, secret, payment_context),
1443                                                 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1444                                                 None => return Err(msgs::DecodeError::InvalidValue),
1445                                         };
1446                                         Ok(Some(Event::PaymentClaimable {
1447                                                 receiver_node_id,
1448                                                 payment_hash,
1449                                                 amount_msat,
1450                                                 counterparty_skimmed_fee_msat: counterparty_skimmed_fee_msat_opt.unwrap_or(0),
1451                                                 purpose,
1452                                                 via_channel_id,
1453                                                 via_user_channel_id,
1454                                                 claim_deadline,
1455                                                 onion_fields,
1456                                         }))
1457                                 };
1458                                 f()
1459                         },
1460                         2u8 => {
1461                                 let mut f = || {
1462                                         let mut payment_preimage = PaymentPreimage([0; 32]);
1463                                         let mut payment_hash = None;
1464                                         let mut payment_id = None;
1465                                         let mut fee_paid_msat = None;
1466                                         read_tlv_fields!(reader, {
1467                                                 (0, payment_preimage, required),
1468                                                 (1, payment_hash, option),
1469                                                 (3, payment_id, option),
1470                                                 (5, fee_paid_msat, option),
1471                                         });
1472                                         if payment_hash.is_none() {
1473                                                 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()));
1474                                         }
1475                                         Ok(Some(Event::PaymentSent {
1476                                                 payment_id,
1477                                                 payment_preimage,
1478                                                 payment_hash: payment_hash.unwrap(),
1479                                                 fee_paid_msat,
1480                                         }))
1481                                 };
1482                                 f()
1483                         },
1484                         3u8 => {
1485                                 let mut f = || {
1486                                         #[cfg(test)]
1487                                         let error_code = Readable::read(reader)?;
1488                                         #[cfg(test)]
1489                                         let error_data = Readable::read(reader)?;
1490                                         let mut payment_hash = PaymentHash([0; 32]);
1491                                         let mut payment_failed_permanently = false;
1492                                         let mut network_update = None;
1493                                         let mut blinded_tail: Option<BlindedTail> = None;
1494                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1495                                         let mut short_channel_id = None;
1496                                         let mut payment_id = None;
1497                                         let mut failure_opt = None;
1498                                         read_tlv_fields!(reader, {
1499                                                 (0, payment_hash, required),
1500                                                 (1, network_update, upgradable_option),
1501                                                 (2, payment_failed_permanently, required),
1502                                                 (4, blinded_tail, option),
1503                                                 // Added as a part of LDK 0.0.101 and always filled in since.
1504                                                 // Defaults to an empty Vec, though likely should have been `Option`al.
1505                                                 (5, path, optional_vec),
1506                                                 (7, short_channel_id, option),
1507                                                 (11, payment_id, option),
1508                                                 (13, failure_opt, upgradable_option),
1509                                         });
1510                                         let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1511                                         Ok(Some(Event::PaymentPathFailed {
1512                                                 payment_id,
1513                                                 payment_hash,
1514                                                 payment_failed_permanently,
1515                                                 failure,
1516                                                 path: Path { hops: path.unwrap(), blinded_tail },
1517                                                 short_channel_id,
1518                                                 #[cfg(test)]
1519                                                 error_code,
1520                                                 #[cfg(test)]
1521                                                 error_data,
1522                                         }))
1523                                 };
1524                                 f()
1525                         },
1526                         4u8 => Ok(None),
1527                         5u8 => {
1528                                 let mut f = || {
1529                                         let mut outputs = WithoutLength(Vec::new());
1530                                         let mut channel_id: Option<ChannelId> = None;
1531                                         read_tlv_fields!(reader, {
1532                                                 (0, outputs, required),
1533                                                 (1, channel_id, option),
1534                                         });
1535                                         Ok(Some(Event::SpendableOutputs { outputs: outputs.0, channel_id }))
1536                                 };
1537                                 f()
1538                         },
1539                         6u8 => {
1540                                 let mut payment_hash = PaymentHash([0; 32]);
1541                                 let mut intercept_id = InterceptId([0; 32]);
1542                                 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1543                                 let mut inbound_amount_msat = 0;
1544                                 let mut expected_outbound_amount_msat = 0;
1545                                 read_tlv_fields!(reader, {
1546                                         (0, intercept_id, required),
1547                                         (2, requested_next_hop_scid, required),
1548                                         (4, payment_hash, required),
1549                                         (6, inbound_amount_msat, required),
1550                                         (8, expected_outbound_amount_msat, required),
1551                                 });
1552                                 let next_scid = match requested_next_hop_scid {
1553                                         InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1554                                 };
1555                                 Ok(Some(Event::HTLCIntercepted {
1556                                         payment_hash,
1557                                         requested_next_hop_scid: next_scid,
1558                                         inbound_amount_msat,
1559                                         expected_outbound_amount_msat,
1560                                         intercept_id,
1561                                 }))
1562                         },
1563                         7u8 => {
1564                                 let mut f = || {
1565                                         let mut prev_channel_id = None;
1566                                         let mut next_channel_id = None;
1567                                         let mut prev_user_channel_id = None;
1568                                         let mut next_user_channel_id = None;
1569                                         let mut total_fee_earned_msat = None;
1570                                         let mut skimmed_fee_msat = None;
1571                                         let mut claim_from_onchain_tx = false;
1572                                         let mut outbound_amount_forwarded_msat = None;
1573                                         read_tlv_fields!(reader, {
1574                                                 (0, total_fee_earned_msat, option),
1575                                                 (1, prev_channel_id, option),
1576                                                 (2, claim_from_onchain_tx, required),
1577                                                 (3, next_channel_id, option),
1578                                                 (5, outbound_amount_forwarded_msat, option),
1579                                                 (7, skimmed_fee_msat, option),
1580                                                 (9, prev_user_channel_id, option),
1581                                                 (11, next_user_channel_id, option),
1582                                         });
1583                                         Ok(Some(Event::PaymentForwarded {
1584                                                 prev_channel_id, next_channel_id, prev_user_channel_id,
1585                                                 next_user_channel_id, total_fee_earned_msat, skimmed_fee_msat,
1586                                                 claim_from_onchain_tx, outbound_amount_forwarded_msat,
1587                                         }))
1588                                 };
1589                                 f()
1590                         },
1591                         9u8 => {
1592                                 let mut f = || {
1593                                         let mut channel_id = ChannelId::new_zero();
1594                                         let mut reason = UpgradableRequired(None);
1595                                         let mut user_channel_id_low_opt: Option<u64> = None;
1596                                         let mut user_channel_id_high_opt: Option<u64> = None;
1597                                         let mut counterparty_node_id = None;
1598                                         let mut channel_capacity_sats = None;
1599                                         let mut channel_funding_txo = None;
1600                                         read_tlv_fields!(reader, {
1601                                                 (0, channel_id, required),
1602                                                 (1, user_channel_id_low_opt, option),
1603                                                 (2, reason, upgradable_required),
1604                                                 (3, user_channel_id_high_opt, option),
1605                                                 (5, counterparty_node_id, option),
1606                                                 (7, channel_capacity_sats, option),
1607                                                 (9, channel_funding_txo, option),
1608                                         });
1609
1610                                         // `user_channel_id` used to be a single u64 value. In order to remain
1611                                         // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1612                                         // as two separate u64 values.
1613                                         let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1614                                                 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1615
1616                                         Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required),
1617                                                 counterparty_node_id, channel_capacity_sats, channel_funding_txo }))
1618                                 };
1619                                 f()
1620                         },
1621                         11u8 => {
1622                                 let mut f = || {
1623                                         let mut channel_id = ChannelId::new_zero();
1624                                         let mut transaction = Transaction{ version: 2, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
1625                                         read_tlv_fields!(reader, {
1626                                                 (0, channel_id, required),
1627                                                 (2, transaction, required),
1628                                         });
1629                                         Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1630                                 };
1631                                 f()
1632                         },
1633                         13u8 => {
1634                                 let mut f = || {
1635                                         _init_and_read_len_prefixed_tlv_fields!(reader, {
1636                                                 (0, payment_id, required),
1637                                                 (2, payment_hash, option),
1638                                                 (4, path, required_vec),
1639                                                 (6, blinded_tail, option),
1640                                         });
1641                                         Ok(Some(Event::PaymentPathSuccessful {
1642                                                 payment_id: payment_id.0.unwrap(),
1643                                                 payment_hash,
1644                                                 path: Path { hops: path, blinded_tail },
1645                                         }))
1646                                 };
1647                                 f()
1648                         },
1649                         15u8 => {
1650                                 let mut f = || {
1651                                         let mut payment_hash = PaymentHash([0; 32]);
1652                                         let mut payment_id = PaymentId([0; 32]);
1653                                         let mut reason = None;
1654                                         read_tlv_fields!(reader, {
1655                                                 (0, payment_id, required),
1656                                                 (1, reason, upgradable_option),
1657                                                 (2, payment_hash, required),
1658                                         });
1659                                         Ok(Some(Event::PaymentFailed {
1660                                                 payment_id,
1661                                                 payment_hash,
1662                                                 reason,
1663                                         }))
1664                                 };
1665                                 f()
1666                         },
1667                         17u8 => {
1668                                 // Value 17 is used for `Event::OpenChannelRequest`.
1669                                 Ok(None)
1670                         },
1671                         19u8 => {
1672                                 let mut f = || {
1673                                         let mut payment_hash = PaymentHash([0; 32]);
1674                                         let mut purpose = UpgradableRequired(None);
1675                                         let mut amount_msat = 0;
1676                                         let mut receiver_node_id = None;
1677                                         let mut htlcs: Option<Vec<ClaimedHTLC>> = Some(vec![]);
1678                                         let mut sender_intended_total_msat: Option<u64> = None;
1679                                         read_tlv_fields!(reader, {
1680                                                 (0, payment_hash, required),
1681                                                 (1, receiver_node_id, option),
1682                                                 (2, purpose, upgradable_required),
1683                                                 (4, amount_msat, required),
1684                                                 (5, htlcs, optional_vec),
1685                                                 (7, sender_intended_total_msat, option),
1686                                         });
1687                                         Ok(Some(Event::PaymentClaimed {
1688                                                 receiver_node_id,
1689                                                 payment_hash,
1690                                                 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1691                                                 amount_msat,
1692                                                 htlcs: htlcs.unwrap_or(vec![]),
1693                                                 sender_intended_total_msat,
1694                                         }))
1695                                 };
1696                                 f()
1697                         },
1698                         21u8 => {
1699                                 let mut f = || {
1700                                         _init_and_read_len_prefixed_tlv_fields!(reader, {
1701                                                 (0, payment_id, required),
1702                                                 (2, payment_hash, required),
1703                                                 (4, path, required_vec),
1704                                                 (6, blinded_tail, option),
1705                                         });
1706                                         Ok(Some(Event::ProbeSuccessful {
1707                                                 payment_id: payment_id.0.unwrap(),
1708                                                 payment_hash: payment_hash.0.unwrap(),
1709                                                 path: Path { hops: path, blinded_tail },
1710                                         }))
1711                                 };
1712                                 f()
1713                         },
1714                         23u8 => {
1715                                 let mut f = || {
1716                                         _init_and_read_len_prefixed_tlv_fields!(reader, {
1717                                                 (0, payment_id, required),
1718                                                 (2, payment_hash, required),
1719                                                 (4, path, required_vec),
1720                                                 (6, short_channel_id, option),
1721                                                 (8, blinded_tail, option),
1722                                         });
1723                                         Ok(Some(Event::ProbeFailed {
1724                                                 payment_id: payment_id.0.unwrap(),
1725                                                 payment_hash: payment_hash.0.unwrap(),
1726                                                 path: Path { hops: path, blinded_tail },
1727                                                 short_channel_id,
1728                                         }))
1729                                 };
1730                                 f()
1731                         },
1732                         25u8 => {
1733                                 let mut f = || {
1734                                         let mut prev_channel_id = ChannelId::new_zero();
1735                                         let mut failed_next_destination_opt = UpgradableRequired(None);
1736                                         read_tlv_fields!(reader, {
1737                                                 (0, prev_channel_id, required),
1738                                                 (2, failed_next_destination_opt, upgradable_required),
1739                                         });
1740                                         Ok(Some(Event::HTLCHandlingFailed {
1741                                                 prev_channel_id,
1742                                                 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1743                                         }))
1744                                 };
1745                                 f()
1746                         },
1747                         27u8 => Ok(None),
1748                         29u8 => {
1749                                 let mut f = || {
1750                                         let mut channel_id = ChannelId::new_zero();
1751                                         let mut user_channel_id: u128 = 0;
1752                                         let mut counterparty_node_id = RequiredWrapper(None);
1753                                         let mut channel_type = RequiredWrapper(None);
1754                                         read_tlv_fields!(reader, {
1755                                                 (0, channel_id, required),
1756                                                 (2, user_channel_id, required),
1757                                                 (4, counterparty_node_id, required),
1758                                                 (6, channel_type, required),
1759                                         });
1760
1761                                         Ok(Some(Event::ChannelReady {
1762                                                 channel_id,
1763                                                 user_channel_id,
1764                                                 counterparty_node_id: counterparty_node_id.0.unwrap(),
1765                                                 channel_type: channel_type.0.unwrap()
1766                                         }))
1767                                 };
1768                                 f()
1769                         },
1770                         31u8 => {
1771                                 let mut f = || {
1772                                         let mut channel_id = ChannelId::new_zero();
1773                                         let mut user_channel_id: u128 = 0;
1774                                         let mut former_temporary_channel_id = None;
1775                                         let mut counterparty_node_id = RequiredWrapper(None);
1776                                         let mut funding_txo = RequiredWrapper(None);
1777                                         let mut channel_type = None;
1778                                         read_tlv_fields!(reader, {
1779                                                 (0, channel_id, required),
1780                                                 (1, channel_type, option),
1781                                                 (2, user_channel_id, required),
1782                                                 (4, former_temporary_channel_id, required),
1783                                                 (6, counterparty_node_id, required),
1784                                                 (8, funding_txo, required),
1785                                         });
1786
1787                                         Ok(Some(Event::ChannelPending {
1788                                                 channel_id,
1789                                                 user_channel_id,
1790                                                 former_temporary_channel_id,
1791                                                 counterparty_node_id: counterparty_node_id.0.unwrap(),
1792                                                 funding_txo: funding_txo.0.unwrap(),
1793                                                 channel_type,
1794                                         }))
1795                                 };
1796                                 f()
1797                         },
1798                         33u8 => {
1799                                 let mut f = || {
1800                                         _init_and_read_len_prefixed_tlv_fields!(reader, {
1801                                                 (0, payment_id, required),
1802                                         });
1803                                         Ok(Some(Event::InvoiceRequestFailed {
1804                                                 payment_id: payment_id.0.unwrap(),
1805                                         }))
1806                                 };
1807                                 f()
1808                         },
1809                         // Note that we do not write a length-prefixed TLV for ConnectionNeeded events.
1810                         35u8 => Ok(None),
1811                         // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1812                         // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1813                         // reads.
1814                         x if x % 2 == 1 => {
1815                                 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1816                                 // which prefixes the whole thing with a length BigSize. Because the event is
1817                                 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1818                                 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1819                                 // exactly the number of bytes specified, ignoring them entirely.
1820                                 let tlv_len: BigSize = Readable::read(reader)?;
1821                                 FixedLengthReader::new(reader, tlv_len.0)
1822                                         .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1823                                 Ok(None)
1824                         },
1825                         _ => Err(msgs::DecodeError::InvalidValue)
1826                 }
1827         }
1828 }
1829
1830 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1831 /// broadcast to most peers).
1832 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1833 #[derive(Clone, Debug)]
1834 #[cfg_attr(test, derive(PartialEq))]
1835 pub enum MessageSendEvent {
1836         /// Used to indicate that we've accepted a channel open and should send the accept_channel
1837         /// message provided to the given peer.
1838         SendAcceptChannel {
1839                 /// The node_id of the node which should receive this message
1840                 node_id: PublicKey,
1841                 /// The message which should be sent.
1842                 msg: msgs::AcceptChannel,
1843         },
1844         /// Used to indicate that we've accepted a V2 channel open and should send the accept_channel2
1845         /// message provided to the given peer.
1846         SendAcceptChannelV2 {
1847                 /// The node_id of the node which should receive this message
1848                 node_id: PublicKey,
1849                 /// The message which should be sent.
1850                 msg: msgs::AcceptChannelV2,
1851         },
1852         /// Used to indicate that we've initiated a channel open and should send the open_channel
1853         /// message provided to the given peer.
1854         SendOpenChannel {
1855                 /// The node_id of the node which should receive this message
1856                 node_id: PublicKey,
1857                 /// The message which should be sent.
1858                 msg: msgs::OpenChannel,
1859         },
1860         /// Used to indicate that we've initiated a V2 channel open and should send the open_channel2
1861         /// message provided to the given peer.
1862         SendOpenChannelV2 {
1863                 /// The node_id of the node which should receive this message
1864                 node_id: PublicKey,
1865                 /// The message which should be sent.
1866                 msg: msgs::OpenChannelV2,
1867         },
1868         /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1869         SendFundingCreated {
1870                 /// The node_id of the node which should receive this message
1871                 node_id: PublicKey,
1872                 /// The message which should be sent.
1873                 msg: msgs::FundingCreated,
1874         },
1875         /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1876         SendFundingSigned {
1877                 /// The node_id of the node which should receive this message
1878                 node_id: PublicKey,
1879                 /// The message which should be sent.
1880                 msg: msgs::FundingSigned,
1881         },
1882         /// Used to indicate that a stfu message should be sent to the peer with the given node id.
1883         SendStfu {
1884                 /// The node_id of the node which should receive this message
1885                 node_id: PublicKey,
1886                 /// The message which should be sent.
1887                 msg: msgs::Stfu,
1888         },
1889         /// Used to indicate that a splice message should be sent to the peer with the given node id.
1890         SendSplice {
1891                 /// The node_id of the node which should receive this message
1892                 node_id: PublicKey,
1893                 /// The message which should be sent.
1894                 msg: msgs::Splice,
1895         },
1896         /// Used to indicate that a splice_ack message should be sent to the peer with the given node id.
1897         SendSpliceAck {
1898                 /// The node_id of the node which should receive this message
1899                 node_id: PublicKey,
1900                 /// The message which should be sent.
1901                 msg: msgs::SpliceAck,
1902         },
1903         /// Used to indicate that a splice_locked message should be sent to the peer with the given node id.
1904         SendSpliceLocked {
1905                 /// The node_id of the node which should receive this message
1906                 node_id: PublicKey,
1907                 /// The message which should be sent.
1908                 msg: msgs::SpliceLocked,
1909         },
1910         /// Used to indicate that a tx_add_input message should be sent to the peer with the given node_id.
1911         SendTxAddInput {
1912                 /// The node_id of the node which should receive this message
1913                 node_id: PublicKey,
1914                 /// The message which should be sent.
1915                 msg: msgs::TxAddInput,
1916         },
1917         /// Used to indicate that a tx_add_output message should be sent to the peer with the given node_id.
1918         SendTxAddOutput {
1919                 /// The node_id of the node which should receive this message
1920                 node_id: PublicKey,
1921                 /// The message which should be sent.
1922                 msg: msgs::TxAddOutput,
1923         },
1924         /// Used to indicate that a tx_remove_input message should be sent to the peer with the given node_id.
1925         SendTxRemoveInput {
1926                 /// The node_id of the node which should receive this message
1927                 node_id: PublicKey,
1928                 /// The message which should be sent.
1929                 msg: msgs::TxRemoveInput,
1930         },
1931         /// Used to indicate that a tx_remove_output message should be sent to the peer with the given node_id.
1932         SendTxRemoveOutput {
1933                 /// The node_id of the node which should receive this message
1934                 node_id: PublicKey,
1935                 /// The message which should be sent.
1936                 msg: msgs::TxRemoveOutput,
1937         },
1938         /// Used to indicate that a tx_complete message should be sent to the peer with the given node_id.
1939         SendTxComplete {
1940                 /// The node_id of the node which should receive this message
1941                 node_id: PublicKey,
1942                 /// The message which should be sent.
1943                 msg: msgs::TxComplete,
1944         },
1945         /// Used to indicate that a tx_signatures message should be sent to the peer with the given node_id.
1946         SendTxSignatures {
1947                 /// The node_id of the node which should receive this message
1948                 node_id: PublicKey,
1949                 /// The message which should be sent.
1950                 msg: msgs::TxSignatures,
1951         },
1952         /// Used to indicate that a tx_init_rbf message should be sent to the peer with the given node_id.
1953         SendTxInitRbf {
1954                 /// The node_id of the node which should receive this message
1955                 node_id: PublicKey,
1956                 /// The message which should be sent.
1957                 msg: msgs::TxInitRbf,
1958         },
1959         /// Used to indicate that a tx_ack_rbf message should be sent to the peer with the given node_id.
1960         SendTxAckRbf {
1961                 /// The node_id of the node which should receive this message
1962                 node_id: PublicKey,
1963                 /// The message which should be sent.
1964                 msg: msgs::TxAckRbf,
1965         },
1966         /// Used to indicate that a tx_abort message should be sent to the peer with the given node_id.
1967         SendTxAbort {
1968                 /// The node_id of the node which should receive this message
1969                 node_id: PublicKey,
1970                 /// The message which should be sent.
1971                 msg: msgs::TxAbort,
1972         },
1973         /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1974         SendChannelReady {
1975                 /// The node_id of the node which should receive these message(s)
1976                 node_id: PublicKey,
1977                 /// The channel_ready message which should be sent.
1978                 msg: msgs::ChannelReady,
1979         },
1980         /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1981         SendAnnouncementSignatures {
1982                 /// The node_id of the node which should receive these message(s)
1983                 node_id: PublicKey,
1984                 /// The announcement_signatures message which should be sent.
1985                 msg: msgs::AnnouncementSignatures,
1986         },
1987         /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1988         /// message should be sent to the peer with the given node_id.
1989         UpdateHTLCs {
1990                 /// The node_id of the node which should receive these message(s)
1991                 node_id: PublicKey,
1992                 /// The update messages which should be sent. ALL messages in the struct should be sent!
1993                 updates: msgs::CommitmentUpdate,
1994         },
1995         /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1996         SendRevokeAndACK {
1997                 /// The node_id of the node which should receive this message
1998                 node_id: PublicKey,
1999                 /// The message which should be sent.
2000                 msg: msgs::RevokeAndACK,
2001         },
2002         /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
2003         SendClosingSigned {
2004                 /// The node_id of the node which should receive this message
2005                 node_id: PublicKey,
2006                 /// The message which should be sent.
2007                 msg: msgs::ClosingSigned,
2008         },
2009         /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
2010         SendShutdown {
2011                 /// The node_id of the node which should receive this message
2012                 node_id: PublicKey,
2013                 /// The message which should be sent.
2014                 msg: msgs::Shutdown,
2015         },
2016         /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
2017         SendChannelReestablish {
2018                 /// The node_id of the node which should receive this message
2019                 node_id: PublicKey,
2020                 /// The message which should be sent.
2021                 msg: msgs::ChannelReestablish,
2022         },
2023         /// Used to send a channel_announcement and channel_update to a specific peer, likely on
2024         /// initial connection to ensure our peers know about our channels.
2025         SendChannelAnnouncement {
2026                 /// The node_id of the node which should receive this message
2027                 node_id: PublicKey,
2028                 /// The channel_announcement which should be sent.
2029                 msg: msgs::ChannelAnnouncement,
2030                 /// The followup channel_update which should be sent.
2031                 update_msg: msgs::ChannelUpdate,
2032         },
2033         /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
2034         /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
2035         ///
2036         /// Note that after doing so, you very likely (unless you did so very recently) want to
2037         /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
2038         /// ensures that any nodes which see our channel_announcement also have a relevant
2039         /// node_announcement, including relevant feature flags which may be important for routing
2040         /// through or to us.
2041         ///
2042         /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
2043         BroadcastChannelAnnouncement {
2044                 /// The channel_announcement which should be sent.
2045                 msg: msgs::ChannelAnnouncement,
2046                 /// The followup channel_update which should be sent.
2047                 update_msg: Option<msgs::ChannelUpdate>,
2048         },
2049         /// Used to indicate that a channel_update should be broadcast to all peers.
2050         BroadcastChannelUpdate {
2051                 /// The channel_update which should be sent.
2052                 msg: msgs::ChannelUpdate,
2053         },
2054         /// Used to indicate that a node_announcement should be broadcast to all peers.
2055         BroadcastNodeAnnouncement {
2056                 /// The node_announcement which should be sent.
2057                 msg: msgs::NodeAnnouncement,
2058         },
2059         /// Used to indicate that a channel_update should be sent to a single peer.
2060         /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
2061         /// private channel and we shouldn't be informing all of our peers of channel parameters.
2062         SendChannelUpdate {
2063                 /// The node_id of the node which should receive this message
2064                 node_id: PublicKey,
2065                 /// The channel_update which should be sent.
2066                 msg: msgs::ChannelUpdate,
2067         },
2068         /// Broadcast an error downstream to be handled
2069         HandleError {
2070                 /// The node_id of the node which should receive this message
2071                 node_id: PublicKey,
2072                 /// The action which should be taken.
2073                 action: msgs::ErrorAction
2074         },
2075         /// Query a peer for channels with funding transaction UTXOs in a block range.
2076         SendChannelRangeQuery {
2077                 /// The node_id of this message recipient
2078                 node_id: PublicKey,
2079                 /// The query_channel_range which should be sent.
2080                 msg: msgs::QueryChannelRange,
2081         },
2082         /// Request routing gossip messages from a peer for a list of channels identified by
2083         /// their short_channel_ids.
2084         SendShortIdsQuery {
2085                 /// The node_id of this message recipient
2086                 node_id: PublicKey,
2087                 /// The query_short_channel_ids which should be sent.
2088                 msg: msgs::QueryShortChannelIds,
2089         },
2090         /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
2091         /// emitted during processing of the query.
2092         SendReplyChannelRange {
2093                 /// The node_id of this message recipient
2094                 node_id: PublicKey,
2095                 /// The reply_channel_range which should be sent.
2096                 msg: msgs::ReplyChannelRange,
2097         },
2098         /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
2099         /// enable receiving gossip messages from the peer.
2100         SendGossipTimestampFilter {
2101                 /// The node_id of this message recipient
2102                 node_id: PublicKey,
2103                 /// The gossip_timestamp_filter which should be sent.
2104                 msg: msgs::GossipTimestampFilter,
2105         },
2106 }
2107
2108 /// A trait indicating an object may generate message send events
2109 pub trait MessageSendEventsProvider {
2110         /// Gets the list of pending events which were generated by previous actions, clearing the list
2111         /// in the process.
2112         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
2113 }
2114
2115 /// A trait indicating an object may generate events.
2116 ///
2117 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
2118 ///
2119 /// Implementations of this trait may also feature an async version of event handling, as shown with
2120 /// [`ChannelManager::process_pending_events_async`] and
2121 /// [`ChainMonitor::process_pending_events_async`].
2122 ///
2123 /// # Requirements
2124 ///
2125 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
2126 /// event since the last invocation.
2127 ///
2128 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
2129 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
2130 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
2131 /// relevant changes to disk *before* returning.
2132 ///
2133 /// Further, because an application may crash between an [`Event`] being handled and the
2134 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
2135 /// effect, [`Event`]s may be replayed.
2136 ///
2137 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
2138 /// consult the provider's documentation on the implication of processing events and how a handler
2139 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
2140 /// [`ChainMonitor::process_pending_events`]).
2141 ///
2142 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
2143 /// own type(s).
2144 ///
2145 /// [`process_pending_events`]: Self::process_pending_events
2146 /// [`handle_event`]: EventHandler::handle_event
2147 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
2148 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
2149 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
2150 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
2151 pub trait EventsProvider {
2152         /// Processes any events generated since the last call using the given event handler.
2153         ///
2154         /// See the trait-level documentation for requirements.
2155         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
2156 }
2157
2158 /// A trait implemented for objects handling events from [`EventsProvider`].
2159 ///
2160 /// An async variation also exists for implementations of [`EventsProvider`] that support async
2161 /// event handling. The async event handler should satisfy the generic bounds: `F:
2162 /// core::future::Future, H: Fn(Event) -> F`.
2163 pub trait EventHandler {
2164         /// Handles the given [`Event`].
2165         ///
2166         /// See [`EventsProvider`] for details that must be considered when implementing this method.
2167         fn handle_event(&self, event: Event);
2168 }
2169
2170 impl<F> EventHandler for F where F: Fn(Event) {
2171         fn handle_event(&self, event: Event) {
2172                 self(event)
2173         }
2174 }
2175
2176 impl<T: EventHandler> EventHandler for Arc<T> {
2177         fn handle_event(&self, event: Event) {
2178                 self.deref().handle_event(event)
2179         }
2180 }