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