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