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