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