]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/events/mod.rs
Support generating events when an OM for an offline peer is received.
[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 }
1057
1058 impl Writeable for Event {
1059         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1060                 match self {
1061                         &Event::FundingGenerationReady { .. } => {
1062                                 0u8.write(writer)?;
1063                                 // We never write out FundingGenerationReady events as, upon disconnection, peers
1064                                 // drop any channels which have not yet exchanged funding_signed.
1065                         },
1066                         &Event::PaymentClaimable { ref payment_hash, ref amount_msat, counterparty_skimmed_fee_msat,
1067                                 ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id,
1068                                 ref claim_deadline, ref onion_fields
1069                         } => {
1070                                 1u8.write(writer)?;
1071                                 let mut payment_secret = None;
1072                                 let payment_preimage;
1073                                 match &purpose {
1074                                         PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
1075                                                 payment_secret = Some(secret);
1076                                                 payment_preimage = *preimage;
1077                                         },
1078                                         PaymentPurpose::SpontaneousPayment(preimage) => {
1079                                                 payment_preimage = Some(*preimage);
1080                                         }
1081                                 }
1082                                 let skimmed_fee_opt = if counterparty_skimmed_fee_msat == 0 { None }
1083                                         else { Some(counterparty_skimmed_fee_msat) };
1084                                 write_tlv_fields!(writer, {
1085                                         (0, payment_hash, required),
1086                                         (1, receiver_node_id, option),
1087                                         (2, payment_secret, option),
1088                                         (3, via_channel_id, option),
1089                                         (4, amount_msat, required),
1090                                         (5, via_user_channel_id, option),
1091                                         // Type 6 was `user_payment_id` on 0.0.103 and earlier
1092                                         (7, claim_deadline, option),
1093                                         (8, payment_preimage, option),
1094                                         (9, onion_fields, option),
1095                                         (10, skimmed_fee_opt, option),
1096                                 });
1097                         },
1098                         &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
1099                                 2u8.write(writer)?;
1100                                 write_tlv_fields!(writer, {
1101                                         (0, payment_preimage, required),
1102                                         (1, payment_hash, required),
1103                                         (3, payment_id, option),
1104                                         (5, fee_paid_msat, option),
1105                                 });
1106                         },
1107                         &Event::PaymentPathFailed {
1108                                 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
1109                                 ref path, ref short_channel_id,
1110                                 #[cfg(test)]
1111                                 ref error_code,
1112                                 #[cfg(test)]
1113                                 ref error_data,
1114                         } => {
1115                                 3u8.write(writer)?;
1116                                 #[cfg(test)]
1117                                 error_code.write(writer)?;
1118                                 #[cfg(test)]
1119                                 error_data.write(writer)?;
1120                                 write_tlv_fields!(writer, {
1121                                         (0, payment_hash, required),
1122                                         (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
1123                                         (2, payment_failed_permanently, required),
1124                                         (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
1125                                         (4, path.blinded_tail, option),
1126                                         (5, path.hops, required_vec),
1127                                         (7, short_channel_id, option),
1128                                         (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
1129                                         (11, payment_id, option),
1130                                         (13, failure, required),
1131                                 });
1132                         },
1133                         &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
1134                                 4u8.write(writer)?;
1135                                 // Note that we now ignore these on the read end as we'll re-generate them in
1136                                 // ChannelManager, we write them here only for backwards compatibility.
1137                         },
1138                         &Event::SpendableOutputs { ref outputs, channel_id } => {
1139                                 5u8.write(writer)?;
1140                                 write_tlv_fields!(writer, {
1141                                         (0, WithoutLength(outputs), required),
1142                                         (1, channel_id, option),
1143                                 });
1144                         },
1145                         &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1146                                 6u8.write(writer)?;
1147                                 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1148                                 write_tlv_fields!(writer, {
1149                                         (0, intercept_id, required),
1150                                         (2, intercept_scid, required),
1151                                         (4, payment_hash, required),
1152                                         (6, inbound_amount_msat, required),
1153                                         (8, expected_outbound_amount_msat, required),
1154                                 });
1155                         }
1156                         &Event::PaymentForwarded {
1157                                 prev_channel_id, next_channel_id, prev_user_channel_id, next_user_channel_id,
1158                                 total_fee_earned_msat, skimmed_fee_msat, claim_from_onchain_tx,
1159                                 outbound_amount_forwarded_msat,
1160                         } => {
1161                                 7u8.write(writer)?;
1162                                 write_tlv_fields!(writer, {
1163                                         (0, total_fee_earned_msat, option),
1164                                         (1, prev_channel_id, option),
1165                                         (2, claim_from_onchain_tx, required),
1166                                         (3, next_channel_id, option),
1167                                         (5, outbound_amount_forwarded_msat, option),
1168                                         (7, skimmed_fee_msat, option),
1169                                         (9, prev_user_channel_id, option),
1170                                         (11, next_user_channel_id, option),
1171                                 });
1172                         },
1173                         &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason,
1174                                 ref counterparty_node_id, ref channel_capacity_sats, ref channel_funding_txo
1175                         } => {
1176                                 9u8.write(writer)?;
1177                                 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1178                                 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1179                                 // separate u64 values.
1180                                 let user_channel_id_low = *user_channel_id as u64;
1181                                 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1182                                 write_tlv_fields!(writer, {
1183                                         (0, channel_id, required),
1184                                         (1, user_channel_id_low, required),
1185                                         (2, reason, required),
1186                                         (3, user_channel_id_high, required),
1187                                         (5, counterparty_node_id, option),
1188                                         (7, channel_capacity_sats, option),
1189                                         (9, channel_funding_txo, option),
1190                                 });
1191                         },
1192                         &Event::DiscardFunding { ref channel_id, ref transaction } => {
1193                                 11u8.write(writer)?;
1194                                 write_tlv_fields!(writer, {
1195                                         (0, channel_id, required),
1196                                         (2, transaction, required)
1197                                 })
1198                         },
1199                         &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1200                                 13u8.write(writer)?;
1201                                 write_tlv_fields!(writer, {
1202                                         (0, payment_id, required),
1203                                         (2, payment_hash, option),
1204                                         (4, path.hops, required_vec),
1205                                         (6, path.blinded_tail, option),
1206                                 })
1207                         },
1208                         &Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
1209                                 15u8.write(writer)?;
1210                                 write_tlv_fields!(writer, {
1211                                         (0, payment_id, required),
1212                                         (1, reason, option),
1213                                         (2, payment_hash, required),
1214                                 })
1215                         },
1216                         &Event::OpenChannelRequest { .. } => {
1217                                 17u8.write(writer)?;
1218                                 // We never write the OpenChannelRequest events as, upon disconnection, peers
1219                                 // drop any channels which have not yet exchanged funding_signed.
1220                         },
1221                         &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref htlcs, ref sender_intended_total_msat } => {
1222                                 19u8.write(writer)?;
1223                                 write_tlv_fields!(writer, {
1224                                         (0, payment_hash, required),
1225                                         (1, receiver_node_id, option),
1226                                         (2, purpose, required),
1227                                         (4, amount_msat, required),
1228                                         (5, *htlcs, optional_vec),
1229                                         (7, sender_intended_total_msat, option),
1230                                 });
1231                         },
1232                         &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1233                                 21u8.write(writer)?;
1234                                 write_tlv_fields!(writer, {
1235                                         (0, payment_id, required),
1236                                         (2, payment_hash, required),
1237                                         (4, path.hops, required_vec),
1238                                         (6, path.blinded_tail, option),
1239                                 })
1240                         },
1241                         &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1242                                 23u8.write(writer)?;
1243                                 write_tlv_fields!(writer, {
1244                                         (0, payment_id, required),
1245                                         (2, payment_hash, required),
1246                                         (4, path.hops, required_vec),
1247                                         (6, short_channel_id, option),
1248                                         (8, path.blinded_tail, option),
1249                                 })
1250                         },
1251                         &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1252                                 25u8.write(writer)?;
1253                                 write_tlv_fields!(writer, {
1254                                         (0, prev_channel_id, required),
1255                                         (2, failed_next_destination, required),
1256                                 })
1257                         },
1258                         &Event::BumpTransaction(ref event)=> {
1259                                 27u8.write(writer)?;
1260                                 match event {
1261                                         // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1262                                         // upon restarting anyway if they remain unresolved.
1263                                         BumpTransactionEvent::ChannelClose { .. } => {}
1264                                         BumpTransactionEvent::HTLCResolution { .. } => {}
1265                                 }
1266                                 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1267                         }
1268                         &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1269                                 29u8.write(writer)?;
1270                                 write_tlv_fields!(writer, {
1271                                         (0, channel_id, required),
1272                                         (2, user_channel_id, required),
1273                                         (4, counterparty_node_id, required),
1274                                         (6, channel_type, required),
1275                                 });
1276                         },
1277                         &Event::ChannelPending { ref channel_id, ref user_channel_id,
1278                                 ref former_temporary_channel_id, ref counterparty_node_id, ref funding_txo,
1279                                 ref channel_type
1280                         } => {
1281                                 31u8.write(writer)?;
1282                                 write_tlv_fields!(writer, {
1283                                         (0, channel_id, required),
1284                                         (1, channel_type, option),
1285                                         (2, user_channel_id, required),
1286                                         (4, former_temporary_channel_id, required),
1287                                         (6, counterparty_node_id, required),
1288                                         (8, funding_txo, required),
1289                                 });
1290                         },
1291                         &Event::InvoiceRequestFailed { ref payment_id } => {
1292                                 33u8.write(writer)?;
1293                                 write_tlv_fields!(writer, {
1294                                         (0, payment_id, required),
1295                                 })
1296                         },
1297                         &Event::ConnectionNeeded { .. } => {
1298                                 35u8.write(writer)?;
1299                                 // Never write ConnectionNeeded events as buffered onion messages aren't serialized.
1300                         },
1301                         &Event::OnionMessageIntercepted { ref peer_node_id, ref message } => {
1302                                 37u8.write(writer)?;
1303                                 write_tlv_fields!(writer, {
1304                                         (0, peer_node_id, required),
1305                                         (2, message, required),
1306                                 });
1307                         }
1308                         // Note that, going forward, all new events must only write data inside of
1309                         // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1310                         // data via `write_tlv_fields`.
1311                 }
1312                 Ok(())
1313         }
1314 }
1315 impl MaybeReadable for Event {
1316         fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1317                 match Readable::read(reader)? {
1318                         // Note that we do not write a length-prefixed TLV for FundingGenerationReady events.
1319                         0u8 => Ok(None),
1320                         1u8 => {
1321                                 let mut f = || {
1322                                         let mut payment_hash = PaymentHash([0; 32]);
1323                                         let mut payment_preimage = None;
1324                                         let mut payment_secret = None;
1325                                         let mut amount_msat = 0;
1326                                         let mut counterparty_skimmed_fee_msat_opt = None;
1327                                         let mut receiver_node_id = None;
1328                                         let mut _user_payment_id = None::<u64>; // Used in 0.0.103 and earlier, no longer written in 0.0.116+.
1329                                         let mut via_channel_id = None;
1330                                         let mut claim_deadline = None;
1331                                         let mut via_user_channel_id = None;
1332                                         let mut onion_fields = None;
1333                                         read_tlv_fields!(reader, {
1334                                                 (0, payment_hash, required),
1335                                                 (1, receiver_node_id, option),
1336                                                 (2, payment_secret, option),
1337                                                 (3, via_channel_id, option),
1338                                                 (4, amount_msat, required),
1339                                                 (5, via_user_channel_id, option),
1340                                                 (6, _user_payment_id, option),
1341                                                 (7, claim_deadline, option),
1342                                                 (8, payment_preimage, option),
1343                                                 (9, onion_fields, option),
1344                                                 (10, counterparty_skimmed_fee_msat_opt, option),
1345                                         });
1346                                         let purpose = match payment_secret {
1347                                                 Some(secret) => PaymentPurpose::InvoicePayment {
1348                                                         payment_preimage,
1349                                                         payment_secret: secret
1350                                                 },
1351                                                 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1352                                                 None => return Err(msgs::DecodeError::InvalidValue),
1353                                         };
1354                                         Ok(Some(Event::PaymentClaimable {
1355                                                 receiver_node_id,
1356                                                 payment_hash,
1357                                                 amount_msat,
1358                                                 counterparty_skimmed_fee_msat: counterparty_skimmed_fee_msat_opt.unwrap_or(0),
1359                                                 purpose,
1360                                                 via_channel_id,
1361                                                 via_user_channel_id,
1362                                                 claim_deadline,
1363                                                 onion_fields,
1364                                         }))
1365                                 };
1366                                 f()
1367                         },
1368                         2u8 => {
1369                                 let mut f = || {
1370                                         let mut payment_preimage = PaymentPreimage([0; 32]);
1371                                         let mut payment_hash = None;
1372                                         let mut payment_id = None;
1373                                         let mut fee_paid_msat = None;
1374                                         read_tlv_fields!(reader, {
1375                                                 (0, payment_preimage, required),
1376                                                 (1, payment_hash, option),
1377                                                 (3, payment_id, option),
1378                                                 (5, fee_paid_msat, option),
1379                                         });
1380                                         if payment_hash.is_none() {
1381                                                 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()));
1382                                         }
1383                                         Ok(Some(Event::PaymentSent {
1384                                                 payment_id,
1385                                                 payment_preimage,
1386                                                 payment_hash: payment_hash.unwrap(),
1387                                                 fee_paid_msat,
1388                                         }))
1389                                 };
1390                                 f()
1391                         },
1392                         3u8 => {
1393                                 let mut f = || {
1394                                         #[cfg(test)]
1395                                         let error_code = Readable::read(reader)?;
1396                                         #[cfg(test)]
1397                                         let error_data = Readable::read(reader)?;
1398                                         let mut payment_hash = PaymentHash([0; 32]);
1399                                         let mut payment_failed_permanently = false;
1400                                         let mut network_update = None;
1401                                         let mut blinded_tail: Option<BlindedTail> = None;
1402                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1403                                         let mut short_channel_id = None;
1404                                         let mut payment_id = None;
1405                                         let mut failure_opt = None;
1406                                         read_tlv_fields!(reader, {
1407                                                 (0, payment_hash, required),
1408                                                 (1, network_update, upgradable_option),
1409                                                 (2, payment_failed_permanently, required),
1410                                                 (4, blinded_tail, option),
1411                                                 // Added as a part of LDK 0.0.101 and always filled in since.
1412                                                 // Defaults to an empty Vec, though likely should have been `Option`al.
1413                                                 (5, path, optional_vec),
1414                                                 (7, short_channel_id, option),
1415                                                 (11, payment_id, option),
1416                                                 (13, failure_opt, upgradable_option),
1417                                         });
1418                                         let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1419                                         Ok(Some(Event::PaymentPathFailed {
1420                                                 payment_id,
1421                                                 payment_hash,
1422                                                 payment_failed_permanently,
1423                                                 failure,
1424                                                 path: Path { hops: path.unwrap(), blinded_tail },
1425                                                 short_channel_id,
1426                                                 #[cfg(test)]
1427                                                 error_code,
1428                                                 #[cfg(test)]
1429                                                 error_data,
1430                                         }))
1431                                 };
1432                                 f()
1433                         },
1434                         4u8 => Ok(None),
1435                         5u8 => {
1436                                 let mut f = || {
1437                                         let mut outputs = WithoutLength(Vec::new());
1438                                         let mut channel_id: Option<ChannelId> = None;
1439                                         read_tlv_fields!(reader, {
1440                                                 (0, outputs, required),
1441                                                 (1, channel_id, option),
1442                                         });
1443                                         Ok(Some(Event::SpendableOutputs { outputs: outputs.0, channel_id }))
1444                                 };
1445                                 f()
1446                         },
1447                         6u8 => {
1448                                 let mut payment_hash = PaymentHash([0; 32]);
1449                                 let mut intercept_id = InterceptId([0; 32]);
1450                                 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1451                                 let mut inbound_amount_msat = 0;
1452                                 let mut expected_outbound_amount_msat = 0;
1453                                 read_tlv_fields!(reader, {
1454                                         (0, intercept_id, required),
1455                                         (2, requested_next_hop_scid, required),
1456                                         (4, payment_hash, required),
1457                                         (6, inbound_amount_msat, required),
1458                                         (8, expected_outbound_amount_msat, required),
1459                                 });
1460                                 let next_scid = match requested_next_hop_scid {
1461                                         InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1462                                 };
1463                                 Ok(Some(Event::HTLCIntercepted {
1464                                         payment_hash,
1465                                         requested_next_hop_scid: next_scid,
1466                                         inbound_amount_msat,
1467                                         expected_outbound_amount_msat,
1468                                         intercept_id,
1469                                 }))
1470                         },
1471                         7u8 => {
1472                                 let mut f = || {
1473                                         let mut prev_channel_id = None;
1474                                         let mut next_channel_id = None;
1475                                         let mut prev_user_channel_id = None;
1476                                         let mut next_user_channel_id = None;
1477                                         let mut total_fee_earned_msat = None;
1478                                         let mut skimmed_fee_msat = None;
1479                                         let mut claim_from_onchain_tx = false;
1480                                         let mut outbound_amount_forwarded_msat = None;
1481                                         read_tlv_fields!(reader, {
1482                                                 (0, total_fee_earned_msat, option),
1483                                                 (1, prev_channel_id, option),
1484                                                 (2, claim_from_onchain_tx, required),
1485                                                 (3, next_channel_id, option),
1486                                                 (5, outbound_amount_forwarded_msat, option),
1487                                                 (7, skimmed_fee_msat, option),
1488                                                 (9, prev_user_channel_id, option),
1489                                                 (11, next_user_channel_id, option),
1490                                         });
1491                                         Ok(Some(Event::PaymentForwarded {
1492                                                 prev_channel_id, next_channel_id, prev_user_channel_id,
1493                                                 next_user_channel_id, total_fee_earned_msat, skimmed_fee_msat,
1494                                                 claim_from_onchain_tx, outbound_amount_forwarded_msat,
1495                                         }))
1496                                 };
1497                                 f()
1498                         },
1499                         9u8 => {
1500                                 let mut f = || {
1501                                         let mut channel_id = ChannelId::new_zero();
1502                                         let mut reason = UpgradableRequired(None);
1503                                         let mut user_channel_id_low_opt: Option<u64> = None;
1504                                         let mut user_channel_id_high_opt: Option<u64> = None;
1505                                         let mut counterparty_node_id = None;
1506                                         let mut channel_capacity_sats = None;
1507                                         let mut channel_funding_txo = None;
1508                                         read_tlv_fields!(reader, {
1509                                                 (0, channel_id, required),
1510                                                 (1, user_channel_id_low_opt, option),
1511                                                 (2, reason, upgradable_required),
1512                                                 (3, user_channel_id_high_opt, option),
1513                                                 (5, counterparty_node_id, option),
1514                                                 (7, channel_capacity_sats, option),
1515                                                 (9, channel_funding_txo, option),
1516                                         });
1517
1518                                         // `user_channel_id` used to be a single u64 value. In order to remain
1519                                         // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1520                                         // as two separate u64 values.
1521                                         let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1522                                                 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1523
1524                                         Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required),
1525                                                 counterparty_node_id, channel_capacity_sats, channel_funding_txo }))
1526                                 };
1527                                 f()
1528                         },
1529                         11u8 => {
1530                                 let mut f = || {
1531                                         let mut channel_id = ChannelId::new_zero();
1532                                         let mut transaction = Transaction{ version: 2, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
1533                                         read_tlv_fields!(reader, {
1534                                                 (0, channel_id, required),
1535                                                 (2, transaction, required),
1536                                         });
1537                                         Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1538                                 };
1539                                 f()
1540                         },
1541                         13u8 => {
1542                                 let mut f = || {
1543                                         _init_and_read_len_prefixed_tlv_fields!(reader, {
1544                                                 (0, payment_id, required),
1545                                                 (2, payment_hash, option),
1546                                                 (4, path, required_vec),
1547                                                 (6, blinded_tail, option),
1548                                         });
1549                                         Ok(Some(Event::PaymentPathSuccessful {
1550                                                 payment_id: payment_id.0.unwrap(),
1551                                                 payment_hash,
1552                                                 path: Path { hops: path, blinded_tail },
1553                                         }))
1554                                 };
1555                                 f()
1556                         },
1557                         15u8 => {
1558                                 let mut f = || {
1559                                         let mut payment_hash = PaymentHash([0; 32]);
1560                                         let mut payment_id = PaymentId([0; 32]);
1561                                         let mut reason = None;
1562                                         read_tlv_fields!(reader, {
1563                                                 (0, payment_id, required),
1564                                                 (1, reason, upgradable_option),
1565                                                 (2, payment_hash, required),
1566                                         });
1567                                         Ok(Some(Event::PaymentFailed {
1568                                                 payment_id,
1569                                                 payment_hash,
1570                                                 reason,
1571                                         }))
1572                                 };
1573                                 f()
1574                         },
1575                         17u8 => {
1576                                 // Value 17 is used for `Event::OpenChannelRequest`.
1577                                 Ok(None)
1578                         },
1579                         19u8 => {
1580                                 let mut f = || {
1581                                         let mut payment_hash = PaymentHash([0; 32]);
1582                                         let mut purpose = UpgradableRequired(None);
1583                                         let mut amount_msat = 0;
1584                                         let mut receiver_node_id = None;
1585                                         let mut htlcs: Option<Vec<ClaimedHTLC>> = Some(vec![]);
1586                                         let mut sender_intended_total_msat: Option<u64> = None;
1587                                         read_tlv_fields!(reader, {
1588                                                 (0, payment_hash, required),
1589                                                 (1, receiver_node_id, option),
1590                                                 (2, purpose, upgradable_required),
1591                                                 (4, amount_msat, required),
1592                                                 (5, htlcs, optional_vec),
1593                                                 (7, sender_intended_total_msat, option),
1594                                         });
1595                                         Ok(Some(Event::PaymentClaimed {
1596                                                 receiver_node_id,
1597                                                 payment_hash,
1598                                                 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1599                                                 amount_msat,
1600                                                 htlcs: htlcs.unwrap_or(vec![]),
1601                                                 sender_intended_total_msat,
1602                                         }))
1603                                 };
1604                                 f()
1605                         },
1606                         21u8 => {
1607                                 let mut f = || {
1608                                         _init_and_read_len_prefixed_tlv_fields!(reader, {
1609                                                 (0, payment_id, required),
1610                                                 (2, payment_hash, required),
1611                                                 (4, path, required_vec),
1612                                                 (6, blinded_tail, option),
1613                                         });
1614                                         Ok(Some(Event::ProbeSuccessful {
1615                                                 payment_id: payment_id.0.unwrap(),
1616                                                 payment_hash: payment_hash.0.unwrap(),
1617                                                 path: Path { hops: path, blinded_tail },
1618                                         }))
1619                                 };
1620                                 f()
1621                         },
1622                         23u8 => {
1623                                 let mut f = || {
1624                                         _init_and_read_len_prefixed_tlv_fields!(reader, {
1625                                                 (0, payment_id, required),
1626                                                 (2, payment_hash, required),
1627                                                 (4, path, required_vec),
1628                                                 (6, short_channel_id, option),
1629                                                 (8, blinded_tail, option),
1630                                         });
1631                                         Ok(Some(Event::ProbeFailed {
1632                                                 payment_id: payment_id.0.unwrap(),
1633                                                 payment_hash: payment_hash.0.unwrap(),
1634                                                 path: Path { hops: path, blinded_tail },
1635                                                 short_channel_id,
1636                                         }))
1637                                 };
1638                                 f()
1639                         },
1640                         25u8 => {
1641                                 let mut f = || {
1642                                         let mut prev_channel_id = ChannelId::new_zero();
1643                                         let mut failed_next_destination_opt = UpgradableRequired(None);
1644                                         read_tlv_fields!(reader, {
1645                                                 (0, prev_channel_id, required),
1646                                                 (2, failed_next_destination_opt, upgradable_required),
1647                                         });
1648                                         Ok(Some(Event::HTLCHandlingFailed {
1649                                                 prev_channel_id,
1650                                                 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1651                                         }))
1652                                 };
1653                                 f()
1654                         },
1655                         27u8 => Ok(None),
1656                         29u8 => {
1657                                 let mut f = || {
1658                                         let mut channel_id = ChannelId::new_zero();
1659                                         let mut user_channel_id: u128 = 0;
1660                                         let mut counterparty_node_id = RequiredWrapper(None);
1661                                         let mut channel_type = RequiredWrapper(None);
1662                                         read_tlv_fields!(reader, {
1663                                                 (0, channel_id, required),
1664                                                 (2, user_channel_id, required),
1665                                                 (4, counterparty_node_id, required),
1666                                                 (6, channel_type, required),
1667                                         });
1668
1669                                         Ok(Some(Event::ChannelReady {
1670                                                 channel_id,
1671                                                 user_channel_id,
1672                                                 counterparty_node_id: counterparty_node_id.0.unwrap(),
1673                                                 channel_type: channel_type.0.unwrap()
1674                                         }))
1675                                 };
1676                                 f()
1677                         },
1678                         31u8 => {
1679                                 let mut f = || {
1680                                         let mut channel_id = ChannelId::new_zero();
1681                                         let mut user_channel_id: u128 = 0;
1682                                         let mut former_temporary_channel_id = None;
1683                                         let mut counterparty_node_id = RequiredWrapper(None);
1684                                         let mut funding_txo = RequiredWrapper(None);
1685                                         let mut channel_type = None;
1686                                         read_tlv_fields!(reader, {
1687                                                 (0, channel_id, required),
1688                                                 (1, channel_type, option),
1689                                                 (2, user_channel_id, required),
1690                                                 (4, former_temporary_channel_id, required),
1691                                                 (6, counterparty_node_id, required),
1692                                                 (8, funding_txo, required),
1693                                         });
1694
1695                                         Ok(Some(Event::ChannelPending {
1696                                                 channel_id,
1697                                                 user_channel_id,
1698                                                 former_temporary_channel_id,
1699                                                 counterparty_node_id: counterparty_node_id.0.unwrap(),
1700                                                 funding_txo: funding_txo.0.unwrap(),
1701                                                 channel_type,
1702                                         }))
1703                                 };
1704                                 f()
1705                         },
1706                         33u8 => {
1707                                 let mut f = || {
1708                                         _init_and_read_len_prefixed_tlv_fields!(reader, {
1709                                                 (0, payment_id, required),
1710                                         });
1711                                         Ok(Some(Event::InvoiceRequestFailed {
1712                                                 payment_id: payment_id.0.unwrap(),
1713                                         }))
1714                                 };
1715                                 f()
1716                         },
1717                         // Note that we do not write a length-prefixed TLV for ConnectionNeeded events.
1718                         35u8 => Ok(None),
1719                         37u8 => {
1720                                 let mut f = || {
1721                                         _init_and_read_len_prefixed_tlv_fields!(reader, {
1722                                                 (0, peer_node_id, required),
1723                                                 (2, message, required),
1724                                         });
1725                                         Ok(Some(Event::OnionMessageIntercepted {
1726                                                 peer_node_id: peer_node_id.0.unwrap(), message: message.0.unwrap()
1727                                         }))
1728                                 };
1729                                 f()
1730                         },
1731                         // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1732                         // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1733                         // reads.
1734                         x if x % 2 == 1 => {
1735                                 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1736                                 // which prefixes the whole thing with a length BigSize. Because the event is
1737                                 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1738                                 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1739                                 // exactly the number of bytes specified, ignoring them entirely.
1740                                 let tlv_len: BigSize = Readable::read(reader)?;
1741                                 FixedLengthReader::new(reader, tlv_len.0)
1742                                         .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1743                                 Ok(None)
1744                         },
1745                         _ => Err(msgs::DecodeError::InvalidValue)
1746                 }
1747         }
1748 }
1749
1750 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1751 /// broadcast to most peers).
1752 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1753 #[derive(Clone, Debug)]
1754 #[cfg_attr(test, derive(PartialEq))]
1755 pub enum MessageSendEvent {
1756         /// Used to indicate that we've accepted a channel open and should send the accept_channel
1757         /// message provided to the given peer.
1758         SendAcceptChannel {
1759                 /// The node_id of the node which should receive this message
1760                 node_id: PublicKey,
1761                 /// The message which should be sent.
1762                 msg: msgs::AcceptChannel,
1763         },
1764         /// Used to indicate that we've accepted a V2 channel open and should send the accept_channel2
1765         /// message provided to the given peer.
1766         SendAcceptChannelV2 {
1767                 /// The node_id of the node which should receive this message
1768                 node_id: PublicKey,
1769                 /// The message which should be sent.
1770                 msg: msgs::AcceptChannelV2,
1771         },
1772         /// Used to indicate that we've initiated a channel open and should send the open_channel
1773         /// message provided to the given peer.
1774         SendOpenChannel {
1775                 /// The node_id of the node which should receive this message
1776                 node_id: PublicKey,
1777                 /// The message which should be sent.
1778                 msg: msgs::OpenChannel,
1779         },
1780         /// Used to indicate that we've initiated a V2 channel open and should send the open_channel2
1781         /// message provided to the given peer.
1782         SendOpenChannelV2 {
1783                 /// The node_id of the node which should receive this message
1784                 node_id: PublicKey,
1785                 /// The message which should be sent.
1786                 msg: msgs::OpenChannelV2,
1787         },
1788         /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1789         SendFundingCreated {
1790                 /// The node_id of the node which should receive this message
1791                 node_id: PublicKey,
1792                 /// The message which should be sent.
1793                 msg: msgs::FundingCreated,
1794         },
1795         /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1796         SendFundingSigned {
1797                 /// The node_id of the node which should receive this message
1798                 node_id: PublicKey,
1799                 /// The message which should be sent.
1800                 msg: msgs::FundingSigned,
1801         },
1802         /// Used to indicate that a stfu message should be sent to the peer with the given node id.
1803         SendStfu {
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::Stfu,
1808         },
1809         /// Used to indicate that a splice message should be sent to the peer with the given node id.
1810         SendSplice {
1811                 /// The node_id of the node which should receive this message
1812                 node_id: PublicKey,
1813                 /// The message which should be sent.
1814                 msg: msgs::Splice,
1815         },
1816         /// Used to indicate that a splice_ack message should be sent to the peer with the given node id.
1817         SendSpliceAck {
1818                 /// The node_id of the node which should receive this message
1819                 node_id: PublicKey,
1820                 /// The message which should be sent.
1821                 msg: msgs::SpliceAck,
1822         },
1823         /// Used to indicate that a splice_locked message should be sent to the peer with the given node id.
1824         SendSpliceLocked {
1825                 /// The node_id of the node which should receive this message
1826                 node_id: PublicKey,
1827                 /// The message which should be sent.
1828                 msg: msgs::SpliceLocked,
1829         },
1830         /// Used to indicate that a tx_add_input message should be sent to the peer with the given node_id.
1831         SendTxAddInput {
1832                 /// The node_id of the node which should receive this message
1833                 node_id: PublicKey,
1834                 /// The message which should be sent.
1835                 msg: msgs::TxAddInput,
1836         },
1837         /// Used to indicate that a tx_add_output message should be sent to the peer with the given node_id.
1838         SendTxAddOutput {
1839                 /// The node_id of the node which should receive this message
1840                 node_id: PublicKey,
1841                 /// The message which should be sent.
1842                 msg: msgs::TxAddOutput,
1843         },
1844         /// Used to indicate that a tx_remove_input message should be sent to the peer with the given node_id.
1845         SendTxRemoveInput {
1846                 /// The node_id of the node which should receive this message
1847                 node_id: PublicKey,
1848                 /// The message which should be sent.
1849                 msg: msgs::TxRemoveInput,
1850         },
1851         /// Used to indicate that a tx_remove_output message should be sent to the peer with the given node_id.
1852         SendTxRemoveOutput {
1853                 /// The node_id of the node which should receive this message
1854                 node_id: PublicKey,
1855                 /// The message which should be sent.
1856                 msg: msgs::TxRemoveOutput,
1857         },
1858         /// Used to indicate that a tx_complete message should be sent to the peer with the given node_id.
1859         SendTxComplete {
1860                 /// The node_id of the node which should receive this message
1861                 node_id: PublicKey,
1862                 /// The message which should be sent.
1863                 msg: msgs::TxComplete,
1864         },
1865         /// Used to indicate that a tx_signatures message should be sent to the peer with the given node_id.
1866         SendTxSignatures {
1867                 /// The node_id of the node which should receive this message
1868                 node_id: PublicKey,
1869                 /// The message which should be sent.
1870                 msg: msgs::TxSignatures,
1871         },
1872         /// Used to indicate that a tx_init_rbf message should be sent to the peer with the given node_id.
1873         SendTxInitRbf {
1874                 /// The node_id of the node which should receive this message
1875                 node_id: PublicKey,
1876                 /// The message which should be sent.
1877                 msg: msgs::TxInitRbf,
1878         },
1879         /// Used to indicate that a tx_ack_rbf message should be sent to the peer with the given node_id.
1880         SendTxAckRbf {
1881                 /// The node_id of the node which should receive this message
1882                 node_id: PublicKey,
1883                 /// The message which should be sent.
1884                 msg: msgs::TxAckRbf,
1885         },
1886         /// Used to indicate that a tx_abort message should be sent to the peer with the given node_id.
1887         SendTxAbort {
1888                 /// The node_id of the node which should receive this message
1889                 node_id: PublicKey,
1890                 /// The message which should be sent.
1891                 msg: msgs::TxAbort,
1892         },
1893         /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1894         SendChannelReady {
1895                 /// The node_id of the node which should receive these message(s)
1896                 node_id: PublicKey,
1897                 /// The channel_ready message which should be sent.
1898                 msg: msgs::ChannelReady,
1899         },
1900         /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1901         SendAnnouncementSignatures {
1902                 /// The node_id of the node which should receive these message(s)
1903                 node_id: PublicKey,
1904                 /// The announcement_signatures message which should be sent.
1905                 msg: msgs::AnnouncementSignatures,
1906         },
1907         /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1908         /// message should be sent to the peer with the given node_id.
1909         UpdateHTLCs {
1910                 /// The node_id of the node which should receive these message(s)
1911                 node_id: PublicKey,
1912                 /// The update messages which should be sent. ALL messages in the struct should be sent!
1913                 updates: msgs::CommitmentUpdate,
1914         },
1915         /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1916         SendRevokeAndACK {
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::RevokeAndACK,
1921         },
1922         /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1923         SendClosingSigned {
1924                 /// The node_id of the node which should receive this message
1925                 node_id: PublicKey,
1926                 /// The message which should be sent.
1927                 msg: msgs::ClosingSigned,
1928         },
1929         /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1930         SendShutdown {
1931                 /// The node_id of the node which should receive this message
1932                 node_id: PublicKey,
1933                 /// The message which should be sent.
1934                 msg: msgs::Shutdown,
1935         },
1936         /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1937         SendChannelReestablish {
1938                 /// The node_id of the node which should receive this message
1939                 node_id: PublicKey,
1940                 /// The message which should be sent.
1941                 msg: msgs::ChannelReestablish,
1942         },
1943         /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1944         /// initial connection to ensure our peers know about our channels.
1945         SendChannelAnnouncement {
1946                 /// The node_id of the node which should receive this message
1947                 node_id: PublicKey,
1948                 /// The channel_announcement which should be sent.
1949                 msg: msgs::ChannelAnnouncement,
1950                 /// The followup channel_update which should be sent.
1951                 update_msg: msgs::ChannelUpdate,
1952         },
1953         /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1954         /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1955         ///
1956         /// Note that after doing so, you very likely (unless you did so very recently) want to
1957         /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1958         /// ensures that any nodes which see our channel_announcement also have a relevant
1959         /// node_announcement, including relevant feature flags which may be important for routing
1960         /// through or to us.
1961         ///
1962         /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1963         BroadcastChannelAnnouncement {
1964                 /// The channel_announcement which should be sent.
1965                 msg: msgs::ChannelAnnouncement,
1966                 /// The followup channel_update which should be sent.
1967                 update_msg: Option<msgs::ChannelUpdate>,
1968         },
1969         /// Used to indicate that a channel_update should be broadcast to all peers.
1970         BroadcastChannelUpdate {
1971                 /// The channel_update which should be sent.
1972                 msg: msgs::ChannelUpdate,
1973         },
1974         /// Used to indicate that a node_announcement should be broadcast to all peers.
1975         BroadcastNodeAnnouncement {
1976                 /// The node_announcement which should be sent.
1977                 msg: msgs::NodeAnnouncement,
1978         },
1979         /// Used to indicate that a channel_update should be sent to a single peer.
1980         /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1981         /// private channel and we shouldn't be informing all of our peers of channel parameters.
1982         SendChannelUpdate {
1983                 /// The node_id of the node which should receive this message
1984                 node_id: PublicKey,
1985                 /// The channel_update which should be sent.
1986                 msg: msgs::ChannelUpdate,
1987         },
1988         /// Broadcast an error downstream to be handled
1989         HandleError {
1990                 /// The node_id of the node which should receive this message
1991                 node_id: PublicKey,
1992                 /// The action which should be taken.
1993                 action: msgs::ErrorAction
1994         },
1995         /// Query a peer for channels with funding transaction UTXOs in a block range.
1996         SendChannelRangeQuery {
1997                 /// The node_id of this message recipient
1998                 node_id: PublicKey,
1999                 /// The query_channel_range which should be sent.
2000                 msg: msgs::QueryChannelRange,
2001         },
2002         /// Request routing gossip messages from a peer for a list of channels identified by
2003         /// their short_channel_ids.
2004         SendShortIdsQuery {
2005                 /// The node_id of this message recipient
2006                 node_id: PublicKey,
2007                 /// The query_short_channel_ids which should be sent.
2008                 msg: msgs::QueryShortChannelIds,
2009         },
2010         /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
2011         /// emitted during processing of the query.
2012         SendReplyChannelRange {
2013                 /// The node_id of this message recipient
2014                 node_id: PublicKey,
2015                 /// The reply_channel_range which should be sent.
2016                 msg: msgs::ReplyChannelRange,
2017         },
2018         /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
2019         /// enable receiving gossip messages from the peer.
2020         SendGossipTimestampFilter {
2021                 /// The node_id of this message recipient
2022                 node_id: PublicKey,
2023                 /// The gossip_timestamp_filter which should be sent.
2024                 msg: msgs::GossipTimestampFilter,
2025         },
2026 }
2027
2028 /// A trait indicating an object may generate message send events
2029 pub trait MessageSendEventsProvider {
2030         /// Gets the list of pending events which were generated by previous actions, clearing the list
2031         /// in the process.
2032         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
2033 }
2034
2035 /// A trait indicating an object may generate events.
2036 ///
2037 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
2038 ///
2039 /// Implementations of this trait may also feature an async version of event handling, as shown with
2040 /// [`ChannelManager::process_pending_events_async`] and
2041 /// [`ChainMonitor::process_pending_events_async`].
2042 ///
2043 /// # Requirements
2044 ///
2045 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
2046 /// event since the last invocation.
2047 ///
2048 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
2049 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
2050 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
2051 /// relevant changes to disk *before* returning.
2052 ///
2053 /// Further, because an application may crash between an [`Event`] being handled and the
2054 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
2055 /// effect, [`Event`]s may be replayed.
2056 ///
2057 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
2058 /// consult the provider's documentation on the implication of processing events and how a handler
2059 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
2060 /// [`ChainMonitor::process_pending_events`]).
2061 ///
2062 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
2063 /// own type(s).
2064 ///
2065 /// [`process_pending_events`]: Self::process_pending_events
2066 /// [`handle_event`]: EventHandler::handle_event
2067 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
2068 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
2069 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
2070 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
2071 pub trait EventsProvider {
2072         /// Processes any events generated since the last call using the given event handler.
2073         ///
2074         /// See the trait-level documentation for requirements.
2075         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
2076 }
2077
2078 /// A trait implemented for objects handling events from [`EventsProvider`].
2079 ///
2080 /// An async variation also exists for implementations of [`EventsProvider`] that support async
2081 /// event handling. The async event handler should satisfy the generic bounds: `F:
2082 /// core::future::Future, H: Fn(Event) -> F`.
2083 pub trait EventHandler {
2084         /// Handles the given [`Event`].
2085         ///
2086         /// See [`EventsProvider`] for details that must be considered when implementing this method.
2087         fn handle_event(&self, event: Event);
2088 }
2089
2090 impl<F> EventHandler for F where F: Fn(Event) {
2091         fn handle_event(&self, event: Event) {
2092                 self(event)
2093         }
2094 }
2095
2096 impl<T: EventHandler> EventHandler for Arc<T> {
2097         fn handle_event(&self, event: Event) {
2098                 self.deref().handle_event(event)
2099         }
2100 }