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