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