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