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