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