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