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