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