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