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