Upgrade rust-bitcoin to 0.31
[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         },
658         /// Indicates that a peer connection with a node is needed in order to send an [`OnionMessage`].
659         ///
660         /// Typically, this happens when a [`MessageRouter`] is unable to find a complete path to a
661         /// [`Destination`]. Once a connection is established, any messages buffered by an
662         /// [`OnionMessageHandler`] may be sent.
663         ///
664         /// This event will not be generated for onion message forwards; only for sends including
665         /// replies. Handlers should connect to the node otherwise any buffered messages may be lost.
666         ///
667         /// [`OnionMessage`]: msgs::OnionMessage
668         /// [`MessageRouter`]: crate::onion_message::messenger::MessageRouter
669         /// [`Destination`]: crate::onion_message::messenger::Destination
670         /// [`OnionMessageHandler`]: crate::ln::msgs::OnionMessageHandler
671         ConnectionNeeded {
672                 /// The node id for the node needing a connection.
673                 node_id: PublicKey,
674                 /// Sockets for connecting to the node.
675                 addresses: Vec<msgs::SocketAddress>,
676         },
677         /// Indicates a request for an invoice failed to yield a response in a reasonable amount of time
678         /// or was explicitly abandoned by [`ChannelManager::abandon_payment`]. This may be for an
679         /// [`InvoiceRequest`] sent for an [`Offer`] or for a [`Refund`] that hasn't been redeemed.
680         ///
681         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
682         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
683         /// [`Offer`]: crate::offers::offer::Offer
684         /// [`Refund`]: crate::offers::refund::Refund
685         InvoiceRequestFailed {
686                 /// The `payment_id` to have been associated with payment for the requested invoice.
687                 payment_id: PaymentId,
688         },
689         /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
690         /// and we got back the payment preimage for it).
691         ///
692         /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
693         /// event. In this situation, you SHOULD treat this payment as having succeeded.
694         PaymentSent {
695                 /// The `payment_id` passed to [`ChannelManager::send_payment`].
696                 ///
697                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
698                 payment_id: Option<PaymentId>,
699                 /// The preimage to the hash given to ChannelManager::send_payment.
700                 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
701                 /// store it somehow!
702                 payment_preimage: PaymentPreimage,
703                 /// The hash that was given to [`ChannelManager::send_payment`].
704                 ///
705                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
706                 payment_hash: PaymentHash,
707                 /// The total fee which was spent at intermediate hops in this payment, across all paths.
708                 ///
709                 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
710                 /// overpayment to the recipient node.
711                 ///
712                 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
713                 /// overstate the amount paid, though this is unlikely.
714                 ///
715                 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
716                 fee_paid_msat: Option<u64>,
717         },
718         /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
719         /// provide failure information for each path attempt in the payment, including retries.
720         ///
721         /// This event is provided once there are no further pending HTLCs for the payment and the
722         /// payment is no longer retryable, due either to the [`Retry`] provided or
723         /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
724         ///
725         /// In exceedingly rare cases, it is possible that an [`Event::PaymentFailed`] is generated for
726         /// a payment after an [`Event::PaymentSent`] event for this same payment has already been
727         /// received and processed. In this case, the [`Event::PaymentFailed`] event MUST be ignored,
728         /// and the payment MUST be treated as having succeeded.
729         ///
730         /// [`Retry`]: crate::ln::channelmanager::Retry
731         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
732         PaymentFailed {
733                 /// The `payment_id` passed to [`ChannelManager::send_payment`].
734                 ///
735                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
736                 payment_id: PaymentId,
737                 /// The hash that was given to [`ChannelManager::send_payment`].
738                 ///
739                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
740                 payment_hash: PaymentHash,
741                 /// The reason the payment failed. This is only `None` for events generated or serialized
742                 /// by versions prior to 0.0.115.
743                 reason: Option<PaymentFailureReason>,
744         },
745         /// Indicates that a path for an outbound payment was successful.
746         ///
747         /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
748         /// [`Event::PaymentSent`] for obtaining the payment preimage.
749         PaymentPathSuccessful {
750                 /// The `payment_id` passed to [`ChannelManager::send_payment`].
751                 ///
752                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
753                 payment_id: PaymentId,
754                 /// The hash that was given to [`ChannelManager::send_payment`].
755                 ///
756                 /// This will be `Some` for all payments which completed on LDK 0.0.104 or later.
757                 ///
758                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
759                 payment_hash: Option<PaymentHash>,
760                 /// The payment path that was successful.
761                 ///
762                 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
763                 path: Path,
764         },
765         /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
766         /// handle the HTLC.
767         ///
768         /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
769         /// [`Event::PaymentFailed`].
770         ///
771         /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
772         /// been exhausted.
773         ///
774         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
775         PaymentPathFailed {
776                 /// The `payment_id` passed to [`ChannelManager::send_payment`].
777                 ///
778                 /// This will be `Some` for all payment paths which failed on LDK 0.0.103 or later.
779                 ///
780                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
781                 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
782                 payment_id: Option<PaymentId>,
783                 /// The hash that was given to [`ChannelManager::send_payment`].
784                 ///
785                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
786                 payment_hash: PaymentHash,
787                 /// Indicates the payment was rejected for some reason by the recipient. This implies that
788                 /// the payment has failed, not just the route in question. If this is not set, the payment may
789                 /// be retried via a different route.
790                 payment_failed_permanently: bool,
791                 /// Extra error details based on the failure type. May contain an update that needs to be
792                 /// applied to the [`NetworkGraph`].
793                 ///
794                 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
795                 failure: PathFailure,
796                 /// The payment path that failed.
797                 path: Path,
798                 /// The channel responsible for the failed payment path.
799                 ///
800                 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
801                 /// may not refer to a channel in the public network graph. These aliases may also collide
802                 /// with channels in the public network graph.
803                 ///
804                 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
805                 /// retried. May be `None` for older [`Event`] serializations.
806                 short_channel_id: Option<u64>,
807 #[cfg(test)]
808                 error_code: Option<u16>,
809 #[cfg(test)]
810                 error_data: Option<Vec<u8>>,
811         },
812         /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
813         ProbeSuccessful {
814                 /// The id returned by [`ChannelManager::send_probe`].
815                 ///
816                 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
817                 payment_id: PaymentId,
818                 /// The hash generated by [`ChannelManager::send_probe`].
819                 ///
820                 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
821                 payment_hash: PaymentHash,
822                 /// The payment path that was successful.
823                 path: Path,
824         },
825         /// Indicates that a probe payment we sent failed at an intermediary node on the path.
826         ProbeFailed {
827                 /// The id returned by [`ChannelManager::send_probe`].
828                 ///
829                 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
830                 payment_id: PaymentId,
831                 /// The hash generated by [`ChannelManager::send_probe`].
832                 ///
833                 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
834                 payment_hash: PaymentHash,
835                 /// The payment path that failed.
836                 path: Path,
837                 /// The channel responsible for the failed probe.
838                 ///
839                 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
840                 /// may not refer to a channel in the public network graph. These aliases may also collide
841                 /// with channels in the public network graph.
842                 short_channel_id: Option<u64>,
843         },
844         /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
845         /// a time in the future.
846         ///
847         /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
848         PendingHTLCsForwardable {
849                 /// The minimum amount of time that should be waited prior to calling
850                 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
851                 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
852                 /// now + 5*time_forwardable).
853                 time_forwardable: Duration,
854         },
855         /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
856         /// you've encoded an intercept scid in the receiver's invoice route hints using
857         /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
858         ///
859         /// [`ChannelManager::forward_intercepted_htlc`] or
860         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
861         /// their docs for more information.
862         ///
863         /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
864         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
865         /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
866         /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
867         HTLCIntercepted {
868                 /// An id to help LDK identify which HTLC is being forwarded or failed.
869                 intercept_id: InterceptId,
870                 /// The fake scid that was programmed as the next hop's scid, generated using
871                 /// [`ChannelManager::get_intercept_scid`].
872                 ///
873                 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
874                 requested_next_hop_scid: u64,
875                 /// The payment hash used for this HTLC.
876                 payment_hash: PaymentHash,
877                 /// How many msats were received on the inbound edge of this HTLC.
878                 inbound_amount_msat: u64,
879                 /// How many msats the payer intended to route to the next node. Depending on the reason you are
880                 /// intercepting this payment, you might take a fee by forwarding less than this amount.
881                 /// Forwarding less than this amount may break compatibility with LDK versions prior to 0.0.116.
882                 ///
883                 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
884                 /// check that whatever fee you want has been included here or subtract it as required. Further,
885                 /// LDK will not stop you from forwarding more than you received.
886                 expected_outbound_amount_msat: u64,
887         },
888         /// Used to indicate that an output which you should know how to spend was confirmed on chain
889         /// and is now spendable.
890         ///
891         /// Such an output will *never* be spent directly by LDK, and are not at risk of your
892         /// counterparty spending them due to some kind of timeout. Thus, you need to store them
893         /// somewhere and spend them when you create on-chain transactions.
894         ///
895         /// You may hand them to the [`OutputSweeper`] utility which will store and (re-)generate spending
896         /// transactions for you.
897         ///
898         /// [`OutputSweeper`]: crate::util::sweep::OutputSweeper
899         SpendableOutputs {
900                 /// The outputs which you should store as spendable by you.
901                 outputs: Vec<SpendableOutputDescriptor>,
902                 /// The `channel_id` indicating which channel the spendable outputs belong to.
903                 ///
904                 /// This will always be `Some` for events generated by LDK versions 0.0.117 and above.
905                 channel_id: Option<ChannelId>,
906         },
907         /// This event is generated when a payment has been successfully forwarded through us and a
908         /// forwarding fee earned.
909         PaymentForwarded {
910                 /// The channel id of the incoming channel between the previous node and us.
911                 ///
912                 /// This is only `None` for events generated or serialized by versions prior to 0.0.107.
913                 prev_channel_id: Option<ChannelId>,
914                 /// The channel id of the outgoing channel between the next node and us.
915                 ///
916                 /// This is only `None` for events generated or serialized by versions prior to 0.0.107.
917                 next_channel_id: Option<ChannelId>,
918                 /// The `user_channel_id` of the incoming channel between the previous node and us.
919                 ///
920                 /// This is only `None` for events generated or serialized by versions prior to 0.0.122.
921                 prev_user_channel_id: Option<u128>,
922                 /// The `user_channel_id` of the outgoing channel between the next node and us.
923                 ///
924                 /// This will be `None` if the payment was settled via an on-chain transaction. See the
925                 /// caveat described for the `total_fee_earned_msat` field. Moreover it will be `None` for
926                 /// events generated or serialized by versions prior to 0.0.122.
927                 next_user_channel_id: Option<u128>,
928                 /// The total fee, in milli-satoshis, which was earned as a result of the payment.
929                 ///
930                 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
931                 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
932                 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
933                 /// claimed the full value in millisatoshis from the source. In this case,
934                 /// `claim_from_onchain_tx` will be set.
935                 ///
936                 /// If the channel which sent us the payment has been force-closed, we will claim the funds
937                 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
938                 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
939                 /// `PaymentForwarded` events are generated for the same payment iff `total_fee_earned_msat` is
940                 /// `None`.
941                 total_fee_earned_msat: Option<u64>,
942                 /// The share of the total fee, in milli-satoshis, which was withheld in addition to the
943                 /// forwarding fee.
944                 ///
945                 /// This will only be `Some` if we forwarded an intercepted HTLC with less than the
946                 /// expected amount. This means our counterparty accepted to receive less than the invoice
947                 /// amount, e.g., by claiming the payment featuring a corresponding
948                 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`].
949                 ///
950                 /// Will also always be `None` for events serialized with LDK prior to version 0.0.122.
951                 ///
952                 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
953                 ///
954                 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`]: Self::PaymentClaimable::counterparty_skimmed_fee_msat
955                 skimmed_fee_msat: Option<u64>,
956                 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
957                 /// transaction.
958                 claim_from_onchain_tx: bool,
959                 /// The final amount forwarded, in milli-satoshis, after the fee is deducted.
960                 ///
961                 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
962                 outbound_amount_forwarded_msat: Option<u64>,
963         },
964         /// Used to indicate that a channel with the given `channel_id` is being opened and pending
965         /// confirmation on-chain.
966         ///
967         /// This event is emitted when the funding transaction has been signed and is broadcast to the
968         /// network. For 0conf channels it will be immediately followed by the corresponding
969         /// [`Event::ChannelReady`] event.
970         ChannelPending {
971                 /// The `channel_id` of the channel that is pending confirmation.
972                 channel_id: ChannelId,
973                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
974                 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
975                 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
976                 /// `user_channel_id` will be randomized for an inbound channel.
977                 ///
978                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
979                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
980                 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
981                 user_channel_id: u128,
982                 /// The `temporary_channel_id` this channel used to be known by during channel establishment.
983                 ///
984                 /// Will be `None` for channels created prior to LDK version 0.0.115.
985                 former_temporary_channel_id: Option<ChannelId>,
986                 /// The `node_id` of the channel counterparty.
987                 counterparty_node_id: PublicKey,
988                 /// The outpoint of the channel's funding transaction.
989                 funding_txo: OutPoint,
990                 /// The features that this channel will operate with.
991                 ///
992                 /// Will be `None` for channels created prior to LDK version 0.0.122.
993                 channel_type: Option<ChannelTypeFeatures>,
994         },
995         /// Used to indicate that a channel with the given `channel_id` is ready to
996         /// be used. This event is emitted either when the funding transaction has been confirmed
997         /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
998         /// establishment.
999         ChannelReady {
1000                 /// The `channel_id` of the channel that is ready.
1001                 channel_id: ChannelId,
1002                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1003                 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1004                 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1005                 /// `user_channel_id` will be randomized for an inbound channel.
1006                 ///
1007                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1008                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1009                 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1010                 user_channel_id: u128,
1011                 /// The `node_id` of the channel counterparty.
1012                 counterparty_node_id: PublicKey,
1013                 /// The features that this channel will operate with.
1014                 channel_type: ChannelTypeFeatures,
1015         },
1016         /// Used to indicate that a channel that got past the initial handshake with the given `channel_id` is in the
1017         /// process of closure. This includes previously opened channels, and channels that time out from not being funded.
1018         ///
1019         /// Note that this event is only triggered for accepted channels: if the
1020         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true and the channel is
1021         /// rejected, no `ChannelClosed` event will be sent.
1022         ///
1023         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1024         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1025         ChannelClosed {
1026                 /// The `channel_id` of the channel which has been closed. Note that on-chain transactions
1027                 /// resolving the channel are likely still awaiting confirmation.
1028                 channel_id: ChannelId,
1029                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1030                 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1031                 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1032                 /// `user_channel_id` will be randomized for inbound channels.
1033                 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
1034                 /// zero for objects serialized with LDK versions prior to 0.0.102.
1035                 ///
1036                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1037                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1038                 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1039                 user_channel_id: u128,
1040                 /// The reason the channel was closed.
1041                 reason: ClosureReason,
1042                 /// Counterparty in the closed channel.
1043                 ///
1044                 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
1045                 counterparty_node_id: Option<PublicKey>,
1046                 /// Channel capacity of the closing channel (sats).
1047                 ///
1048                 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
1049                 channel_capacity_sats: Option<u64>,
1050                 /// The original channel funding TXO; this helps checking for the existence and confirmation
1051                 /// status of the closing tx.
1052                 /// Note that for instances serialized in v0.0.119 or prior this will be missing (None).
1053                 channel_funding_txo: Option<transaction::OutPoint>,
1054         },
1055         /// Used to indicate to the user that they can abandon the funding transaction and recycle the
1056         /// inputs for another purpose.
1057         ///
1058         /// This event is not guaranteed to be generated for channels that are closed due to a restart.
1059         DiscardFunding {
1060                 /// The channel_id of the channel which has been closed.
1061                 channel_id: ChannelId,
1062                 /// The full transaction received from the user
1063                 transaction: Transaction
1064         },
1065         /// Indicates a request to open a new channel by a peer.
1066         ///
1067         /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the request,
1068         /// call [`ChannelManager::force_close_without_broadcasting_txn`]. Note that a ['ChannelClosed`]
1069         /// event will _not_ be triggered if the channel is rejected.
1070         ///
1071         /// The event is only triggered when a new open channel request is received and the
1072         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
1073         ///
1074         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1075         /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1076         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1077         OpenChannelRequest {
1078                 /// The temporary channel ID of the channel requested to be opened.
1079                 ///
1080                 /// When responding to the request, the `temporary_channel_id` should be passed
1081                 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
1082                 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
1083                 ///
1084                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1085                 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1086                 temporary_channel_id: ChannelId,
1087                 /// The node_id of the counterparty requesting to open the channel.
1088                 ///
1089                 /// When responding to the request, the `counterparty_node_id` should be passed
1090                 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
1091                 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
1092                 /// request.
1093                 ///
1094                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1095                 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1096                 counterparty_node_id: PublicKey,
1097                 /// The channel value of the requested channel.
1098                 funding_satoshis: u64,
1099                 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
1100                 push_msat: u64,
1101                 /// The features that this channel will operate with. If you reject the channel, a
1102                 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
1103                 /// feature flags.
1104                 ///
1105                 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
1106                 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1107                 /// 0.0.106.
1108                 ///
1109                 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
1110                 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1111                 /// 0.0.107. Channels setting this type also need to get manually accepted via
1112                 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
1113                 /// or will be rejected otherwise.
1114                 ///
1115                 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1116                 channel_type: ChannelTypeFeatures,
1117         },
1118         /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
1119         /// forward it.
1120         ///
1121         /// Some scenarios where this event may be sent include:
1122         /// * Insufficient capacity in the outbound channel
1123         /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
1124         /// * When an unknown SCID is requested for forwarding a payment.
1125         /// * Expected MPP amount has already been reached
1126         /// * The HTLC has timed out
1127         ///
1128         /// This event, however, does not get generated if an HTLC fails to meet the forwarding
1129         /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
1130         HTLCHandlingFailed {
1131                 /// The channel over which the HTLC was received.
1132                 prev_channel_id: ChannelId,
1133                 /// Destination of the HTLC that failed to be processed.
1134                 failed_next_destination: HTLCDestination,
1135         },
1136         /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
1137         /// requires confirmed external funds to be readily available to spend.
1138         ///
1139         /// LDK does not currently generate this event unless the
1140         /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`] config flag is set to true.
1141         /// It is limited to the scope of channels with anchor outputs.
1142         ///
1143         /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`]: crate::util::config::ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx
1144         BumpTransaction(BumpTransactionEvent),
1145         /// We received an onion message that is intended to be forwarded to a peer
1146         /// that is currently offline. This event will only be generated if the
1147         /// `OnionMessenger` was initialized with
1148         /// [`OnionMessenger::new_with_offline_peer_interception`], see its docs.
1149         ///
1150         /// [`OnionMessenger::new_with_offline_peer_interception`]: crate::onion_message::messenger::OnionMessenger::new_with_offline_peer_interception
1151         OnionMessageIntercepted {
1152                 /// The node id of the offline peer.
1153                 peer_node_id: PublicKey,
1154                 /// The onion message intended to be forwarded to `peer_node_id`.
1155                 message: msgs::OnionMessage,
1156         },
1157         /// Indicates that an onion message supporting peer has come online and it may
1158         /// be time to forward any onion messages that were previously intercepted for
1159         /// them. This event will only be generated if the `OnionMessenger` was
1160         /// initialized with
1161         /// [`OnionMessenger::new_with_offline_peer_interception`], see its docs.
1162         ///
1163         /// [`OnionMessenger::new_with_offline_peer_interception`]: crate::onion_message::messenger::OnionMessenger::new_with_offline_peer_interception
1164         OnionMessagePeerConnected {
1165                 /// The node id of the peer we just connected to, who advertises support for
1166                 /// onion messages.
1167                 peer_node_id: PublicKey,
1168         }
1169 }
1170
1171 impl Writeable for Event {
1172         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1173                 match self {
1174                         &Event::FundingGenerationReady { .. } => {
1175                                 0u8.write(writer)?;
1176                                 // We never write out FundingGenerationReady events as, upon disconnection, peers
1177                                 // drop any channels which have not yet exchanged funding_signed.
1178                         },
1179                         &Event::PaymentClaimable { ref payment_hash, ref amount_msat, counterparty_skimmed_fee_msat,
1180                                 ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id,
1181                                 ref claim_deadline, ref onion_fields
1182                         } => {
1183                                 1u8.write(writer)?;
1184                                 let mut payment_secret = None;
1185                                 let payment_preimage;
1186                                 let mut payment_context = None;
1187                                 match &purpose {
1188                                         PaymentPurpose::Bolt11InvoicePayment {
1189                                                 payment_preimage: preimage, payment_secret: secret
1190                                         } => {
1191                                                 payment_secret = Some(secret);
1192                                                 payment_preimage = *preimage;
1193                                         },
1194                                         PaymentPurpose::Bolt12OfferPayment {
1195                                                 payment_preimage: preimage, payment_secret: secret, payment_context: context
1196                                         } => {
1197                                                 payment_secret = Some(secret);
1198                                                 payment_preimage = *preimage;
1199                                                 payment_context = Some(PaymentContextRef::Bolt12Offer(context));
1200                                         },
1201                                         PaymentPurpose::Bolt12RefundPayment {
1202                                                 payment_preimage: preimage, payment_secret: secret, payment_context: context
1203                                         } => {
1204                                                 payment_secret = Some(secret);
1205                                                 payment_preimage = *preimage;
1206                                                 payment_context = Some(PaymentContextRef::Bolt12Refund(context));
1207                                         },
1208                                         PaymentPurpose::SpontaneousPayment(preimage) => {
1209                                                 payment_preimage = Some(*preimage);
1210                                         }
1211                                 }
1212                                 let skimmed_fee_opt = if counterparty_skimmed_fee_msat == 0 { None }
1213                                         else { Some(counterparty_skimmed_fee_msat) };
1214                                 write_tlv_fields!(writer, {
1215                                         (0, payment_hash, required),
1216                                         (1, receiver_node_id, option),
1217                                         (2, payment_secret, option),
1218                                         (3, via_channel_id, option),
1219                                         (4, amount_msat, required),
1220                                         (5, via_user_channel_id, option),
1221                                         // Type 6 was `user_payment_id` on 0.0.103 and earlier
1222                                         (7, claim_deadline, option),
1223                                         (8, payment_preimage, option),
1224                                         (9, onion_fields, option),
1225                                         (10, skimmed_fee_opt, option),
1226                                         (11, payment_context, option),
1227                                 });
1228                         },
1229                         &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
1230                                 2u8.write(writer)?;
1231                                 write_tlv_fields!(writer, {
1232                                         (0, payment_preimage, required),
1233                                         (1, payment_hash, required),
1234                                         (3, payment_id, option),
1235                                         (5, fee_paid_msat, option),
1236                                 });
1237                         },
1238                         &Event::PaymentPathFailed {
1239                                 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
1240                                 ref path, ref short_channel_id,
1241                                 #[cfg(test)]
1242                                 ref error_code,
1243                                 #[cfg(test)]
1244                                 ref error_data,
1245                         } => {
1246                                 3u8.write(writer)?;
1247                                 #[cfg(test)]
1248                                 error_code.write(writer)?;
1249                                 #[cfg(test)]
1250                                 error_data.write(writer)?;
1251                                 write_tlv_fields!(writer, {
1252                                         (0, payment_hash, required),
1253                                         (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
1254                                         (2, payment_failed_permanently, required),
1255                                         (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
1256                                         (4, path.blinded_tail, option),
1257                                         (5, path.hops, required_vec),
1258                                         (7, short_channel_id, option),
1259                                         (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
1260                                         (11, payment_id, option),
1261                                         (13, failure, required),
1262                                 });
1263                         },
1264                         &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
1265                                 4u8.write(writer)?;
1266                                 // Note that we now ignore these on the read end as we'll re-generate them in
1267                                 // ChannelManager, we write them here only for backwards compatibility.
1268                         },
1269                         &Event::SpendableOutputs { ref outputs, channel_id } => {
1270                                 5u8.write(writer)?;
1271                                 write_tlv_fields!(writer, {
1272                                         (0, WithoutLength(outputs), required),
1273                                         (1, channel_id, option),
1274                                 });
1275                         },
1276                         &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1277                                 6u8.write(writer)?;
1278                                 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1279                                 write_tlv_fields!(writer, {
1280                                         (0, intercept_id, required),
1281                                         (2, intercept_scid, required),
1282                                         (4, payment_hash, required),
1283                                         (6, inbound_amount_msat, required),
1284                                         (8, expected_outbound_amount_msat, required),
1285                                 });
1286                         }
1287                         &Event::PaymentForwarded {
1288                                 prev_channel_id, next_channel_id, prev_user_channel_id, next_user_channel_id,
1289                                 total_fee_earned_msat, skimmed_fee_msat, claim_from_onchain_tx,
1290                                 outbound_amount_forwarded_msat,
1291                         } => {
1292                                 7u8.write(writer)?;
1293                                 write_tlv_fields!(writer, {
1294                                         (0, total_fee_earned_msat, option),
1295                                         (1, prev_channel_id, option),
1296                                         (2, claim_from_onchain_tx, required),
1297                                         (3, next_channel_id, option),
1298                                         (5, outbound_amount_forwarded_msat, option),
1299                                         (7, skimmed_fee_msat, option),
1300                                         (9, prev_user_channel_id, option),
1301                                         (11, next_user_channel_id, option),
1302                                 });
1303                         },
1304                         &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason,
1305                                 ref counterparty_node_id, ref channel_capacity_sats, ref channel_funding_txo
1306                         } => {
1307                                 9u8.write(writer)?;
1308                                 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1309                                 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1310                                 // separate u64 values.
1311                                 let user_channel_id_low = *user_channel_id as u64;
1312                                 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1313                                 write_tlv_fields!(writer, {
1314                                         (0, channel_id, required),
1315                                         (1, user_channel_id_low, required),
1316                                         (2, reason, required),
1317                                         (3, user_channel_id_high, required),
1318                                         (5, counterparty_node_id, option),
1319                                         (7, channel_capacity_sats, option),
1320                                         (9, channel_funding_txo, option),
1321                                 });
1322                         },
1323                         &Event::DiscardFunding { ref channel_id, ref transaction } => {
1324                                 11u8.write(writer)?;
1325                                 write_tlv_fields!(writer, {
1326                                         (0, channel_id, required),
1327                                         (2, transaction, required)
1328                                 })
1329                         },
1330                         &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1331                                 13u8.write(writer)?;
1332                                 write_tlv_fields!(writer, {
1333                                         (0, payment_id, required),
1334                                         (2, payment_hash, option),
1335                                         (4, path.hops, required_vec),
1336                                         (6, path.blinded_tail, option),
1337                                 })
1338                         },
1339                         &Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
1340                                 15u8.write(writer)?;
1341                                 write_tlv_fields!(writer, {
1342                                         (0, payment_id, required),
1343                                         (1, reason, option),
1344                                         (2, payment_hash, required),
1345                                 })
1346                         },
1347                         &Event::OpenChannelRequest { .. } => {
1348                                 17u8.write(writer)?;
1349                                 // We never write the OpenChannelRequest events as, upon disconnection, peers
1350                                 // drop any channels which have not yet exchanged funding_signed.
1351                         },
1352                         &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref htlcs, ref sender_intended_total_msat } => {
1353                                 19u8.write(writer)?;
1354                                 write_tlv_fields!(writer, {
1355                                         (0, payment_hash, required),
1356                                         (1, receiver_node_id, option),
1357                                         (2, purpose, required),
1358                                         (4, amount_msat, required),
1359                                         (5, *htlcs, optional_vec),
1360                                         (7, sender_intended_total_msat, option),
1361                                 });
1362                         },
1363                         &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1364                                 21u8.write(writer)?;
1365                                 write_tlv_fields!(writer, {
1366                                         (0, payment_id, required),
1367                                         (2, payment_hash, required),
1368                                         (4, path.hops, required_vec),
1369                                         (6, path.blinded_tail, option),
1370                                 })
1371                         },
1372                         &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1373                                 23u8.write(writer)?;
1374                                 write_tlv_fields!(writer, {
1375                                         (0, payment_id, required),
1376                                         (2, payment_hash, required),
1377                                         (4, path.hops, required_vec),
1378                                         (6, short_channel_id, option),
1379                                         (8, path.blinded_tail, option),
1380                                 })
1381                         },
1382                         &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1383                                 25u8.write(writer)?;
1384                                 write_tlv_fields!(writer, {
1385                                         (0, prev_channel_id, required),
1386                                         (2, failed_next_destination, required),
1387                                 })
1388                         },
1389                         &Event::BumpTransaction(ref event)=> {
1390                                 27u8.write(writer)?;
1391                                 match event {
1392                                         // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1393                                         // upon restarting anyway if they remain unresolved.
1394                                         BumpTransactionEvent::ChannelClose { .. } => {}
1395                                         BumpTransactionEvent::HTLCResolution { .. } => {}
1396                                 }
1397                                 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1398                         }
1399                         &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1400                                 29u8.write(writer)?;
1401                                 write_tlv_fields!(writer, {
1402                                         (0, channel_id, required),
1403                                         (2, user_channel_id, required),
1404                                         (4, counterparty_node_id, required),
1405                                         (6, channel_type, required),
1406                                 });
1407                         },
1408                         &Event::ChannelPending { ref channel_id, ref user_channel_id,
1409                                 ref former_temporary_channel_id, ref counterparty_node_id, ref funding_txo,
1410                                 ref channel_type
1411                         } => {
1412                                 31u8.write(writer)?;
1413                                 write_tlv_fields!(writer, {
1414                                         (0, channel_id, required),
1415                                         (1, channel_type, option),
1416                                         (2, user_channel_id, required),
1417                                         (4, former_temporary_channel_id, required),
1418                                         (6, counterparty_node_id, required),
1419                                         (8, funding_txo, required),
1420                                 });
1421                         },
1422                         &Event::InvoiceRequestFailed { ref payment_id } => {
1423                                 33u8.write(writer)?;
1424                                 write_tlv_fields!(writer, {
1425                                         (0, payment_id, required),
1426                                 })
1427                         },
1428                         &Event::ConnectionNeeded { .. } => {
1429                                 35u8.write(writer)?;
1430                                 // Never write ConnectionNeeded events as buffered onion messages aren't serialized.
1431                         },
1432                         &Event::OnionMessageIntercepted { ref peer_node_id, ref message } => {
1433                                 37u8.write(writer)?;
1434                                 write_tlv_fields!(writer, {
1435                                         (0, peer_node_id, required),
1436                                         (2, message, required),
1437                                 });
1438                         },
1439                         &Event::OnionMessagePeerConnected { ref peer_node_id } => {
1440                                 39u8.write(writer)?;
1441                                 write_tlv_fields!(writer, {
1442                                         (0, peer_node_id, required),
1443                                 });
1444                         }
1445                         // Note that, going forward, all new events must only write data inside of
1446                         // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1447                         // data via `write_tlv_fields`.
1448                 }
1449                 Ok(())
1450         }
1451 }
1452 impl MaybeReadable for Event {
1453         fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1454                 match Readable::read(reader)? {
1455                         // Note that we do not write a length-prefixed TLV for FundingGenerationReady events.
1456                         0u8 => Ok(None),
1457                         1u8 => {
1458                                 let mut f = || {
1459                                         let mut payment_hash = PaymentHash([0; 32]);
1460                                         let mut payment_preimage = None;
1461                                         let mut payment_secret = None;
1462                                         let mut amount_msat = 0;
1463                                         let mut counterparty_skimmed_fee_msat_opt = None;
1464                                         let mut receiver_node_id = None;
1465                                         let mut _user_payment_id = None::<u64>; // Used in 0.0.103 and earlier, no longer written in 0.0.116+.
1466                                         let mut via_channel_id = None;
1467                                         let mut claim_deadline = None;
1468                                         let mut via_user_channel_id = None;
1469                                         let mut onion_fields = None;
1470                                         let mut payment_context = None;
1471                                         read_tlv_fields!(reader, {
1472                                                 (0, payment_hash, required),
1473                                                 (1, receiver_node_id, option),
1474                                                 (2, payment_secret, option),
1475                                                 (3, via_channel_id, option),
1476                                                 (4, amount_msat, required),
1477                                                 (5, via_user_channel_id, option),
1478                                                 (6, _user_payment_id, option),
1479                                                 (7, claim_deadline, option),
1480                                                 (8, payment_preimage, option),
1481                                                 (9, onion_fields, option),
1482                                                 (10, counterparty_skimmed_fee_msat_opt, option),
1483                                                 (11, payment_context, option),
1484                                         });
1485                                         let purpose = match payment_secret {
1486                                                 Some(secret) => PaymentPurpose::from_parts(payment_preimage, secret, payment_context),
1487                                                 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1488                                                 None => return Err(msgs::DecodeError::InvalidValue),
1489                                         };
1490                                         Ok(Some(Event::PaymentClaimable {
1491                                                 receiver_node_id,
1492                                                 payment_hash,
1493                                                 amount_msat,
1494                                                 counterparty_skimmed_fee_msat: counterparty_skimmed_fee_msat_opt.unwrap_or(0),
1495                                                 purpose,
1496                                                 via_channel_id,
1497                                                 via_user_channel_id,
1498                                                 claim_deadline,
1499                                                 onion_fields,
1500                                         }))
1501                                 };
1502                                 f()
1503                         },
1504                         2u8 => {
1505                                 let mut f = || {
1506                                         let mut payment_preimage = PaymentPreimage([0; 32]);
1507                                         let mut payment_hash = None;
1508                                         let mut payment_id = None;
1509                                         let mut fee_paid_msat = None;
1510                                         read_tlv_fields!(reader, {
1511                                                 (0, payment_preimage, required),
1512                                                 (1, payment_hash, option),
1513                                                 (3, payment_id, option),
1514                                                 (5, fee_paid_msat, option),
1515                                         });
1516                                         if payment_hash.is_none() {
1517                                                 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()));
1518                                         }
1519                                         Ok(Some(Event::PaymentSent {
1520                                                 payment_id,
1521                                                 payment_preimage,
1522                                                 payment_hash: payment_hash.unwrap(),
1523                                                 fee_paid_msat,
1524                                         }))
1525                                 };
1526                                 f()
1527                         },
1528                         3u8 => {
1529                                 let mut f = || {
1530                                         #[cfg(test)]
1531                                         let error_code = Readable::read(reader)?;
1532                                         #[cfg(test)]
1533                                         let error_data = Readable::read(reader)?;
1534                                         let mut payment_hash = PaymentHash([0; 32]);
1535                                         let mut payment_failed_permanently = false;
1536                                         let mut network_update = None;
1537                                         let mut blinded_tail: Option<BlindedTail> = None;
1538                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1539                                         let mut short_channel_id = None;
1540                                         let mut payment_id = None;
1541                                         let mut failure_opt = None;
1542                                         read_tlv_fields!(reader, {
1543                                                 (0, payment_hash, required),
1544                                                 (1, network_update, upgradable_option),
1545                                                 (2, payment_failed_permanently, required),
1546                                                 (4, blinded_tail, option),
1547                                                 // Added as a part of LDK 0.0.101 and always filled in since.
1548                                                 // Defaults to an empty Vec, though likely should have been `Option`al.
1549                                                 (5, path, optional_vec),
1550                                                 (7, short_channel_id, option),
1551                                                 (11, payment_id, option),
1552                                                 (13, failure_opt, upgradable_option),
1553                                         });
1554                                         let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1555                                         Ok(Some(Event::PaymentPathFailed {
1556                                                 payment_id,
1557                                                 payment_hash,
1558                                                 payment_failed_permanently,
1559                                                 failure,
1560                                                 path: Path { hops: path.unwrap(), blinded_tail },
1561                                                 short_channel_id,
1562                                                 #[cfg(test)]
1563                                                 error_code,
1564                                                 #[cfg(test)]
1565                                                 error_data,
1566                                         }))
1567                                 };
1568                                 f()
1569                         },
1570                         4u8 => Ok(None),
1571                         5u8 => {
1572                                 let mut f = || {
1573                                         let mut outputs = WithoutLength(Vec::new());
1574                                         let mut channel_id: Option<ChannelId> = None;
1575                                         read_tlv_fields!(reader, {
1576                                                 (0, outputs, required),
1577                                                 (1, channel_id, option),
1578                                         });
1579                                         Ok(Some(Event::SpendableOutputs { outputs: outputs.0, channel_id }))
1580                                 };
1581                                 f()
1582                         },
1583                         6u8 => {
1584                                 let mut payment_hash = PaymentHash([0; 32]);
1585                                 let mut intercept_id = InterceptId([0; 32]);
1586                                 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1587                                 let mut inbound_amount_msat = 0;
1588                                 let mut expected_outbound_amount_msat = 0;
1589                                 read_tlv_fields!(reader, {
1590                                         (0, intercept_id, required),
1591                                         (2, requested_next_hop_scid, required),
1592                                         (4, payment_hash, required),
1593                                         (6, inbound_amount_msat, required),
1594                                         (8, expected_outbound_amount_msat, required),
1595                                 });
1596                                 let next_scid = match requested_next_hop_scid {
1597                                         InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1598                                 };
1599                                 Ok(Some(Event::HTLCIntercepted {
1600                                         payment_hash,
1601                                         requested_next_hop_scid: next_scid,
1602                                         inbound_amount_msat,
1603                                         expected_outbound_amount_msat,
1604                                         intercept_id,
1605                                 }))
1606                         },
1607                         7u8 => {
1608                                 let mut f = || {
1609                                         let mut prev_channel_id = None;
1610                                         let mut next_channel_id = None;
1611                                         let mut prev_user_channel_id = None;
1612                                         let mut next_user_channel_id = None;
1613                                         let mut total_fee_earned_msat = None;
1614                                         let mut skimmed_fee_msat = None;
1615                                         let mut claim_from_onchain_tx = false;
1616                                         let mut outbound_amount_forwarded_msat = None;
1617                                         read_tlv_fields!(reader, {
1618                                                 (0, total_fee_earned_msat, option),
1619                                                 (1, prev_channel_id, option),
1620                                                 (2, claim_from_onchain_tx, required),
1621                                                 (3, next_channel_id, option),
1622                                                 (5, outbound_amount_forwarded_msat, option),
1623                                                 (7, skimmed_fee_msat, option),
1624                                                 (9, prev_user_channel_id, option),
1625                                                 (11, next_user_channel_id, option),
1626                                         });
1627                                         Ok(Some(Event::PaymentForwarded {
1628                                                 prev_channel_id, next_channel_id, prev_user_channel_id,
1629                                                 next_user_channel_id, total_fee_earned_msat, skimmed_fee_msat,
1630                                                 claim_from_onchain_tx, outbound_amount_forwarded_msat,
1631                                         }))
1632                                 };
1633                                 f()
1634                         },
1635                         9u8 => {
1636                                 let mut f = || {
1637                                         let mut channel_id = ChannelId::new_zero();
1638                                         let mut reason = UpgradableRequired(None);
1639                                         let mut user_channel_id_low_opt: Option<u64> = None;
1640                                         let mut user_channel_id_high_opt: Option<u64> = None;
1641                                         let mut counterparty_node_id = None;
1642                                         let mut channel_capacity_sats = None;
1643                                         let mut channel_funding_txo = None;
1644                                         read_tlv_fields!(reader, {
1645                                                 (0, channel_id, required),
1646                                                 (1, user_channel_id_low_opt, option),
1647                                                 (2, reason, upgradable_required),
1648                                                 (3, user_channel_id_high_opt, option),
1649                                                 (5, counterparty_node_id, option),
1650                                                 (7, channel_capacity_sats, option),
1651                                                 (9, channel_funding_txo, option),
1652                                         });
1653
1654                                         // `user_channel_id` used to be a single u64 value. In order to remain
1655                                         // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1656                                         // as two separate u64 values.
1657                                         let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1658                                                 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1659
1660                                         Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required),
1661                                                 counterparty_node_id, channel_capacity_sats, channel_funding_txo }))
1662                                 };
1663                                 f()
1664                         },
1665                         11u8 => {
1666                                 let mut f = || {
1667                                         let mut channel_id = ChannelId::new_zero();
1668                                         let mut transaction = Transaction{ version: Version::TWO, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
1669                                         read_tlv_fields!(reader, {
1670                                                 (0, channel_id, required),
1671                                                 (2, transaction, required),
1672                                         });
1673                                         Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1674                                 };
1675                                 f()
1676                         },
1677                         13u8 => {
1678                                 let mut f = || {
1679                                         _init_and_read_len_prefixed_tlv_fields!(reader, {
1680                                                 (0, payment_id, required),
1681                                                 (2, payment_hash, option),
1682                                                 (4, path, required_vec),
1683                                                 (6, blinded_tail, option),
1684                                         });
1685                                         Ok(Some(Event::PaymentPathSuccessful {
1686                                                 payment_id: payment_id.0.unwrap(),
1687                                                 payment_hash,
1688                                                 path: Path { hops: path, blinded_tail },
1689                                         }))
1690                                 };
1691                                 f()
1692                         },
1693                         15u8 => {
1694                                 let mut f = || {
1695                                         let mut payment_hash = PaymentHash([0; 32]);
1696                                         let mut payment_id = PaymentId([0; 32]);
1697                                         let mut reason = None;
1698                                         read_tlv_fields!(reader, {
1699                                                 (0, payment_id, required),
1700                                                 (1, reason, upgradable_option),
1701                                                 (2, payment_hash, required),
1702                                         });
1703                                         Ok(Some(Event::PaymentFailed {
1704                                                 payment_id,
1705                                                 payment_hash,
1706                                                 reason,
1707                                         }))
1708                                 };
1709                                 f()
1710                         },
1711                         17u8 => {
1712                                 // Value 17 is used for `Event::OpenChannelRequest`.
1713                                 Ok(None)
1714                         },
1715                         19u8 => {
1716                                 let mut f = || {
1717                                         let mut payment_hash = PaymentHash([0; 32]);
1718                                         let mut purpose = UpgradableRequired(None);
1719                                         let mut amount_msat = 0;
1720                                         let mut receiver_node_id = None;
1721                                         let mut htlcs: Option<Vec<ClaimedHTLC>> = Some(vec![]);
1722                                         let mut sender_intended_total_msat: Option<u64> = None;
1723                                         read_tlv_fields!(reader, {
1724                                                 (0, payment_hash, required),
1725                                                 (1, receiver_node_id, option),
1726                                                 (2, purpose, upgradable_required),
1727                                                 (4, amount_msat, required),
1728                                                 (5, htlcs, optional_vec),
1729                                                 (7, sender_intended_total_msat, option),
1730                                         });
1731                                         Ok(Some(Event::PaymentClaimed {
1732                                                 receiver_node_id,
1733                                                 payment_hash,
1734                                                 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1735                                                 amount_msat,
1736                                                 htlcs: htlcs.unwrap_or(vec![]),
1737                                                 sender_intended_total_msat,
1738                                         }))
1739                                 };
1740                                 f()
1741                         },
1742                         21u8 => {
1743                                 let mut f = || {
1744                                         _init_and_read_len_prefixed_tlv_fields!(reader, {
1745                                                 (0, payment_id, required),
1746                                                 (2, payment_hash, required),
1747                                                 (4, path, required_vec),
1748                                                 (6, blinded_tail, option),
1749                                         });
1750                                         Ok(Some(Event::ProbeSuccessful {
1751                                                 payment_id: payment_id.0.unwrap(),
1752                                                 payment_hash: payment_hash.0.unwrap(),
1753                                                 path: Path { hops: path, blinded_tail },
1754                                         }))
1755                                 };
1756                                 f()
1757                         },
1758                         23u8 => {
1759                                 let mut f = || {
1760                                         _init_and_read_len_prefixed_tlv_fields!(reader, {
1761                                                 (0, payment_id, required),
1762                                                 (2, payment_hash, required),
1763                                                 (4, path, required_vec),
1764                                                 (6, short_channel_id, option),
1765                                                 (8, blinded_tail, option),
1766                                         });
1767                                         Ok(Some(Event::ProbeFailed {
1768                                                 payment_id: payment_id.0.unwrap(),
1769                                                 payment_hash: payment_hash.0.unwrap(),
1770                                                 path: Path { hops: path, blinded_tail },
1771                                                 short_channel_id,
1772                                         }))
1773                                 };
1774                                 f()
1775                         },
1776                         25u8 => {
1777                                 let mut f = || {
1778                                         let mut prev_channel_id = ChannelId::new_zero();
1779                                         let mut failed_next_destination_opt = UpgradableRequired(None);
1780                                         read_tlv_fields!(reader, {
1781                                                 (0, prev_channel_id, required),
1782                                                 (2, failed_next_destination_opt, upgradable_required),
1783                                         });
1784                                         Ok(Some(Event::HTLCHandlingFailed {
1785                                                 prev_channel_id,
1786                                                 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1787                                         }))
1788                                 };
1789                                 f()
1790                         },
1791                         27u8 => Ok(None),
1792                         29u8 => {
1793                                 let mut f = || {
1794                                         let mut channel_id = ChannelId::new_zero();
1795                                         let mut user_channel_id: u128 = 0;
1796                                         let mut counterparty_node_id = RequiredWrapper(None);
1797                                         let mut channel_type = RequiredWrapper(None);
1798                                         read_tlv_fields!(reader, {
1799                                                 (0, channel_id, required),
1800                                                 (2, user_channel_id, required),
1801                                                 (4, counterparty_node_id, required),
1802                                                 (6, channel_type, required),
1803                                         });
1804
1805                                         Ok(Some(Event::ChannelReady {
1806                                                 channel_id,
1807                                                 user_channel_id,
1808                                                 counterparty_node_id: counterparty_node_id.0.unwrap(),
1809                                                 channel_type: channel_type.0.unwrap()
1810                                         }))
1811                                 };
1812                                 f()
1813                         },
1814                         31u8 => {
1815                                 let mut f = || {
1816                                         let mut channel_id = ChannelId::new_zero();
1817                                         let mut user_channel_id: u128 = 0;
1818                                         let mut former_temporary_channel_id = None;
1819                                         let mut counterparty_node_id = RequiredWrapper(None);
1820                                         let mut funding_txo = RequiredWrapper(None);
1821                                         let mut channel_type = None;
1822                                         read_tlv_fields!(reader, {
1823                                                 (0, channel_id, required),
1824                                                 (1, channel_type, option),
1825                                                 (2, user_channel_id, required),
1826                                                 (4, former_temporary_channel_id, required),
1827                                                 (6, counterparty_node_id, required),
1828                                                 (8, funding_txo, required),
1829                                         });
1830
1831                                         Ok(Some(Event::ChannelPending {
1832                                                 channel_id,
1833                                                 user_channel_id,
1834                                                 former_temporary_channel_id,
1835                                                 counterparty_node_id: counterparty_node_id.0.unwrap(),
1836                                                 funding_txo: funding_txo.0.unwrap(),
1837                                                 channel_type,
1838                                         }))
1839                                 };
1840                                 f()
1841                         },
1842                         33u8 => {
1843                                 let mut f = || {
1844                                         _init_and_read_len_prefixed_tlv_fields!(reader, {
1845                                                 (0, payment_id, required),
1846                                         });
1847                                         Ok(Some(Event::InvoiceRequestFailed {
1848                                                 payment_id: payment_id.0.unwrap(),
1849                                         }))
1850                                 };
1851                                 f()
1852                         },
1853                         // Note that we do not write a length-prefixed TLV for ConnectionNeeded events.
1854                         35u8 => Ok(None),
1855                         37u8 => {
1856                                 let mut f = || {
1857                                         _init_and_read_len_prefixed_tlv_fields!(reader, {
1858                                                 (0, peer_node_id, required),
1859                                                 (2, message, required),
1860                                         });
1861                                         Ok(Some(Event::OnionMessageIntercepted {
1862                                                 peer_node_id: peer_node_id.0.unwrap(), message: message.0.unwrap()
1863                                         }))
1864                                 };
1865                                 f()
1866                         },
1867                         39u8 => {
1868                                 let mut f = || {
1869                                         _init_and_read_len_prefixed_tlv_fields!(reader, {
1870                                                 (0, peer_node_id, required),
1871                                         });
1872                                         Ok(Some(Event::OnionMessagePeerConnected {
1873                                                 peer_node_id: peer_node_id.0.unwrap()
1874                                         }))
1875                                 };
1876                                 f()
1877                         },
1878                         // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1879                         // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1880                         // reads.
1881                         x if x % 2 == 1 => {
1882                                 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1883                                 // which prefixes the whole thing with a length BigSize. Because the event is
1884                                 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1885                                 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1886                                 // exactly the number of bytes specified, ignoring them entirely.
1887                                 let tlv_len: BigSize = Readable::read(reader)?;
1888                                 FixedLengthReader::new(reader, tlv_len.0)
1889                                         .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1890                                 Ok(None)
1891                         },
1892                         _ => Err(msgs::DecodeError::InvalidValue)
1893                 }
1894         }
1895 }
1896
1897 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1898 /// broadcast to most peers).
1899 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1900 #[derive(Clone, Debug)]
1901 #[cfg_attr(test, derive(PartialEq))]
1902 pub enum MessageSendEvent {
1903         /// Used to indicate that we've accepted a channel open and should send the accept_channel
1904         /// message provided to the given peer.
1905         SendAcceptChannel {
1906                 /// The node_id of the node which should receive this message
1907                 node_id: PublicKey,
1908                 /// The message which should be sent.
1909                 msg: msgs::AcceptChannel,
1910         },
1911         /// Used to indicate that we've accepted a V2 channel open and should send the accept_channel2
1912         /// message provided to the given peer.
1913         SendAcceptChannelV2 {
1914                 /// The node_id of the node which should receive this message
1915                 node_id: PublicKey,
1916                 /// The message which should be sent.
1917                 msg: msgs::AcceptChannelV2,
1918         },
1919         /// Used to indicate that we've initiated a channel open and should send the open_channel
1920         /// message provided to the given peer.
1921         SendOpenChannel {
1922                 /// The node_id of the node which should receive this message
1923                 node_id: PublicKey,
1924                 /// The message which should be sent.
1925                 msg: msgs::OpenChannel,
1926         },
1927         /// Used to indicate that we've initiated a V2 channel open and should send the open_channel2
1928         /// message provided to the given peer.
1929         SendOpenChannelV2 {
1930                 /// The node_id of the node which should receive this message
1931                 node_id: PublicKey,
1932                 /// The message which should be sent.
1933                 msg: msgs::OpenChannelV2,
1934         },
1935         /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1936         SendFundingCreated {
1937                 /// The node_id of the node which should receive this message
1938                 node_id: PublicKey,
1939                 /// The message which should be sent.
1940                 msg: msgs::FundingCreated,
1941         },
1942         /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1943         SendFundingSigned {
1944                 /// The node_id of the node which should receive this message
1945                 node_id: PublicKey,
1946                 /// The message which should be sent.
1947                 msg: msgs::FundingSigned,
1948         },
1949         /// Used to indicate that a stfu message should be sent to the peer with the given node id.
1950         SendStfu {
1951                 /// The node_id of the node which should receive this message
1952                 node_id: PublicKey,
1953                 /// The message which should be sent.
1954                 msg: msgs::Stfu,
1955         },
1956         /// Used to indicate that a splice message should be sent to the peer with the given node id.
1957         SendSplice {
1958                 /// The node_id of the node which should receive this message
1959                 node_id: PublicKey,
1960                 /// The message which should be sent.
1961                 msg: msgs::Splice,
1962         },
1963         /// Used to indicate that a splice_ack message should be sent to the peer with the given node id.
1964         SendSpliceAck {
1965                 /// The node_id of the node which should receive this message
1966                 node_id: PublicKey,
1967                 /// The message which should be sent.
1968                 msg: msgs::SpliceAck,
1969         },
1970         /// Used to indicate that a splice_locked message should be sent to the peer with the given node id.
1971         SendSpliceLocked {
1972                 /// The node_id of the node which should receive this message
1973                 node_id: PublicKey,
1974                 /// The message which should be sent.
1975                 msg: msgs::SpliceLocked,
1976         },
1977         /// Used to indicate that a tx_add_input message should be sent to the peer with the given node_id.
1978         SendTxAddInput {
1979                 /// The node_id of the node which should receive this message
1980                 node_id: PublicKey,
1981                 /// The message which should be sent.
1982                 msg: msgs::TxAddInput,
1983         },
1984         /// Used to indicate that a tx_add_output message should be sent to the peer with the given node_id.
1985         SendTxAddOutput {
1986                 /// The node_id of the node which should receive this message
1987                 node_id: PublicKey,
1988                 /// The message which should be sent.
1989                 msg: msgs::TxAddOutput,
1990         },
1991         /// Used to indicate that a tx_remove_input message should be sent to the peer with the given node_id.
1992         SendTxRemoveInput {
1993                 /// The node_id of the node which should receive this message
1994                 node_id: PublicKey,
1995                 /// The message which should be sent.
1996                 msg: msgs::TxRemoveInput,
1997         },
1998         /// Used to indicate that a tx_remove_output message should be sent to the peer with the given node_id.
1999         SendTxRemoveOutput {
2000                 /// The node_id of the node which should receive this message
2001                 node_id: PublicKey,
2002                 /// The message which should be sent.
2003                 msg: msgs::TxRemoveOutput,
2004         },
2005         /// Used to indicate that a tx_complete message should be sent to the peer with the given node_id.
2006         SendTxComplete {
2007                 /// The node_id of the node which should receive this message
2008                 node_id: PublicKey,
2009                 /// The message which should be sent.
2010                 msg: msgs::TxComplete,
2011         },
2012         /// Used to indicate that a tx_signatures message should be sent to the peer with the given node_id.
2013         SendTxSignatures {
2014                 /// The node_id of the node which should receive this message
2015                 node_id: PublicKey,
2016                 /// The message which should be sent.
2017                 msg: msgs::TxSignatures,
2018         },
2019         /// Used to indicate that a tx_init_rbf message should be sent to the peer with the given node_id.
2020         SendTxInitRbf {
2021                 /// The node_id of the node which should receive this message
2022                 node_id: PublicKey,
2023                 /// The message which should be sent.
2024                 msg: msgs::TxInitRbf,
2025         },
2026         /// Used to indicate that a tx_ack_rbf message should be sent to the peer with the given node_id.
2027         SendTxAckRbf {
2028                 /// The node_id of the node which should receive this message
2029                 node_id: PublicKey,
2030                 /// The message which should be sent.
2031                 msg: msgs::TxAckRbf,
2032         },
2033         /// Used to indicate that a tx_abort message should be sent to the peer with the given node_id.
2034         SendTxAbort {
2035                 /// The node_id of the node which should receive this message
2036                 node_id: PublicKey,
2037                 /// The message which should be sent.
2038                 msg: msgs::TxAbort,
2039         },
2040         /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
2041         SendChannelReady {
2042                 /// The node_id of the node which should receive these message(s)
2043                 node_id: PublicKey,
2044                 /// The channel_ready message which should be sent.
2045                 msg: msgs::ChannelReady,
2046         },
2047         /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
2048         SendAnnouncementSignatures {
2049                 /// The node_id of the node which should receive these message(s)
2050                 node_id: PublicKey,
2051                 /// The announcement_signatures message which should be sent.
2052                 msg: msgs::AnnouncementSignatures,
2053         },
2054         /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
2055         /// message should be sent to the peer with the given node_id.
2056         UpdateHTLCs {
2057                 /// The node_id of the node which should receive these message(s)
2058                 node_id: PublicKey,
2059                 /// The update messages which should be sent. ALL messages in the struct should be sent!
2060                 updates: msgs::CommitmentUpdate,
2061         },
2062         /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
2063         SendRevokeAndACK {
2064                 /// The node_id of the node which should receive this message
2065                 node_id: PublicKey,
2066                 /// The message which should be sent.
2067                 msg: msgs::RevokeAndACK,
2068         },
2069         /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
2070         SendClosingSigned {
2071                 /// The node_id of the node which should receive this message
2072                 node_id: PublicKey,
2073                 /// The message which should be sent.
2074                 msg: msgs::ClosingSigned,
2075         },
2076         /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
2077         SendShutdown {
2078                 /// The node_id of the node which should receive this message
2079                 node_id: PublicKey,
2080                 /// The message which should be sent.
2081                 msg: msgs::Shutdown,
2082         },
2083         /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
2084         SendChannelReestablish {
2085                 /// The node_id of the node which should receive this message
2086                 node_id: PublicKey,
2087                 /// The message which should be sent.
2088                 msg: msgs::ChannelReestablish,
2089         },
2090         /// Used to send a channel_announcement and channel_update to a specific peer, likely on
2091         /// initial connection to ensure our peers know about our channels.
2092         SendChannelAnnouncement {
2093                 /// The node_id of the node which should receive this message
2094                 node_id: PublicKey,
2095                 /// The channel_announcement which should be sent.
2096                 msg: msgs::ChannelAnnouncement,
2097                 /// The followup channel_update which should be sent.
2098                 update_msg: msgs::ChannelUpdate,
2099         },
2100         /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
2101         /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
2102         ///
2103         /// Note that after doing so, you very likely (unless you did so very recently) want to
2104         /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
2105         /// ensures that any nodes which see our channel_announcement also have a relevant
2106         /// node_announcement, including relevant feature flags which may be important for routing
2107         /// through or to us.
2108         ///
2109         /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
2110         BroadcastChannelAnnouncement {
2111                 /// The channel_announcement which should be sent.
2112                 msg: msgs::ChannelAnnouncement,
2113                 /// The followup channel_update which should be sent.
2114                 update_msg: Option<msgs::ChannelUpdate>,
2115         },
2116         /// Used to indicate that a channel_update should be broadcast to all peers.
2117         BroadcastChannelUpdate {
2118                 /// The channel_update which should be sent.
2119                 msg: msgs::ChannelUpdate,
2120         },
2121         /// Used to indicate that a node_announcement should be broadcast to all peers.
2122         BroadcastNodeAnnouncement {
2123                 /// The node_announcement which should be sent.
2124                 msg: msgs::NodeAnnouncement,
2125         },
2126         /// Used to indicate that a channel_update should be sent to a single peer.
2127         /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
2128         /// private channel and we shouldn't be informing all of our peers of channel parameters.
2129         SendChannelUpdate {
2130                 /// The node_id of the node which should receive this message
2131                 node_id: PublicKey,
2132                 /// The channel_update which should be sent.
2133                 msg: msgs::ChannelUpdate,
2134         },
2135         /// Broadcast an error downstream to be handled
2136         HandleError {
2137                 /// The node_id of the node which should receive this message
2138                 node_id: PublicKey,
2139                 /// The action which should be taken.
2140                 action: msgs::ErrorAction
2141         },
2142         /// Query a peer for channels with funding transaction UTXOs in a block range.
2143         SendChannelRangeQuery {
2144                 /// The node_id of this message recipient
2145                 node_id: PublicKey,
2146                 /// The query_channel_range which should be sent.
2147                 msg: msgs::QueryChannelRange,
2148         },
2149         /// Request routing gossip messages from a peer for a list of channels identified by
2150         /// their short_channel_ids.
2151         SendShortIdsQuery {
2152                 /// The node_id of this message recipient
2153                 node_id: PublicKey,
2154                 /// The query_short_channel_ids which should be sent.
2155                 msg: msgs::QueryShortChannelIds,
2156         },
2157         /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
2158         /// emitted during processing of the query.
2159         SendReplyChannelRange {
2160                 /// The node_id of this message recipient
2161                 node_id: PublicKey,
2162                 /// The reply_channel_range which should be sent.
2163                 msg: msgs::ReplyChannelRange,
2164         },
2165         /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
2166         /// enable receiving gossip messages from the peer.
2167         SendGossipTimestampFilter {
2168                 /// The node_id of this message recipient
2169                 node_id: PublicKey,
2170                 /// The gossip_timestamp_filter which should be sent.
2171                 msg: msgs::GossipTimestampFilter,
2172         },
2173 }
2174
2175 /// A trait indicating an object may generate message send events
2176 pub trait MessageSendEventsProvider {
2177         /// Gets the list of pending events which were generated by previous actions, clearing the list
2178         /// in the process.
2179         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
2180 }
2181
2182 /// A trait indicating an object may generate events.
2183 ///
2184 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
2185 ///
2186 /// Implementations of this trait may also feature an async version of event handling, as shown with
2187 /// [`ChannelManager::process_pending_events_async`] and
2188 /// [`ChainMonitor::process_pending_events_async`].
2189 ///
2190 /// # Requirements
2191 ///
2192 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
2193 /// event since the last invocation.
2194 ///
2195 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
2196 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
2197 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
2198 /// relevant changes to disk *before* returning.
2199 ///
2200 /// Further, because an application may crash between an [`Event`] being handled and the
2201 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
2202 /// effect, [`Event`]s may be replayed.
2203 ///
2204 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
2205 /// consult the provider's documentation on the implication of processing events and how a handler
2206 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
2207 /// [`ChainMonitor::process_pending_events`]).
2208 ///
2209 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
2210 /// own type(s).
2211 ///
2212 /// [`process_pending_events`]: Self::process_pending_events
2213 /// [`handle_event`]: EventHandler::handle_event
2214 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
2215 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
2216 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
2217 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
2218 pub trait EventsProvider {
2219         /// Processes any events generated since the last call using the given event handler.
2220         ///
2221         /// See the trait-level documentation for requirements.
2222         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
2223 }
2224
2225 /// A trait implemented for objects handling events from [`EventsProvider`].
2226 ///
2227 /// An async variation also exists for implementations of [`EventsProvider`] that support async
2228 /// event handling. The async event handler should satisfy the generic bounds: `F:
2229 /// core::future::Future, H: Fn(Event) -> F`.
2230 pub trait EventHandler {
2231         /// Handles the given [`Event`].
2232         ///
2233         /// See [`EventsProvider`] for details that must be considered when implementing this method.
2234         fn handle_event(&self, event: Event);
2235 }
2236
2237 impl<F> EventHandler for F where F: Fn(Event) {
2238         fn handle_event(&self, event: Event) {
2239                 self(event)
2240         }
2241 }
2242
2243 impl<T: EventHandler> EventHandler for Arc<T> {
2244         fn handle_event(&self, event: Event) {
2245                 self.deref().handle_event(event)
2246         }
2247 }