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