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