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