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