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