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