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