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