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