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