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