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