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