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