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