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