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