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