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