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