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