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