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