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