Merge pull request #2136 from marctyndel/2023-03-paymentforwarded-expose-amount-forwarded
[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 #[cfg(anchors)]
18 pub mod bump_transaction;
19
20 #[cfg(anchors)]
21 pub use bump_transaction::BumpTransactionEvent;
22
23 use crate::chain::keysinterface::SpendableOutputDescriptor;
24 use crate::ln::channelmanager::{InterceptId, PaymentId};
25 use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
26 use crate::ln::features::ChannelTypeFeatures;
27 use crate::ln::msgs;
28 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
29 use crate::routing::gossip::NetworkUpdate;
30 use crate::util::errors::APIError;
31 use crate::util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, RequiredWrapper, UpgradableRequired, WithoutLength};
32 use crate::util::string::UntrustedString;
33 use crate::routing::router::{RouteHop, RouteParameters};
34
35 use bitcoin::{PackedLockTime, Transaction};
36 use bitcoin::blockdata::script::Script;
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_writeable_tlv_based_enum!(PaymentPurpose,
77         (0, InvoicePayment) => {
78                 (0, payment_preimage, option),
79                 (2, payment_secret, required),
80         };
81         (2, SpontaneousPayment)
82 );
83
84 /// When the payment path failure took place and extra details about it. [`PathFailure::OnPath`] may
85 /// contain a [`NetworkUpdate`] that needs to be applied to the [`NetworkGraph`].
86 ///
87 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
88 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
89 #[derive(Clone, Debug, Eq, PartialEq)]
90 pub enum PathFailure {
91         /// We failed to initially send the payment and no HTLC was committed to. Contains the relevant
92         /// error.
93         InitialSend {
94                 /// The error surfaced from initial send.
95                 err: APIError,
96         },
97         /// A hop on the path failed to forward our payment.
98         OnPath {
99                 /// If present, this [`NetworkUpdate`] should be applied to the [`NetworkGraph`] so that routing
100                 /// decisions can take into account the update.
101                 ///
102                 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
103                 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
104                 network_update: Option<NetworkUpdate>,
105         },
106 }
107
108 impl_writeable_tlv_based_enum_upgradable!(PathFailure,
109         (0, OnPath) => {
110                 (0, network_update, upgradable_option),
111         },
112         (2, InitialSend) => {
113                 (0, err, upgradable_required),
114         },
115 );
116
117 #[derive(Clone, Debug, PartialEq, Eq)]
118 /// The reason the channel was closed. See individual variants more details.
119 pub enum ClosureReason {
120         /// Closure generated from receiving a peer error message.
121         ///
122         /// Our counterparty may have broadcasted their latest commitment state, and we have
123         /// as well.
124         CounterpartyForceClosed {
125                 /// The error which the peer sent us.
126                 ///
127                 /// Be careful about printing the peer_msg, a well-crafted message could exploit
128                 /// a security vulnerability in the terminal emulator or the logging subsystem.
129                 /// To be safe, use `Display` on `UntrustedString`
130                 /// 
131                 /// [`UntrustedString`]: crate::util::string::UntrustedString
132                 peer_msg: UntrustedString,
133         },
134         /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
135         ///
136         /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
137         HolderForceClosed,
138         /// The channel was closed after negotiating a cooperative close and we've now broadcasted
139         /// the cooperative close transaction. Note the shutdown may have been initiated by us.
140         //TODO: split between CounterpartyInitiated/LocallyInitiated
141         CooperativeClosure,
142         /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
143         /// commitment transaction came from our counterparty, but it may also have come from
144         /// a copy of our own `ChannelMonitor`.
145         CommitmentTxConfirmed,
146         /// The funding transaction failed to confirm in a timely manner on an inbound channel.
147         FundingTimedOut,
148         /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
149         ProcessingError {
150                 /// A developer-readable error message which we generated.
151                 err: String,
152         },
153         /// The peer disconnected prior to funding completing. In this case the spec mandates that we
154         /// forget the channel entirely - we can attempt again if the peer reconnects.
155         ///
156         /// This includes cases where we restarted prior to funding completion, including prior to the
157         /// initial [`ChannelMonitor`] persistence completing.
158         ///
159         /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
160         /// peer because of mutual incompatibility between us and our channel counterparty.
161         ///
162         /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
163         DisconnectedPeer,
164         /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
165         /// the [`ChannelManager`] deserialized.
166         ///
167         /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
168         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
169         OutdatedChannelManager
170 }
171
172 impl core::fmt::Display for ClosureReason {
173         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
174                 f.write_str("Channel closed because ")?;
175                 match self {
176                         ClosureReason::CounterpartyForceClosed { peer_msg } => {
177                                 f.write_fmt(format_args!("counterparty force-closed with message: {}", peer_msg))
178                         },
179                         ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
180                         ClosureReason::CooperativeClosure => f.write_str("the channel was cooperatively closed"),
181                         ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
182                         ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
183                         ClosureReason::ProcessingError { err } => {
184                                 f.write_str("of an exception: ")?;
185                                 f.write_str(&err)
186                         },
187                         ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
188                         ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
189                 }
190         }
191 }
192
193 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
194         (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
195         (1, FundingTimedOut) => {},
196         (2, HolderForceClosed) => {},
197         (6, CommitmentTxConfirmed) => {},
198         (4, CooperativeClosure) => {},
199         (8, ProcessingError) => { (1, err, required) },
200         (10, DisconnectedPeer) => {},
201         (12, OutdatedChannelManager) => {},
202 );
203
204 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
205 #[derive(Clone, Debug, PartialEq, Eq)]
206 pub enum HTLCDestination {
207         /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
208         /// there is insufficient capacity in our outbound channel.
209         NextHopChannel {
210                 /// The `node_id` of the next node. For backwards compatibility, this field is
211                 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
212                 /// counterparty node information.
213                 node_id: Option<PublicKey>,
214                 /// The outgoing `channel_id` between us and the next node.
215                 channel_id: [u8; 32],
216         },
217         /// Scenario where we are unsure of the next node to forward the HTLC to.
218         UnknownNextHop {
219                 /// Short channel id we are requesting to forward an HTLC to.
220                 requested_forward_scid: u64,
221         },
222         /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
223         /// intercept HTLC.
224         InvalidForward {
225                 /// Short channel id we are requesting to forward an HTLC to.
226                 requested_forward_scid: u64
227         },
228         /// Failure scenario where an HTLC may have been forwarded to be intended for us,
229         /// but is invalid for some reason, so we reject it.
230         ///
231         /// Some of the reasons may include:
232         /// * HTLC Timeouts
233         /// * Expected MPP amount has already been reached
234         /// * Claimable amount does not match expected amount
235         FailedPayment {
236                 /// The payment hash of the payment we attempted to process.
237                 payment_hash: PaymentHash
238         },
239 }
240
241 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
242         (0, NextHopChannel) => {
243                 (0, node_id, required),
244                 (2, channel_id, required),
245         },
246         (1, InvalidForward) => {
247                 (0, requested_forward_scid, required),
248         },
249         (2, UnknownNextHop) => {
250                 (0, requested_forward_scid, required),
251         },
252         (4, FailedPayment) => {
253                 (0, payment_hash, required),
254         },
255 );
256
257 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
258 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
259 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
260 /// intercepts in upcoming work.
261 enum InterceptNextHop {
262         FakeScid {
263                 requested_next_hop_scid: u64,
264         },
265 }
266
267 impl_writeable_tlv_based_enum!(InterceptNextHop,
268         (0, FakeScid) => {
269                 (0, requested_next_hop_scid, required),
270         };
271 );
272
273 /// An Event which you should probably take some action in response to.
274 ///
275 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
276 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
277 /// written as it makes no sense to respond to it after reconnecting to peers).
278 #[derive(Clone, Debug, PartialEq, Eq)]
279 pub enum Event {
280         /// Used to indicate that the client should generate a funding transaction with the given
281         /// parameters and then call [`ChannelManager::funding_transaction_generated`].
282         /// Generated in [`ChannelManager`] message handling.
283         /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
284         /// counterparty can steal your funds!
285         ///
286         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
287         /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
288         FundingGenerationReady {
289                 /// The random channel_id we picked which you'll need to pass into
290                 /// [`ChannelManager::funding_transaction_generated`].
291                 ///
292                 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
293                 temporary_channel_id: [u8; 32],
294                 /// The counterparty's node_id, which you'll need to pass back into
295                 /// [`ChannelManager::funding_transaction_generated`].
296                 ///
297                 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
298                 counterparty_node_id: PublicKey,
299                 /// The value, in satoshis, that the output should have.
300                 channel_value_satoshis: u64,
301                 /// The script which should be used in the transaction output.
302                 output_script: Script,
303                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or a
304                 /// random value for an inbound channel. This may be zero for objects serialized with LDK
305                 /// versions prior to 0.0.113.
306                 ///
307                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
308                 user_channel_id: u128,
309         },
310         /// Indicates that we've been offered a payment and it needs to be claimed via calling
311         /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
312         ///
313         /// Note that if the preimage is not known, you should call
314         /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
315         /// to free up resources for this HTLC and avoid network congestion.
316         /// If you fail to call either [`ChannelManager::claim_funds`], [`ChannelManager::fail_htlc_backwards`],
317         /// or [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will be
318         /// automatically failed.
319         ///
320         /// # Note
321         /// LDK will not stop an inbound payment from being paid multiple times, so multiple
322         /// `PaymentClaimable` events may be generated for the same payment.
323         ///
324         /// # Note
325         /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
326         ///
327         /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
328         /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
329         /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
330         PaymentClaimable {
331                 /// The node that will receive the payment after it has been claimed.
332                 /// This is useful to identify payments received via [phantom nodes].
333                 /// This field will always be filled in when the event was generated by LDK versions
334                 /// 0.0.113 and above.
335                 ///
336                 /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
337                 receiver_node_id: Option<PublicKey>,
338                 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
339                 /// not stop you from registering duplicate payment hashes for inbound payments.
340                 payment_hash: PaymentHash,
341                 /// The value, in thousandths of a satoshi, that this payment is for.
342                 amount_msat: u64,
343                 /// Information for claiming this received payment, based on whether the purpose of the
344                 /// payment is to pay an invoice or to send a spontaneous payment.
345                 purpose: PaymentPurpose,
346                 /// The `channel_id` indicating over which channel we received the payment.
347                 via_channel_id: Option<[u8; 32]>,
348                 /// The `user_channel_id` indicating over which channel we received the payment.
349                 via_user_channel_id: Option<u128>,
350         },
351         /// Indicates a payment has been claimed and we've received money!
352         ///
353         /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
354         /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
355         /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
356         /// [`Event::PaymentClaimable`] event.
357         ///
358         /// # Note
359         /// LDK will not stop an inbound payment from being paid multiple times, so multiple
360         /// `PaymentClaimable` events may be generated for the same payment. If you then call
361         /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
362         /// multiple `PaymentClaimed` events.
363         ///
364         /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
365         PaymentClaimed {
366                 /// The node that received the payment.
367                 /// This is useful to identify payments which were received via [phantom nodes].
368                 /// This field will always be filled in when the event was generated by LDK versions
369                 /// 0.0.113 and above.
370                 ///
371                 /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
372                 receiver_node_id: Option<PublicKey>,
373                 /// The payment hash of the claimed payment. Note that LDK will not stop you from
374                 /// registering duplicate payment hashes for inbound payments.
375                 payment_hash: PaymentHash,
376                 /// The value, in thousandths of a satoshi, that this payment is for.
377                 amount_msat: u64,
378                 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
379                 /// spontaneous payment.
380                 purpose: PaymentPurpose,
381         },
382         /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
383         /// and we got back the payment preimage for it).
384         ///
385         /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
386         /// event. In this situation, you SHOULD treat this payment as having succeeded.
387         PaymentSent {
388                 /// The id returned by [`ChannelManager::send_payment`].
389                 ///
390                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
391                 payment_id: Option<PaymentId>,
392                 /// The preimage to the hash given to ChannelManager::send_payment.
393                 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
394                 /// store it somehow!
395                 payment_preimage: PaymentPreimage,
396                 /// The hash that was given to [`ChannelManager::send_payment`].
397                 ///
398                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
399                 payment_hash: PaymentHash,
400                 /// The total fee which was spent at intermediate hops in this payment, across all paths.
401                 ///
402                 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
403                 /// overpayment to the recipient node.
404                 ///
405                 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
406                 /// overstate the amount paid, though this is unlikely.
407                 ///
408                 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
409                 fee_paid_msat: Option<u64>,
410         },
411         /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
412         /// provide failure information for each path attempt in the payment, including retries.
413         ///
414         /// This event is provided once there are no further pending HTLCs for the payment and the
415         /// payment is no longer retryable, due either to the [`Retry`] provided or
416         /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
417         ///
418         /// [`Retry`]: crate::ln::channelmanager::Retry
419         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
420         PaymentFailed {
421                 /// The id returned by [`ChannelManager::send_payment`] and used with
422                 /// [`ChannelManager::abandon_payment`].
423                 ///
424                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
425                 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
426                 payment_id: PaymentId,
427                 /// The hash that was given to [`ChannelManager::send_payment`].
428                 ///
429                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
430                 payment_hash: PaymentHash,
431         },
432         /// Indicates that a path for an outbound payment was successful.
433         ///
434         /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
435         /// [`Event::PaymentSent`] for obtaining the payment preimage.
436         PaymentPathSuccessful {
437                 /// The id returned by [`ChannelManager::send_payment`].
438                 ///
439                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
440                 payment_id: PaymentId,
441                 /// The hash that was given to [`ChannelManager::send_payment`].
442                 ///
443                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
444                 payment_hash: Option<PaymentHash>,
445                 /// The payment path that was successful.
446                 ///
447                 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
448                 path: Vec<RouteHop>,
449         },
450         /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
451         /// handle the HTLC.
452         ///
453         /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
454         /// [`Event::PaymentFailed`].
455         ///
456         /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
457         /// been exhausted.
458         ///
459         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
460         PaymentPathFailed {
461                 /// The id returned by [`ChannelManager::send_payment`] and used with
462                 /// [`ChannelManager::abandon_payment`].
463                 ///
464                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
465                 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
466                 payment_id: Option<PaymentId>,
467                 /// The hash that was given to [`ChannelManager::send_payment`].
468                 ///
469                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
470                 payment_hash: PaymentHash,
471                 /// Indicates the payment was rejected for some reason by the recipient. This implies that
472                 /// the payment has failed, not just the route in question. If this is not set, the payment may
473                 /// be retried via a different route.
474                 payment_failed_permanently: bool,
475                 /// Extra error details based on the failure type. May contain an update that needs to be
476                 /// applied to the [`NetworkGraph`].
477                 ///
478                 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
479                 failure: PathFailure,
480                 /// The payment path that failed.
481                 path: Vec<RouteHop>,
482                 /// The channel responsible for the failed payment path.
483                 ///
484                 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
485                 /// may not refer to a channel in the public network graph. These aliases may also collide
486                 /// with channels in the public network graph.
487                 ///
488                 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
489                 /// retried. May be `None` for older [`Event`] serializations.
490                 short_channel_id: Option<u64>,
491 #[cfg(test)]
492                 error_code: Option<u16>,
493 #[cfg(test)]
494                 error_data: Option<Vec<u8>>,
495         },
496         /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
497         ProbeSuccessful {
498                 /// The id returned by [`ChannelManager::send_probe`].
499                 ///
500                 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
501                 payment_id: PaymentId,
502                 /// The hash generated by [`ChannelManager::send_probe`].
503                 ///
504                 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
505                 payment_hash: PaymentHash,
506                 /// The payment path that was successful.
507                 path: Vec<RouteHop>,
508         },
509         /// Indicates that a probe payment we sent failed at an intermediary node on the path.
510         ProbeFailed {
511                 /// The id returned by [`ChannelManager::send_probe`].
512                 ///
513                 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
514                 payment_id: PaymentId,
515                 /// The hash generated by [`ChannelManager::send_probe`].
516                 ///
517                 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
518                 payment_hash: PaymentHash,
519                 /// The payment path that failed.
520                 path: Vec<RouteHop>,
521                 /// The channel responsible for the failed probe.
522                 ///
523                 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
524                 /// may not refer to a channel in the public network graph. These aliases may also collide
525                 /// with channels in the public network graph.
526                 short_channel_id: Option<u64>,
527         },
528         /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
529         /// a time in the future.
530         ///
531         /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
532         PendingHTLCsForwardable {
533                 /// The minimum amount of time that should be waited prior to calling
534                 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
535                 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
536                 /// now + 5*time_forwardable).
537                 time_forwardable: Duration,
538         },
539         /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
540         /// you've encoded an intercept scid in the receiver's invoice route hints using
541         /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
542         ///
543         /// [`ChannelManager::forward_intercepted_htlc`] or
544         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
545         /// their docs for more information.
546         ///
547         /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
548         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
549         /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
550         /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
551         HTLCIntercepted {
552                 /// An id to help LDK identify which HTLC is being forwarded or failed.
553                 intercept_id: InterceptId,
554                 /// The fake scid that was programmed as the next hop's scid, generated using
555                 /// [`ChannelManager::get_intercept_scid`].
556                 ///
557                 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
558                 requested_next_hop_scid: u64,
559                 /// The payment hash used for this HTLC.
560                 payment_hash: PaymentHash,
561                 /// How many msats were received on the inbound edge of this HTLC.
562                 inbound_amount_msat: u64,
563                 /// How many msats the payer intended to route to the next node. Depending on the reason you are
564                 /// intercepting this payment, you might take a fee by forwarding less than this amount.
565                 ///
566                 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
567                 /// check that whatever fee you want has been included here or subtract it as required. Further,
568                 /// LDK will not stop you from forwarding more than you received.
569                 expected_outbound_amount_msat: u64,
570         },
571         /// Used to indicate that an output which you should know how to spend was confirmed on chain
572         /// and is now spendable.
573         /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
574         /// counterparty spending them due to some kind of timeout. Thus, you need to store them
575         /// somewhere and spend them when you create on-chain transactions.
576         SpendableOutputs {
577                 /// The outputs which you should store as spendable by you.
578                 outputs: Vec<SpendableOutputDescriptor>,
579         },
580         /// This event is generated when a payment has been successfully forwarded through us and a
581         /// forwarding fee earned.
582         PaymentForwarded {
583                 /// The incoming channel between the previous node and us. This is only `None` for events
584                 /// generated or serialized by versions prior to 0.0.107.
585                 prev_channel_id: Option<[u8; 32]>,
586                 /// The outgoing channel between the next node and us. This is only `None` for events
587                 /// generated or serialized by versions prior to 0.0.107.
588                 next_channel_id: Option<[u8; 32]>,
589                 /// The fee, in milli-satoshis, which was earned as a result of the payment.
590                 ///
591                 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
592                 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
593                 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
594                 /// claimed the full value in millisatoshis from the source. In this case,
595                 /// `claim_from_onchain_tx` will be set.
596                 ///
597                 /// If the channel which sent us the payment has been force-closed, we will claim the funds
598                 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
599                 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
600                 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
601                 /// `None`.
602                 fee_earned_msat: Option<u64>,
603                 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
604                 /// transaction.
605                 claim_from_onchain_tx: bool,
606                 /// The final amount forwarded, in milli-satoshis, after the fee is deducted.
607                 ///
608                 /// The caveat described above the `fee_earned_msat` field applies here as well.
609                 outbound_amount_forwarded_msat: Option<u64>,
610         },
611         /// Used to indicate that a channel with the given `channel_id` is ready to
612         /// be used. This event is emitted either when the funding transaction has been confirmed
613         /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
614         /// establishment.
615         ChannelReady {
616                 /// The channel_id of the channel that is ready.
617                 channel_id: [u8; 32],
618                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
619                 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
620                 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
621                 /// `user_channel_id` will be randomized for an inbound channel.
622                 ///
623                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
624                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
625                 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
626                 user_channel_id: u128,
627                 /// The node_id of the channel counterparty.
628                 counterparty_node_id: PublicKey,
629                 /// The features that this channel will operate with.
630                 channel_type: ChannelTypeFeatures,
631         },
632         /// Used to indicate that a previously opened channel with the given `channel_id` is in the
633         /// process of closure.
634         ChannelClosed  {
635                 /// The channel_id of the channel which has been closed. Note that on-chain transactions
636                 /// resolving the channel are likely still awaiting confirmation.
637                 channel_id: [u8; 32],
638                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
639                 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
640                 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
641                 /// `user_channel_id` will be randomized for inbound channels.
642                 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
643                 /// zero for objects serialized with LDK versions prior to 0.0.102.
644                 ///
645                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
646                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
647                 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
648                 user_channel_id: u128,
649                 /// The reason the channel was closed.
650                 reason: ClosureReason
651         },
652         /// Used to indicate to the user that they can abandon the funding transaction and recycle the
653         /// inputs for another purpose.
654         DiscardFunding {
655                 /// The channel_id of the channel which has been closed.
656                 channel_id: [u8; 32],
657                 /// The full transaction received from the user
658                 transaction: Transaction
659         },
660         /// Indicates a request to open a new channel by a peer.
661         ///
662         /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the
663         /// request, call [`ChannelManager::force_close_without_broadcasting_txn`].
664         ///
665         /// The event is only triggered when a new open channel request is received and the
666         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
667         ///
668         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
669         /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
670         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
671         OpenChannelRequest {
672                 /// The temporary channel ID of the channel requested to be opened.
673                 ///
674                 /// When responding to the request, the `temporary_channel_id` should be passed
675                 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
676                 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
677                 ///
678                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
679                 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
680                 temporary_channel_id: [u8; 32],
681                 /// The node_id of the counterparty requesting to open the channel.
682                 ///
683                 /// When responding to the request, the `counterparty_node_id` should be passed
684                 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
685                 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
686                 /// request.
687                 ///
688                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
689                 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
690                 counterparty_node_id: PublicKey,
691                 /// The channel value of the requested channel.
692                 funding_satoshis: u64,
693                 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
694                 push_msat: u64,
695                 /// The features that this channel will operate with. If you reject the channel, a
696                 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
697                 /// feature flags.
698                 ///
699                 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
700                 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
701                 /// 0.0.106.
702                 ///
703                 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
704                 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
705                 /// 0.0.107. Channels setting this type also need to get manually accepted via
706                 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
707                 /// or will be rejected otherwise.
708                 ///
709                 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
710                 channel_type: ChannelTypeFeatures,
711         },
712         /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
713         /// forward it.
714         ///
715         /// Some scenarios where this event may be sent include:
716         /// * Insufficient capacity in the outbound channel
717         /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
718         /// * When an unknown SCID is requested for forwarding a payment.
719         /// * Expected MPP amount has already been reached
720         /// * The HTLC has timed out
721         ///
722         /// This event, however, does not get generated if an HTLC fails to meet the forwarding
723         /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
724         HTLCHandlingFailed {
725                 /// The channel over which the HTLC was received.
726                 prev_channel_id: [u8; 32],
727                 /// Destination of the HTLC that failed to be processed.
728                 failed_next_destination: HTLCDestination,
729         },
730         #[cfg(anchors)]
731         /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
732         /// requires confirmed external funds to be readily available to spend.
733         ///
734         /// LDK does not currently generate this event. It is limited to the scope of channels with
735         /// anchor outputs, which will be introduced in a future release.
736         BumpTransaction(BumpTransactionEvent),
737 }
738
739 impl Writeable for Event {
740         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
741                 match self {
742                         &Event::FundingGenerationReady { .. } => {
743                                 0u8.write(writer)?;
744                                 // We never write out FundingGenerationReady events as, upon disconnection, peers
745                                 // drop any channels which have not yet exchanged funding_signed.
746                         },
747                         &Event::PaymentClaimable { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id } => {
748                                 1u8.write(writer)?;
749                                 let mut payment_secret = None;
750                                 let payment_preimage;
751                                 match &purpose {
752                                         PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
753                                                 payment_secret = Some(secret);
754                                                 payment_preimage = *preimage;
755                                         },
756                                         PaymentPurpose::SpontaneousPayment(preimage) => {
757                                                 payment_preimage = Some(*preimage);
758                                         }
759                                 }
760                                 write_tlv_fields!(writer, {
761                                         (0, payment_hash, required),
762                                         (1, receiver_node_id, option),
763                                         (2, payment_secret, option),
764                                         (3, via_channel_id, option),
765                                         (4, amount_msat, required),
766                                         (5, via_user_channel_id, option),
767                                         (6, 0u64, required), // user_payment_id required for compatibility with 0.0.103 and earlier
768                                         (8, payment_preimage, option),
769                                 });
770                         },
771                         &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
772                                 2u8.write(writer)?;
773                                 write_tlv_fields!(writer, {
774                                         (0, payment_preimage, required),
775                                         (1, payment_hash, required),
776                                         (3, payment_id, option),
777                                         (5, fee_paid_msat, option),
778                                 });
779                         },
780                         &Event::PaymentPathFailed {
781                                 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
782                                 ref path, ref short_channel_id,
783                                 #[cfg(test)]
784                                 ref error_code,
785                                 #[cfg(test)]
786                                 ref error_data,
787                         } => {
788                                 3u8.write(writer)?;
789                                 #[cfg(test)]
790                                 error_code.write(writer)?;
791                                 #[cfg(test)]
792                                 error_data.write(writer)?;
793                                 write_tlv_fields!(writer, {
794                                         (0, payment_hash, required),
795                                         (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
796                                         (2, payment_failed_permanently, required),
797                                         (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
798                                         (5, *path, vec_type),
799                                         (7, short_channel_id, option),
800                                         (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
801                                         (11, payment_id, option),
802                                         (13, failure, required),
803                                 });
804                         },
805                         &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
806                                 4u8.write(writer)?;
807                                 // Note that we now ignore these on the read end as we'll re-generate them in
808                                 // ChannelManager, we write them here only for backwards compatibility.
809                         },
810                         &Event::SpendableOutputs { ref outputs } => {
811                                 5u8.write(writer)?;
812                                 write_tlv_fields!(writer, {
813                                         (0, WithoutLength(outputs), required),
814                                 });
815                         },
816                         &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
817                                 6u8.write(writer)?;
818                                 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
819                                 write_tlv_fields!(writer, {
820                                         (0, intercept_id, required),
821                                         (2, intercept_scid, required),
822                                         (4, payment_hash, required),
823                                         (6, inbound_amount_msat, required),
824                                         (8, expected_outbound_amount_msat, required),
825                                 });
826                         }
827                         &Event::PaymentForwarded {
828                                 fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
829                                 next_channel_id, outbound_amount_forwarded_msat
830                         } => {
831                                 7u8.write(writer)?;
832                                 write_tlv_fields!(writer, {
833                                         (0, fee_earned_msat, option),
834                                         (1, prev_channel_id, option),
835                                         (2, claim_from_onchain_tx, required),
836                                         (3, next_channel_id, option),
837                                         (5, outbound_amount_forwarded_msat, option),
838                                 });
839                         },
840                         &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
841                                 9u8.write(writer)?;
842                                 // `user_channel_id` used to be a single u64 value. In order to remain backwards
843                                 // compatible with versions prior to 0.0.113, the u128 is serialized as two
844                                 // separate u64 values.
845                                 let user_channel_id_low = *user_channel_id as u64;
846                                 let user_channel_id_high = (*user_channel_id >> 64) as u64;
847                                 write_tlv_fields!(writer, {
848                                         (0, channel_id, required),
849                                         (1, user_channel_id_low, required),
850                                         (2, reason, required),
851                                         (3, user_channel_id_high, required),
852                                 });
853                         },
854                         &Event::DiscardFunding { ref channel_id, ref transaction } => {
855                                 11u8.write(writer)?;
856                                 write_tlv_fields!(writer, {
857                                         (0, channel_id, required),
858                                         (2, transaction, required)
859                                 })
860                         },
861                         &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
862                                 13u8.write(writer)?;
863                                 write_tlv_fields!(writer, {
864                                         (0, payment_id, required),
865                                         (2, payment_hash, option),
866                                         (4, *path, vec_type)
867                                 })
868                         },
869                         &Event::PaymentFailed { ref payment_id, ref payment_hash } => {
870                                 15u8.write(writer)?;
871                                 write_tlv_fields!(writer, {
872                                         (0, payment_id, required),
873                                         (2, payment_hash, required),
874                                 })
875                         },
876                         &Event::OpenChannelRequest { .. } => {
877                                 17u8.write(writer)?;
878                                 // We never write the OpenChannelRequest events as, upon disconnection, peers
879                                 // drop any channels which have not yet exchanged funding_signed.
880                         },
881                         &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id } => {
882                                 19u8.write(writer)?;
883                                 write_tlv_fields!(writer, {
884                                         (0, payment_hash, required),
885                                         (1, receiver_node_id, option),
886                                         (2, purpose, required),
887                                         (4, amount_msat, required),
888                                 });
889                         },
890                         &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
891                                 21u8.write(writer)?;
892                                 write_tlv_fields!(writer, {
893                                         (0, payment_id, required),
894                                         (2, payment_hash, required),
895                                         (4, *path, vec_type)
896                                 })
897                         },
898                         &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
899                                 23u8.write(writer)?;
900                                 write_tlv_fields!(writer, {
901                                         (0, payment_id, required),
902                                         (2, payment_hash, required),
903                                         (4, *path, vec_type),
904                                         (6, short_channel_id, option),
905                                 })
906                         },
907                         &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
908                                 25u8.write(writer)?;
909                                 write_tlv_fields!(writer, {
910                                         (0, prev_channel_id, required),
911                                         (2, failed_next_destination, required),
912                                 })
913                         },
914                         #[cfg(anchors)]
915                         &Event::BumpTransaction(ref event)=> {
916                                 27u8.write(writer)?;
917                                 match event {
918                                         // We never write the ChannelClose|HTLCResolution events as they'll be replayed
919                                         // upon restarting anyway if they remain unresolved.
920                                         BumpTransactionEvent::ChannelClose { .. } => {}
921                                         BumpTransactionEvent::HTLCResolution { .. } => {}
922                                 }
923                                 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
924                         }
925                         &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
926                                 29u8.write(writer)?;
927                                 write_tlv_fields!(writer, {
928                                         (0, channel_id, required),
929                                         (2, user_channel_id, required),
930                                         (4, counterparty_node_id, required),
931                                         (6, channel_type, required),
932                                 });
933                         },
934                         // Note that, going forward, all new events must only write data inside of
935                         // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
936                         // data via `write_tlv_fields`.
937                 }
938                 Ok(())
939         }
940 }
941 impl MaybeReadable for Event {
942         fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
943                 match Readable::read(reader)? {
944                         // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
945                         // unlike all other events, thus we return immediately here.
946                         0u8 => Ok(None),
947                         1u8 => {
948                                 let f = || {
949                                         let mut payment_hash = PaymentHash([0; 32]);
950                                         let mut payment_preimage = None;
951                                         let mut payment_secret = None;
952                                         let mut amount_msat = 0;
953                                         let mut receiver_node_id = None;
954                                         let mut _user_payment_id = None::<u64>; // For compatibility with 0.0.103 and earlier
955                                         let mut via_channel_id = None;
956                                         let mut via_user_channel_id = None;
957                                         read_tlv_fields!(reader, {
958                                                 (0, payment_hash, required),
959                                                 (1, receiver_node_id, option),
960                                                 (2, payment_secret, option),
961                                                 (3, via_channel_id, option),
962                                                 (4, amount_msat, required),
963                                                 (5, via_user_channel_id, option),
964                                                 (6, _user_payment_id, option),
965                                                 (8, payment_preimage, option),
966                                         });
967                                         let purpose = match payment_secret {
968                                                 Some(secret) => PaymentPurpose::InvoicePayment {
969                                                         payment_preimage,
970                                                         payment_secret: secret
971                                                 },
972                                                 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
973                                                 None => return Err(msgs::DecodeError::InvalidValue),
974                                         };
975                                         Ok(Some(Event::PaymentClaimable {
976                                                 receiver_node_id,
977                                                 payment_hash,
978                                                 amount_msat,
979                                                 purpose,
980                                                 via_channel_id,
981                                                 via_user_channel_id,
982                                         }))
983                                 };
984                                 f()
985                         },
986                         2u8 => {
987                                 let f = || {
988                                         let mut payment_preimage = PaymentPreimage([0; 32]);
989                                         let mut payment_hash = None;
990                                         let mut payment_id = None;
991                                         let mut fee_paid_msat = None;
992                                         read_tlv_fields!(reader, {
993                                                 (0, payment_preimage, required),
994                                                 (1, payment_hash, option),
995                                                 (3, payment_id, option),
996                                                 (5, fee_paid_msat, option),
997                                         });
998                                         if payment_hash.is_none() {
999                                                 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
1000                                         }
1001                                         Ok(Some(Event::PaymentSent {
1002                                                 payment_id,
1003                                                 payment_preimage,
1004                                                 payment_hash: payment_hash.unwrap(),
1005                                                 fee_paid_msat,
1006                                         }))
1007                                 };
1008                                 f()
1009                         },
1010                         3u8 => {
1011                                 let f = || {
1012                                         #[cfg(test)]
1013                                         let error_code = Readable::read(reader)?;
1014                                         #[cfg(test)]
1015                                         let error_data = Readable::read(reader)?;
1016                                         let mut payment_hash = PaymentHash([0; 32]);
1017                                         let mut payment_failed_permanently = false;
1018                                         let mut network_update = None;
1019                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1020                                         let mut short_channel_id = None;
1021                                         let mut payment_id = None;
1022                                         let mut failure_opt = None;
1023                                         read_tlv_fields!(reader, {
1024                                                 (0, payment_hash, required),
1025                                                 (1, network_update, upgradable_option),
1026                                                 (2, payment_failed_permanently, required),
1027                                                 (5, path, vec_type),
1028                                                 (7, short_channel_id, option),
1029                                                 (11, payment_id, option),
1030                                                 (13, failure_opt, upgradable_option),
1031                                         });
1032                                         let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1033                                         Ok(Some(Event::PaymentPathFailed {
1034                                                 payment_id,
1035                                                 payment_hash,
1036                                                 payment_failed_permanently,
1037                                                 failure,
1038                                                 path: path.unwrap(),
1039                                                 short_channel_id,
1040                                                 #[cfg(test)]
1041                                                 error_code,
1042                                                 #[cfg(test)]
1043                                                 error_data,
1044                                         }))
1045                                 };
1046                                 f()
1047                         },
1048                         4u8 => Ok(None),
1049                         5u8 => {
1050                                 let f = || {
1051                                         let mut outputs = WithoutLength(Vec::new());
1052                                         read_tlv_fields!(reader, {
1053                                                 (0, outputs, required),
1054                                         });
1055                                         Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
1056                                 };
1057                                 f()
1058                         },
1059                         6u8 => {
1060                                 let mut payment_hash = PaymentHash([0; 32]);
1061                                 let mut intercept_id = InterceptId([0; 32]);
1062                                 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1063                                 let mut inbound_amount_msat = 0;
1064                                 let mut expected_outbound_amount_msat = 0;
1065                                 read_tlv_fields!(reader, {
1066                                         (0, intercept_id, required),
1067                                         (2, requested_next_hop_scid, required),
1068                                         (4, payment_hash, required),
1069                                         (6, inbound_amount_msat, required),
1070                                         (8, expected_outbound_amount_msat, required),
1071                                 });
1072                                 let next_scid = match requested_next_hop_scid {
1073                                         InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1074                                 };
1075                                 Ok(Some(Event::HTLCIntercepted {
1076                                         payment_hash,
1077                                         requested_next_hop_scid: next_scid,
1078                                         inbound_amount_msat,
1079                                         expected_outbound_amount_msat,
1080                                         intercept_id,
1081                                 }))
1082                         },
1083                         7u8 => {
1084                                 let f = || {
1085                                         let mut fee_earned_msat = None;
1086                                         let mut prev_channel_id = None;
1087                                         let mut claim_from_onchain_tx = false;
1088                                         let mut next_channel_id = None;
1089                                         let mut outbound_amount_forwarded_msat = None;
1090                                         read_tlv_fields!(reader, {
1091                                                 (0, fee_earned_msat, option),
1092                                                 (1, prev_channel_id, option),
1093                                                 (2, claim_from_onchain_tx, required),
1094                                                 (3, next_channel_id, option),
1095                                                 (5, outbound_amount_forwarded_msat, option),
1096                                         });
1097                                         Ok(Some(Event::PaymentForwarded {
1098                                                 fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id,
1099                                                 outbound_amount_forwarded_msat
1100                                         }))
1101                                 };
1102                                 f()
1103                         },
1104                         9u8 => {
1105                                 let f = || {
1106                                         let mut channel_id = [0; 32];
1107                                         let mut reason = UpgradableRequired(None);
1108                                         let mut user_channel_id_low_opt: Option<u64> = None;
1109                                         let mut user_channel_id_high_opt: Option<u64> = None;
1110                                         read_tlv_fields!(reader, {
1111                                                 (0, channel_id, required),
1112                                                 (1, user_channel_id_low_opt, option),
1113                                                 (2, reason, upgradable_required),
1114                                                 (3, user_channel_id_high_opt, option),
1115                                         });
1116
1117                                         // `user_channel_id` used to be a single u64 value. In order to remain
1118                                         // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1119                                         // as two separate u64 values.
1120                                         let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1121                                                 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1122
1123                                         Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required) }))
1124                                 };
1125                                 f()
1126                         },
1127                         11u8 => {
1128                                 let f = || {
1129                                         let mut channel_id = [0; 32];
1130                                         let mut transaction = Transaction{ version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
1131                                         read_tlv_fields!(reader, {
1132                                                 (0, channel_id, required),
1133                                                 (2, transaction, required),
1134                                         });
1135                                         Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1136                                 };
1137                                 f()
1138                         },
1139                         13u8 => {
1140                                 let f = || {
1141                                         let mut payment_id = PaymentId([0; 32]);
1142                                         let mut payment_hash = None;
1143                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1144                                         read_tlv_fields!(reader, {
1145                                                 (0, payment_id, required),
1146                                                 (2, payment_hash, option),
1147                                                 (4, path, vec_type),
1148                                         });
1149                                         Ok(Some(Event::PaymentPathSuccessful {
1150                                                 payment_id,
1151                                                 payment_hash,
1152                                                 path: path.unwrap(),
1153                                         }))
1154                                 };
1155                                 f()
1156                         },
1157                         15u8 => {
1158                                 let f = || {
1159                                         let mut payment_hash = PaymentHash([0; 32]);
1160                                         let mut payment_id = PaymentId([0; 32]);
1161                                         read_tlv_fields!(reader, {
1162                                                 (0, payment_id, required),
1163                                                 (2, payment_hash, required),
1164                                         });
1165                                         Ok(Some(Event::PaymentFailed {
1166                                                 payment_id,
1167                                                 payment_hash,
1168                                         }))
1169                                 };
1170                                 f()
1171                         },
1172                         17u8 => {
1173                                 // Value 17 is used for `Event::OpenChannelRequest`.
1174                                 Ok(None)
1175                         },
1176                         19u8 => {
1177                                 let f = || {
1178                                         let mut payment_hash = PaymentHash([0; 32]);
1179                                         let mut purpose = UpgradableRequired(None);
1180                                         let mut amount_msat = 0;
1181                                         let mut receiver_node_id = None;
1182                                         read_tlv_fields!(reader, {
1183                                                 (0, payment_hash, required),
1184                                                 (1, receiver_node_id, option),
1185                                                 (2, purpose, upgradable_required),
1186                                                 (4, amount_msat, required),
1187                                         });
1188                                         Ok(Some(Event::PaymentClaimed {
1189                                                 receiver_node_id,
1190                                                 payment_hash,
1191                                                 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1192                                                 amount_msat,
1193                                         }))
1194                                 };
1195                                 f()
1196                         },
1197                         21u8 => {
1198                                 let f = || {
1199                                         let mut payment_id = PaymentId([0; 32]);
1200                                         let mut payment_hash = PaymentHash([0; 32]);
1201                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1202                                         read_tlv_fields!(reader, {
1203                                                 (0, payment_id, required),
1204                                                 (2, payment_hash, required),
1205                                                 (4, path, vec_type),
1206                                         });
1207                                         Ok(Some(Event::ProbeSuccessful {
1208                                                 payment_id,
1209                                                 payment_hash,
1210                                                 path: path.unwrap(),
1211                                         }))
1212                                 };
1213                                 f()
1214                         },
1215                         23u8 => {
1216                                 let f = || {
1217                                         let mut payment_id = PaymentId([0; 32]);
1218                                         let mut payment_hash = PaymentHash([0; 32]);
1219                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1220                                         let mut short_channel_id = None;
1221                                         read_tlv_fields!(reader, {
1222                                                 (0, payment_id, required),
1223                                                 (2, payment_hash, required),
1224                                                 (4, path, vec_type),
1225                                                 (6, short_channel_id, option),
1226                                         });
1227                                         Ok(Some(Event::ProbeFailed {
1228                                                 payment_id,
1229                                                 payment_hash,
1230                                                 path: path.unwrap(),
1231                                                 short_channel_id,
1232                                         }))
1233                                 };
1234                                 f()
1235                         },
1236                         25u8 => {
1237                                 let f = || {
1238                                         let mut prev_channel_id = [0; 32];
1239                                         let mut failed_next_destination_opt = UpgradableRequired(None);
1240                                         read_tlv_fields!(reader, {
1241                                                 (0, prev_channel_id, required),
1242                                                 (2, failed_next_destination_opt, upgradable_required),
1243                                         });
1244                                         Ok(Some(Event::HTLCHandlingFailed {
1245                                                 prev_channel_id,
1246                                                 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1247                                         }))
1248                                 };
1249                                 f()
1250                         },
1251                         27u8 => Ok(None),
1252                         29u8 => {
1253                                 let f = || {
1254                                         let mut channel_id = [0; 32];
1255                                         let mut user_channel_id: u128 = 0;
1256                                         let mut counterparty_node_id = RequiredWrapper(None);
1257                                         let mut channel_type = RequiredWrapper(None);
1258                                         read_tlv_fields!(reader, {
1259                                                 (0, channel_id, required),
1260                                                 (2, user_channel_id, required),
1261                                                 (4, counterparty_node_id, required),
1262                                                 (6, channel_type, required),
1263                                         });
1264
1265                                         Ok(Some(Event::ChannelReady {
1266                                                 channel_id,
1267                                                 user_channel_id,
1268                                                 counterparty_node_id: counterparty_node_id.0.unwrap(),
1269                                                 channel_type: channel_type.0.unwrap()
1270                                         }))
1271                                 };
1272                                 f()
1273                         },
1274                         // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1275                         // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1276                         // reads.
1277                         x if x % 2 == 1 => {
1278                                 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1279                                 // which prefixes the whole thing with a length BigSize. Because the event is
1280                                 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1281                                 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1282                                 // exactly the number of bytes specified, ignoring them entirely.
1283                                 let tlv_len: BigSize = Readable::read(reader)?;
1284                                 FixedLengthReader::new(reader, tlv_len.0)
1285                                         .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1286                                 Ok(None)
1287                         },
1288                         _ => Err(msgs::DecodeError::InvalidValue)
1289                 }
1290         }
1291 }
1292
1293 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1294 /// broadcast to most peers).
1295 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1296 #[derive(Clone, Debug)]
1297 pub enum MessageSendEvent {
1298         /// Used to indicate that we've accepted a channel open and should send the accept_channel
1299         /// message provided to the given peer.
1300         SendAcceptChannel {
1301                 /// The node_id of the node which should receive this message
1302                 node_id: PublicKey,
1303                 /// The message which should be sent.
1304                 msg: msgs::AcceptChannel,
1305         },
1306         /// Used to indicate that we've initiated a channel open and should send the open_channel
1307         /// message provided to the given peer.
1308         SendOpenChannel {
1309                 /// The node_id of the node which should receive this message
1310                 node_id: PublicKey,
1311                 /// The message which should be sent.
1312                 msg: msgs::OpenChannel,
1313         },
1314         /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1315         SendFundingCreated {
1316                 /// The node_id of the node which should receive this message
1317                 node_id: PublicKey,
1318                 /// The message which should be sent.
1319                 msg: msgs::FundingCreated,
1320         },
1321         /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1322         SendFundingSigned {
1323                 /// The node_id of the node which should receive this message
1324                 node_id: PublicKey,
1325                 /// The message which should be sent.
1326                 msg: msgs::FundingSigned,
1327         },
1328         /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1329         SendChannelReady {
1330                 /// The node_id of the node which should receive these message(s)
1331                 node_id: PublicKey,
1332                 /// The channel_ready message which should be sent.
1333                 msg: msgs::ChannelReady,
1334         },
1335         /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1336         SendAnnouncementSignatures {
1337                 /// The node_id of the node which should receive these message(s)
1338                 node_id: PublicKey,
1339                 /// The announcement_signatures message which should be sent.
1340                 msg: msgs::AnnouncementSignatures,
1341         },
1342         /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1343         /// message should be sent to the peer with the given node_id.
1344         UpdateHTLCs {
1345                 /// The node_id of the node which should receive these message(s)
1346                 node_id: PublicKey,
1347                 /// The update messages which should be sent. ALL messages in the struct should be sent!
1348                 updates: msgs::CommitmentUpdate,
1349         },
1350         /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1351         SendRevokeAndACK {
1352                 /// The node_id of the node which should receive this message
1353                 node_id: PublicKey,
1354                 /// The message which should be sent.
1355                 msg: msgs::RevokeAndACK,
1356         },
1357         /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1358         SendClosingSigned {
1359                 /// The node_id of the node which should receive this message
1360                 node_id: PublicKey,
1361                 /// The message which should be sent.
1362                 msg: msgs::ClosingSigned,
1363         },
1364         /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1365         SendShutdown {
1366                 /// The node_id of the node which should receive this message
1367                 node_id: PublicKey,
1368                 /// The message which should be sent.
1369                 msg: msgs::Shutdown,
1370         },
1371         /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1372         SendChannelReestablish {
1373                 /// The node_id of the node which should receive this message
1374                 node_id: PublicKey,
1375                 /// The message which should be sent.
1376                 msg: msgs::ChannelReestablish,
1377         },
1378         /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1379         /// initial connection to ensure our peers know about our channels.
1380         SendChannelAnnouncement {
1381                 /// The node_id of the node which should receive this message
1382                 node_id: PublicKey,
1383                 /// The channel_announcement which should be sent.
1384                 msg: msgs::ChannelAnnouncement,
1385                 /// The followup channel_update which should be sent.
1386                 update_msg: msgs::ChannelUpdate,
1387         },
1388         /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1389         /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1390         ///
1391         /// Note that after doing so, you very likely (unless you did so very recently) want to
1392         /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1393         /// ensures that any nodes which see our channel_announcement also have a relevant
1394         /// node_announcement, including relevant feature flags which may be important for routing
1395         /// through or to us.
1396         ///
1397         /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1398         BroadcastChannelAnnouncement {
1399                 /// The channel_announcement which should be sent.
1400                 msg: msgs::ChannelAnnouncement,
1401                 /// The followup channel_update which should be sent.
1402                 update_msg: Option<msgs::ChannelUpdate>,
1403         },
1404         /// Used to indicate that a channel_update should be broadcast to all peers.
1405         BroadcastChannelUpdate {
1406                 /// The channel_update which should be sent.
1407                 msg: msgs::ChannelUpdate,
1408         },
1409         /// Used to indicate that a node_announcement should be broadcast to all peers.
1410         BroadcastNodeAnnouncement {
1411                 /// The node_announcement which should be sent.
1412                 msg: msgs::NodeAnnouncement,
1413         },
1414         /// Used to indicate that a channel_update should be sent to a single peer.
1415         /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1416         /// private channel and we shouldn't be informing all of our peers of channel parameters.
1417         SendChannelUpdate {
1418                 /// The node_id of the node which should receive this message
1419                 node_id: PublicKey,
1420                 /// The channel_update which should be sent.
1421                 msg: msgs::ChannelUpdate,
1422         },
1423         /// Broadcast an error downstream to be handled
1424         HandleError {
1425                 /// The node_id of the node which should receive this message
1426                 node_id: PublicKey,
1427                 /// The action which should be taken.
1428                 action: msgs::ErrorAction
1429         },
1430         /// Query a peer for channels with funding transaction UTXOs in a block range.
1431         SendChannelRangeQuery {
1432                 /// The node_id of this message recipient
1433                 node_id: PublicKey,
1434                 /// The query_channel_range which should be sent.
1435                 msg: msgs::QueryChannelRange,
1436         },
1437         /// Request routing gossip messages from a peer for a list of channels identified by
1438         /// their short_channel_ids.
1439         SendShortIdsQuery {
1440                 /// The node_id of this message recipient
1441                 node_id: PublicKey,
1442                 /// The query_short_channel_ids which should be sent.
1443                 msg: msgs::QueryShortChannelIds,
1444         },
1445         /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1446         /// emitted during processing of the query.
1447         SendReplyChannelRange {
1448                 /// The node_id of this message recipient
1449                 node_id: PublicKey,
1450                 /// The reply_channel_range which should be sent.
1451                 msg: msgs::ReplyChannelRange,
1452         },
1453         /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1454         /// enable receiving gossip messages from the peer.
1455         SendGossipTimestampFilter {
1456                 /// The node_id of this message recipient
1457                 node_id: PublicKey,
1458                 /// The gossip_timestamp_filter which should be sent.
1459                 msg: msgs::GossipTimestampFilter,
1460         },
1461 }
1462
1463 /// A trait indicating an object may generate message send events
1464 pub trait MessageSendEventsProvider {
1465         /// Gets the list of pending events which were generated by previous actions, clearing the list
1466         /// in the process.
1467         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1468 }
1469
1470 /// A trait indicating an object may generate onion messages to send
1471 pub trait OnionMessageProvider {
1472         /// Gets the next pending onion message for the peer with the given node id.
1473         fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<msgs::OnionMessage>;
1474 }
1475
1476 /// A trait indicating an object may generate events.
1477 ///
1478 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1479 ///
1480 /// Implementations of this trait may also feature an async version of event handling, as shown with
1481 /// [`ChannelManager::process_pending_events_async`] and
1482 /// [`ChainMonitor::process_pending_events_async`].
1483 ///
1484 /// # Requirements
1485 ///
1486 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1487 /// event since the last invocation.
1488 ///
1489 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1490 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1491 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1492 /// relevant changes to disk *before* returning.
1493 ///
1494 /// Further, because an application may crash between an [`Event`] being handled and the
1495 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1496 /// effect, [`Event`]s may be replayed.
1497 ///
1498 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1499 /// consult the provider's documentation on the implication of processing events and how a handler
1500 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1501 /// [`ChainMonitor::process_pending_events`]).
1502 ///
1503 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1504 /// own type(s).
1505 ///
1506 /// [`process_pending_events`]: Self::process_pending_events
1507 /// [`handle_event`]: EventHandler::handle_event
1508 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1509 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1510 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
1511 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
1512 pub trait EventsProvider {
1513         /// Processes any events generated since the last call using the given event handler.
1514         ///
1515         /// See the trait-level documentation for requirements.
1516         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1517 }
1518
1519 /// A trait implemented for objects handling events from [`EventsProvider`].
1520 ///
1521 /// An async variation also exists for implementations of [`EventsProvider`] that support async
1522 /// event handling. The async event handler should satisfy the generic bounds: `F:
1523 /// core::future::Future, H: Fn(Event) -> F`.
1524 pub trait EventHandler {
1525         /// Handles the given [`Event`].
1526         ///
1527         /// See [`EventsProvider`] for details that must be considered when implementing this method.
1528         fn handle_event(&self, event: Event);
1529 }
1530
1531 impl<F> EventHandler for F where F: Fn(Event) {
1532         fn handle_event(&self, event: Event) {
1533                 self(event)
1534         }
1535 }
1536
1537 impl<T: EventHandler> EventHandler for Arc<T> {
1538         fn handle_event(&self, event: Event) {
1539                 self.deref().handle_event(event)
1540         }
1541 }