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