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