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