Merge pull request #1388 from lightning-signer/2022-03-grind
[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::msgs;
21 use ln::msgs::DecodeError;
22 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
23 use routing::network_graph::NetworkUpdate;
24 use util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, VecReadWrapper, VecWriteWrapper};
25 use routing::router::{RouteHop, RouteParameters};
26
27 use bitcoin::Transaction;
28 use bitcoin::blockdata::script::Script;
29 use bitcoin::hashes::Hash;
30 use bitcoin::hashes::sha256::Hash as Sha256;
31 use bitcoin::secp256k1::key::PublicKey;
32 use io;
33 use prelude::*;
34 use core::time::Duration;
35 use core::ops::Deref;
36 use sync::Arc;
37
38 /// Some information provided on receipt of payment depends on whether the payment received is a
39 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
40 #[derive(Clone, Debug)]
41 pub enum PaymentPurpose {
42         /// Information for receiving a payment that we generated an invoice for.
43         InvoicePayment {
44                 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
45                 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
46                 /// [`ChannelManager::claim_funds`].
47                 ///
48                 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
49                 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
50                 payment_preimage: Option<PaymentPreimage>,
51                 /// The "payment secret". This authenticates the sender to the recipient, preventing a
52                 /// number of deanonymization attacks during the routing process.
53                 /// It is provided here for your reference, however its accuracy is enforced directly by
54                 /// [`ChannelManager`] using the values you previously provided to
55                 /// [`ChannelManager::create_inbound_payment`] or
56                 /// [`ChannelManager::create_inbound_payment_for_hash`].
57                 ///
58                 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
59                 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
60                 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
61                 payment_secret: PaymentSecret,
62         },
63         /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
64         /// (the payee) providing a preimage.
65         SpontaneousPayment(PaymentPreimage),
66 }
67
68 #[derive(Clone, Debug, PartialEq)]
69 /// The reason the channel was closed. See individual variants more details.
70 pub enum ClosureReason {
71         /// Closure generated from receiving a peer error message.
72         ///
73         /// Our counterparty may have broadcasted their latest commitment state, and we have
74         /// as well.
75         CounterpartyForceClosed {
76                 /// The error which the peer sent us.
77                 ///
78                 /// The string should be sanitized before it is used (e.g emitted to logs
79                 /// or printed to stdout). Otherwise, a well crafted error message may exploit
80                 /// a security vulnerability in the terminal emulator or the logging subsystem.
81                 peer_msg: String,
82         },
83         /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
84         ///
85         /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
86         HolderForceClosed,
87         /// The channel was closed after negotiating a cooperative close and we've now broadcasted
88         /// the cooperative close transaction. Note the shutdown may have been initiated by us.
89         //TODO: split between CounterpartyInitiated/LocallyInitiated
90         CooperativeClosure,
91         /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
92         /// commitment transaction came from our counterparty, but it may also have come from
93         /// a copy of our own `ChannelMonitor`.
94         CommitmentTxConfirmed,
95         /// The funding transaction failed to confirm in a timely manner on an inbound channel.
96         FundingTimedOut,
97         /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
98         ProcessingError {
99                 /// A developer-readable error message which we generated.
100                 err: String,
101         },
102         /// The `PeerManager` informed us that we've disconnected from the peer. We close channels
103         /// if the `PeerManager` informed us that it is unlikely we'll be able to connect to the
104         /// peer again in the future or if the peer disconnected before we finished negotiating
105         /// the channel open. The first case may be caused by incompatible features which our
106         /// counterparty, or we, require.
107         //TODO: split between PeerUnconnectable/PeerDisconnected ?
108         DisconnectedPeer,
109         /// Closure generated from `ChannelManager::read` if the ChannelMonitor is newer than
110         /// the ChannelManager deserialized.
111         OutdatedChannelManager
112 }
113
114 impl core::fmt::Display for ClosureReason {
115         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
116                 f.write_str("Channel closed because ")?;
117                 match self {
118                         ClosureReason::CounterpartyForceClosed { peer_msg } => {
119                                 f.write_str("counterparty force-closed with message ")?;
120                                 f.write_str(&peer_msg)
121                         },
122                         ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
123                         ClosureReason::CooperativeClosure => f.write_str("the channel was cooperatively closed"),
124                         ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
125                         ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
126                         ClosureReason::ProcessingError { err } => {
127                                 f.write_str("of an exception: ")?;
128                                 f.write_str(&err)
129                         },
130                         ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
131                         ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
132                 }
133         }
134 }
135
136 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
137         (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
138         (1, FundingTimedOut) => {},
139         (2, HolderForceClosed) => {},
140         (6, CommitmentTxConfirmed) => {},
141         (4, CooperativeClosure) => {},
142         (8, ProcessingError) => { (1, err, required) },
143         (10, DisconnectedPeer) => {},
144         (12, OutdatedChannelManager) => {},
145 );
146
147 /// An Event which you should probably take some action in response to.
148 ///
149 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
150 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
151 /// written as it makes no sense to respond to it after reconnecting to peers).
152 #[derive(Clone, Debug)]
153 pub enum Event {
154         /// Used to indicate that the client should generate a funding transaction with the given
155         /// parameters and then call [`ChannelManager::funding_transaction_generated`].
156         /// Generated in [`ChannelManager`] message handling.
157         /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
158         /// counterparty can steal your funds!
159         ///
160         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
161         /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
162         FundingGenerationReady {
163                 /// The random channel_id we picked which you'll need to pass into
164                 /// ChannelManager::funding_transaction_generated.
165                 temporary_channel_id: [u8; 32],
166                 /// The value, in satoshis, that the output should have.
167                 channel_value_satoshis: u64,
168                 /// The script which should be used in the transaction output.
169                 output_script: Script,
170                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or 0 for
171                 /// an inbound channel.
172                 ///
173                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
174                 user_channel_id: u64,
175         },
176         /// Indicates we've received money! Just gotta dig out that payment preimage and feed it to
177         /// [`ChannelManager::claim_funds`] to get it....
178         /// Note that if the preimage is not known, you should call
179         /// [`ChannelManager::fail_htlc_backwards`] to free up resources for this HTLC and avoid
180         /// network congestion.
181         /// If you fail to call either [`ChannelManager::claim_funds`] or
182         /// [`ChannelManager::fail_htlc_backwards`] within the HTLC's timeout, the HTLC will be
183         /// automatically failed.
184         ///
185         /// # Note
186         /// LDK will not stop an inbound payment from being paid multiple times, so multiple
187         /// `PaymentReceived` events may be generated for the same payment.
188         ///
189         /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
190         /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
191         PaymentReceived {
192                 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
193                 /// not stop you from registering duplicate payment hashes for inbound payments.
194                 payment_hash: PaymentHash,
195                 /// The value, in thousandths of a satoshi, that this payment is for.
196                 amt: u64,
197                 /// Information for claiming this received payment, based on whether the purpose of the
198                 /// payment is to pay an invoice or to send a spontaneous payment.
199                 purpose: PaymentPurpose,
200         },
201         /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
202         /// and we got back the payment preimage for it).
203         ///
204         /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
205         /// event. In this situation, you SHOULD treat this payment as having succeeded.
206         PaymentSent {
207                 /// The id returned by [`ChannelManager::send_payment`] and used with
208                 /// [`ChannelManager::retry_payment`].
209                 ///
210                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
211                 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
212                 payment_id: Option<PaymentId>,
213                 /// The preimage to the hash given to ChannelManager::send_payment.
214                 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
215                 /// store it somehow!
216                 payment_preimage: PaymentPreimage,
217                 /// The hash that was given to [`ChannelManager::send_payment`].
218                 ///
219                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
220                 payment_hash: PaymentHash,
221                 /// The total fee which was spent at intermediate hops in this payment, across all paths.
222                 ///
223                 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
224                 /// overpayment to the recipient node.
225                 ///
226                 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
227                 /// overstate the amount paid, though this is unlikely.
228                 ///
229                 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
230                 fee_paid_msat: Option<u64>,
231         },
232         /// Indicates an outbound HTLC we sent failed. Probably some intermediary node dropped
233         /// something. You may wish to retry with a different route.
234         ///
235         /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
236         /// [`Event::PaymentFailed`] and [`all_paths_failed`].
237         ///
238         /// [`all_paths_failed`]: Self::PaymentPathFailed::all_paths_failed
239         PaymentPathFailed {
240                 /// The id returned by [`ChannelManager::send_payment`] and used with
241                 /// [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`].
242                 ///
243                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
244                 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
245                 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
246                 payment_id: Option<PaymentId>,
247                 /// The hash that was given to [`ChannelManager::send_payment`].
248                 ///
249                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
250                 payment_hash: PaymentHash,
251                 /// Indicates the payment was rejected for some reason by the recipient. This implies that
252                 /// the payment has failed, not just the route in question. If this is not set, you may
253                 /// retry the payment via a different route.
254                 rejected_by_dest: bool,
255                 /// Any failure information conveyed via the Onion return packet by a node along the failed
256                 /// payment route.
257                 ///
258                 /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into
259                 /// account the update. [`NetGraphMsgHandler`] is capable of doing this.
260                 ///
261                 /// [`NetworkGraph`]: crate::routing::network_graph::NetworkGraph
262                 /// [`NetGraphMsgHandler`]: crate::routing::network_graph::NetGraphMsgHandler
263                 network_update: Option<NetworkUpdate>,
264                 /// For both single-path and multi-path payments, this is set if all paths of the payment have
265                 /// failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the
266                 /// larger MPP payment were still in flight when this event was generated.
267                 ///
268                 /// Note that if you are retrying individual MPP parts, using this value to determine if a
269                 /// payment has fully failed is race-y. Because multiple failures can happen prior to events
270                 /// being processed, you may retry in response to a first failure, with a second failure
271                 /// (with `all_paths_failed` set) still pending. Then, when the second failure is processed
272                 /// you will see `all_paths_failed` set even though the retry of the first failure still
273                 /// has an associated in-flight HTLC. See (1) for an example of such a failure.
274                 ///
275                 /// If you wish to retry individual MPP parts and learn when a payment has failed, you must
276                 /// call [`ChannelManager::abandon_payment`] and wait for a [`Event::PaymentFailed`] event.
277                 ///
278                 /// (1) <https://github.com/lightningdevkit/rust-lightning/issues/1164>
279                 ///
280                 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
281                 all_paths_failed: bool,
282                 /// The payment path that failed.
283                 path: Vec<RouteHop>,
284                 /// The channel responsible for the failed payment path.
285                 ///
286                 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
287                 /// retried. May be `None` for older [`Event`] serializations.
288                 short_channel_id: Option<u64>,
289                 /// Parameters needed to compute a new [`Route`] when retrying the failed payment path.
290                 ///
291                 /// See [`find_route`] for details.
292                 ///
293                 /// [`Route`]: crate::routing::router::Route
294                 /// [`find_route`]: crate::routing::router::find_route
295                 retry: Option<RouteParameters>,
296 #[cfg(test)]
297                 error_code: Option<u16>,
298 #[cfg(test)]
299                 error_data: Option<Vec<u8>>,
300         },
301         /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
302         /// provide failure information for each MPP part in the payment.
303         ///
304         /// This event is provided once there are no further pending HTLCs for the payment and the
305         /// payment is no longer retryable, either due to a several-block timeout or because
306         /// [`ChannelManager::abandon_payment`] was previously called for the corresponding payment.
307         ///
308         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
309         PaymentFailed {
310                 /// The id returned by [`ChannelManager::send_payment`] and used with
311                 /// [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`].
312                 ///
313                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
314                 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
315                 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
316                 payment_id: PaymentId,
317                 /// The hash that was given to [`ChannelManager::send_payment`].
318                 ///
319                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
320                 payment_hash: PaymentHash,
321         },
322         /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
323         /// a time in the future.
324         ///
325         /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
326         PendingHTLCsForwardable {
327                 /// The minimum amount of time that should be waited prior to calling
328                 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
329                 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
330                 /// now + 5*time_forwardable).
331                 time_forwardable: Duration,
332         },
333         /// Used to indicate that an output which you should know how to spend was confirmed on chain
334         /// and is now spendable.
335         /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
336         /// counterparty spending them due to some kind of timeout. Thus, you need to store them
337         /// somewhere and spend them when you create on-chain transactions.
338         SpendableOutputs {
339                 /// The outputs which you should store as spendable by you.
340                 outputs: Vec<SpendableOutputDescriptor>,
341         },
342         /// This event is generated when a payment has been successfully forwarded through us and a
343         /// forwarding fee earned.
344         PaymentForwarded {
345                 /// The fee, in milli-satoshis, which was earned as a result of the payment.
346                 ///
347                 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
348                 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
349                 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
350                 /// claimed the full value in millisatoshis from the source. In this case,
351                 /// `claim_from_onchain_tx` will be set.
352                 ///
353                 /// If the channel which sent us the payment has been force-closed, we will claim the funds
354                 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
355                 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
356                 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
357                 /// `None`.
358                 fee_earned_msat: Option<u64>,
359                 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
360                 /// transaction.
361                 claim_from_onchain_tx: bool,
362         },
363         /// Used to indicate that a channel with the given `channel_id` is in the process of closure.
364         ChannelClosed  {
365                 /// The channel_id of the channel which has been closed. Note that on-chain transactions
366                 /// resolving the channel are likely still awaiting confirmation.
367                 channel_id: [u8; 32],
368                 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
369                 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
370                 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
371                 /// `user_channel_id` will be 0 for an inbound channel.
372                 /// This will always be zero for objects serialized with LDK versions prior to 0.0.102.
373                 ///
374                 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
375                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
376                 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
377                 user_channel_id: u64,
378                 /// The reason the channel was closed.
379                 reason: ClosureReason
380         },
381         /// Used to indicate to the user that they can abandon the funding transaction and recycle the
382         /// inputs for another purpose.
383         DiscardFunding {
384                 /// The channel_id of the channel which has been closed.
385                 channel_id: [u8; 32],
386                 /// The full transaction received from the user
387                 transaction: Transaction
388         },
389         /// Indicates that a path for an outbound payment was successful.
390         ///
391         /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
392         /// [`Event::PaymentSent`] for obtaining the payment preimage.
393         PaymentPathSuccessful {
394                 /// The id returned by [`ChannelManager::send_payment`] and used with
395                 /// [`ChannelManager::retry_payment`].
396                 ///
397                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
398                 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
399                 payment_id: PaymentId,
400                 /// The hash that was given to [`ChannelManager::send_payment`].
401                 ///
402                 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
403                 payment_hash: Option<PaymentHash>,
404                 /// The payment path that was successful.
405                 ///
406                 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
407                 path: Vec<RouteHop>,
408         },
409         /// Indicates a request to open a new channel by a peer.
410         ///
411         /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the
412         /// request, call [`ChannelManager::force_close_channel`].
413         ///
414         /// The event is only triggered when a new open channel request is received and the
415         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
416         ///
417         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
418         /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel
419         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
420         OpenChannelRequest {
421                 /// The temporary channel ID of the channel requested to be opened.
422                 ///
423                 /// When responding to the request, the `temporary_channel_id` should be passed
424                 /// back to the ChannelManager with [`ChannelManager::accept_inbound_channel`] to accept,
425                 /// or to [`ChannelManager::force_close_channel`] to reject.
426                 ///
427                 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
428                 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel
429                 temporary_channel_id: [u8; 32],
430                 /// The node_id of the counterparty requesting to open the channel.
431                 counterparty_node_id: PublicKey,
432                 /// The channel value of the requested channel.
433                 funding_satoshis: u64,
434                 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
435                 push_msat: u64,
436         },
437 }
438
439 impl Writeable for Event {
440         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
441                 match self {
442                         &Event::FundingGenerationReady { .. } => {
443                                 0u8.write(writer)?;
444                                 // We never write out FundingGenerationReady events as, upon disconnection, peers
445                                 // drop any channels which have not yet exchanged funding_signed.
446                         },
447                         &Event::PaymentReceived { ref payment_hash, ref amt, ref purpose } => {
448                                 1u8.write(writer)?;
449                                 let mut payment_secret = None;
450                                 let payment_preimage;
451                                 match &purpose {
452                                         PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
453                                                 payment_secret = Some(secret);
454                                                 payment_preimage = *preimage;
455                                         },
456                                         PaymentPurpose::SpontaneousPayment(preimage) => {
457                                                 payment_preimage = Some(*preimage);
458                                         }
459                                 }
460                                 write_tlv_fields!(writer, {
461                                         (0, payment_hash, required),
462                                         (2, payment_secret, option),
463                                         (4, amt, required),
464                                         (6, 0u64, required), // user_payment_id required for compatibility with 0.0.103 and earlier
465                                         (8, payment_preimage, option),
466                                 });
467                         },
468                         &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
469                                 2u8.write(writer)?;
470                                 write_tlv_fields!(writer, {
471                                         (0, payment_preimage, required),
472                                         (1, payment_hash, required),
473                                         (3, payment_id, option),
474                                         (5, fee_paid_msat, option),
475                                 });
476                         },
477                         &Event::PaymentPathFailed {
478                                 ref payment_id, ref payment_hash, ref rejected_by_dest, ref network_update,
479                                 ref all_paths_failed, ref path, ref short_channel_id, ref retry,
480                                 #[cfg(test)]
481                                 ref error_code,
482                                 #[cfg(test)]
483                                 ref error_data,
484                         } => {
485                                 3u8.write(writer)?;
486                                 #[cfg(test)]
487                                 error_code.write(writer)?;
488                                 #[cfg(test)]
489                                 error_data.write(writer)?;
490                                 write_tlv_fields!(writer, {
491                                         (0, payment_hash, required),
492                                         (1, network_update, option),
493                                         (2, rejected_by_dest, required),
494                                         (3, all_paths_failed, required),
495                                         (5, path, vec_type),
496                                         (7, short_channel_id, option),
497                                         (9, retry, option),
498                                         (11, payment_id, option),
499                                 });
500                         },
501                         &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
502                                 4u8.write(writer)?;
503                                 // Note that we now ignore these on the read end as we'll re-generate them in
504                                 // ChannelManager, we write them here only for backwards compatibility.
505                         },
506                         &Event::SpendableOutputs { ref outputs } => {
507                                 5u8.write(writer)?;
508                                 write_tlv_fields!(writer, {
509                                         (0, VecWriteWrapper(outputs), required),
510                                 });
511                         },
512                         &Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
513                                 7u8.write(writer)?;
514                                 write_tlv_fields!(writer, {
515                                         (0, fee_earned_msat, option),
516                                         (2, claim_from_onchain_tx, required),
517                                 });
518                         },
519                         &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
520                                 9u8.write(writer)?;
521                                 write_tlv_fields!(writer, {
522                                         (0, channel_id, required),
523                                         (1, user_channel_id, required),
524                                         (2, reason, required)
525                                 });
526                         },
527                         &Event::DiscardFunding { ref channel_id, ref transaction } => {
528                                 11u8.write(writer)?;
529                                 write_tlv_fields!(writer, {
530                                         (0, channel_id, required),
531                                         (2, transaction, required)
532                                 })
533                         },
534                         &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
535                                 13u8.write(writer)?;
536                                 write_tlv_fields!(writer, {
537                                         (0, payment_id, required),
538                                         (2, payment_hash, option),
539                                         (4, path, vec_type)
540                                 })
541                         },
542                         &Event::PaymentFailed { ref payment_id, ref payment_hash } => {
543                                 15u8.write(writer)?;
544                                 write_tlv_fields!(writer, {
545                                         (0, payment_id, required),
546                                         (2, payment_hash, required),
547                                 })
548                         },
549                         &Event::OpenChannelRequest { .. } => {
550                                 17u8.write(writer)?;
551                                 // We never write the OpenChannelRequest events as, upon disconnection, peers
552                                 // drop any channels which have not yet exchanged funding_signed.
553                         },
554                         // Note that, going forward, all new events must only write data inside of
555                         // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
556                         // data via `write_tlv_fields`.
557                 }
558                 Ok(())
559         }
560 }
561 impl MaybeReadable for Event {
562         fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
563                 match Readable::read(reader)? {
564                         // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
565                         // unlike all other events, thus we return immediately here.
566                         0u8 => Ok(None),
567                         1u8 => {
568                                 let f = || {
569                                         let mut payment_hash = PaymentHash([0; 32]);
570                                         let mut payment_preimage = None;
571                                         let mut payment_secret = None;
572                                         let mut amt = 0;
573                                         let mut _user_payment_id = None::<u64>; // For compatibility with 0.0.103 and earlier
574                                         read_tlv_fields!(reader, {
575                                                 (0, payment_hash, required),
576                                                 (2, payment_secret, option),
577                                                 (4, amt, required),
578                                                 (6, _user_payment_id, option),
579                                                 (8, payment_preimage, option),
580                                         });
581                                         let purpose = match payment_secret {
582                                                 Some(secret) => PaymentPurpose::InvoicePayment {
583                                                         payment_preimage,
584                                                         payment_secret: secret
585                                                 },
586                                                 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
587                                                 None => return Err(msgs::DecodeError::InvalidValue),
588                                         };
589                                         Ok(Some(Event::PaymentReceived {
590                                                 payment_hash,
591                                                 amt,
592                                                 purpose,
593                                         }))
594                                 };
595                                 f()
596                         },
597                         2u8 => {
598                                 let f = || {
599                                         let mut payment_preimage = PaymentPreimage([0; 32]);
600                                         let mut payment_hash = None;
601                                         let mut payment_id = None;
602                                         let mut fee_paid_msat = None;
603                                         read_tlv_fields!(reader, {
604                                                 (0, payment_preimage, required),
605                                                 (1, payment_hash, option),
606                                                 (3, payment_id, option),
607                                                 (5, fee_paid_msat, option),
608                                         });
609                                         if payment_hash.is_none() {
610                                                 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
611                                         }
612                                         Ok(Some(Event::PaymentSent {
613                                                 payment_id,
614                                                 payment_preimage,
615                                                 payment_hash: payment_hash.unwrap(),
616                                                 fee_paid_msat,
617                                         }))
618                                 };
619                                 f()
620                         },
621                         3u8 => {
622                                 let f = || {
623                                         #[cfg(test)]
624                                         let error_code = Readable::read(reader)?;
625                                         #[cfg(test)]
626                                         let error_data = Readable::read(reader)?;
627                                         let mut payment_hash = PaymentHash([0; 32]);
628                                         let mut rejected_by_dest = false;
629                                         let mut network_update = None;
630                                         let mut all_paths_failed = Some(true);
631                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
632                                         let mut short_channel_id = None;
633                                         let mut retry = None;
634                                         let mut payment_id = None;
635                                         read_tlv_fields!(reader, {
636                                                 (0, payment_hash, required),
637                                                 (1, network_update, ignorable),
638                                                 (2, rejected_by_dest, required),
639                                                 (3, all_paths_failed, option),
640                                                 (5, path, vec_type),
641                                                 (7, short_channel_id, option),
642                                                 (9, retry, option),
643                                                 (11, payment_id, option),
644                                         });
645                                         Ok(Some(Event::PaymentPathFailed {
646                                                 payment_id,
647                                                 payment_hash,
648                                                 rejected_by_dest,
649                                                 network_update,
650                                                 all_paths_failed: all_paths_failed.unwrap(),
651                                                 path: path.unwrap(),
652                                                 short_channel_id,
653                                                 retry,
654                                                 #[cfg(test)]
655                                                 error_code,
656                                                 #[cfg(test)]
657                                                 error_data,
658                                         }))
659                                 };
660                                 f()
661                         },
662                         4u8 => Ok(None),
663                         5u8 => {
664                                 let f = || {
665                                         let mut outputs = VecReadWrapper(Vec::new());
666                                         read_tlv_fields!(reader, {
667                                                 (0, outputs, required),
668                                         });
669                                         Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
670                                 };
671                                 f()
672                         },
673                         7u8 => {
674                                 let f = || {
675                                         let mut fee_earned_msat = None;
676                                         let mut claim_from_onchain_tx = false;
677                                         read_tlv_fields!(reader, {
678                                                 (0, fee_earned_msat, option),
679                                                 (2, claim_from_onchain_tx, required),
680                                         });
681                                         Ok(Some(Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx }))
682                                 };
683                                 f()
684                         },
685                         9u8 => {
686                                 let f = || {
687                                         let mut channel_id = [0; 32];
688                                         let mut reason = None;
689                                         let mut user_channel_id_opt = None;
690                                         read_tlv_fields!(reader, {
691                                                 (0, channel_id, required),
692                                                 (1, user_channel_id_opt, option),
693                                                 (2, reason, ignorable),
694                                         });
695                                         if reason.is_none() { return Ok(None); }
696                                         let user_channel_id = if let Some(id) = user_channel_id_opt { id } else { 0 };
697                                         Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: reason.unwrap() }))
698                                 };
699                                 f()
700                         },
701                         11u8 => {
702                                 let f = || {
703                                         let mut channel_id = [0; 32];
704                                         let mut transaction = Transaction{ version: 2, lock_time: 0, input: Vec::new(), output: Vec::new() };
705                                         read_tlv_fields!(reader, {
706                                                 (0, channel_id, required),
707                                                 (2, transaction, required),
708                                         });
709                                         Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
710                                 };
711                                 f()
712                         },
713                         13u8 => {
714                                 let f = || {
715                                         let mut payment_id = PaymentId([0; 32]);
716                                         let mut payment_hash = None;
717                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
718                                         read_tlv_fields!(reader, {
719                                                 (0, payment_id, required),
720                                                 (2, payment_hash, option),
721                                                 (4, path, vec_type),
722                                         });
723                                         Ok(Some(Event::PaymentPathSuccessful {
724                                                 payment_id,
725                                                 payment_hash,
726                                                 path: path.unwrap(),
727                                         }))
728                                 };
729                                 f()
730                         },
731                         15u8 => {
732                                 let f = || {
733                                         let mut payment_hash = PaymentHash([0; 32]);
734                                         let mut payment_id = PaymentId([0; 32]);
735                                         read_tlv_fields!(reader, {
736                                                 (0, payment_id, required),
737                                                 (2, payment_hash, required),
738                                         });
739                                         Ok(Some(Event::PaymentFailed {
740                                                 payment_id,
741                                                 payment_hash,
742                                         }))
743                                 };
744                                 f()
745                         },
746                         17u8 => {
747                                 // Value 17 is used for `Event::OpenChannelRequest`.
748                                 Ok(None)
749                         },
750                         // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
751                         // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
752                         // reads.
753                         x if x % 2 == 1 => {
754                                 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
755                                 // which prefixes the whole thing with a length BigSize. Because the event is
756                                 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
757                                 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
758                                 // exactly the number of bytes specified, ignoring them entirely.
759                                 let tlv_len: BigSize = Readable::read(reader)?;
760                                 FixedLengthReader::new(reader, tlv_len.0)
761                                         .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
762                                 Ok(None)
763                         },
764                         _ => Err(msgs::DecodeError::InvalidValue)
765                 }
766         }
767 }
768
769 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
770 /// broadcast to most peers).
771 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
772 #[derive(Clone, Debug)]
773 pub enum MessageSendEvent {
774         /// Used to indicate that we've accepted a channel open and should send the accept_channel
775         /// message provided to the given peer.
776         SendAcceptChannel {
777                 /// The node_id of the node which should receive this message
778                 node_id: PublicKey,
779                 /// The message which should be sent.
780                 msg: msgs::AcceptChannel,
781         },
782         /// Used to indicate that we've initiated a channel open and should send the open_channel
783         /// message provided to the given peer.
784         SendOpenChannel {
785                 /// The node_id of the node which should receive this message
786                 node_id: PublicKey,
787                 /// The message which should be sent.
788                 msg: msgs::OpenChannel,
789         },
790         /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
791         SendFundingCreated {
792                 /// The node_id of the node which should receive this message
793                 node_id: PublicKey,
794                 /// The message which should be sent.
795                 msg: msgs::FundingCreated,
796         },
797         /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
798         SendFundingSigned {
799                 /// The node_id of the node which should receive this message
800                 node_id: PublicKey,
801                 /// The message which should be sent.
802                 msg: msgs::FundingSigned,
803         },
804         /// Used to indicate that a funding_locked message should be sent to the peer with the given node_id.
805         SendFundingLocked {
806                 /// The node_id of the node which should receive these message(s)
807                 node_id: PublicKey,
808                 /// The funding_locked message which should be sent.
809                 msg: msgs::FundingLocked,
810         },
811         /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
812         SendAnnouncementSignatures {
813                 /// The node_id of the node which should receive these message(s)
814                 node_id: PublicKey,
815                 /// The announcement_signatures message which should be sent.
816                 msg: msgs::AnnouncementSignatures,
817         },
818         /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
819         /// message should be sent to the peer with the given node_id.
820         UpdateHTLCs {
821                 /// The node_id of the node which should receive these message(s)
822                 node_id: PublicKey,
823                 /// The update messages which should be sent. ALL messages in the struct should be sent!
824                 updates: msgs::CommitmentUpdate,
825         },
826         /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
827         SendRevokeAndACK {
828                 /// The node_id of the node which should receive this message
829                 node_id: PublicKey,
830                 /// The message which should be sent.
831                 msg: msgs::RevokeAndACK,
832         },
833         /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
834         SendClosingSigned {
835                 /// The node_id of the node which should receive this message
836                 node_id: PublicKey,
837                 /// The message which should be sent.
838                 msg: msgs::ClosingSigned,
839         },
840         /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
841         SendShutdown {
842                 /// The node_id of the node which should receive this message
843                 node_id: PublicKey,
844                 /// The message which should be sent.
845                 msg: msgs::Shutdown,
846         },
847         /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
848         SendChannelReestablish {
849                 /// The node_id of the node which should receive this message
850                 node_id: PublicKey,
851                 /// The message which should be sent.
852                 msg: msgs::ChannelReestablish,
853         },
854         /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
855         /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
856         ///
857         /// Note that after doing so, you very likely (unless you did so very recently) want to call
858         /// ChannelManager::broadcast_node_announcement to trigger a BroadcastNodeAnnouncement event.
859         /// This ensures that any nodes which see our channel_announcement also have a relevant
860         /// node_announcement, including relevant feature flags which may be important for routing
861         /// through or to us.
862         BroadcastChannelAnnouncement {
863                 /// The channel_announcement which should be sent.
864                 msg: msgs::ChannelAnnouncement,
865                 /// The followup channel_update which should be sent.
866                 update_msg: msgs::ChannelUpdate,
867         },
868         /// Used to indicate that a node_announcement should be broadcast to all peers.
869         BroadcastNodeAnnouncement {
870                 /// The node_announcement which should be sent.
871                 msg: msgs::NodeAnnouncement,
872         },
873         /// Used to indicate that a channel_update should be broadcast to all peers.
874         BroadcastChannelUpdate {
875                 /// The channel_update which should be sent.
876                 msg: msgs::ChannelUpdate,
877         },
878         /// Used to indicate that a channel_update should be sent to a single peer.
879         /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
880         /// private channel and we shouldn't be informing all of our peers of channel parameters.
881         SendChannelUpdate {
882                 /// The node_id of the node which should receive this message
883                 node_id: PublicKey,
884                 /// The channel_update which should be sent.
885                 msg: msgs::ChannelUpdate,
886         },
887         /// Broadcast an error downstream to be handled
888         HandleError {
889                 /// The node_id of the node which should receive this message
890                 node_id: PublicKey,
891                 /// The action which should be taken.
892                 action: msgs::ErrorAction
893         },
894         /// Query a peer for channels with funding transaction UTXOs in a block range.
895         SendChannelRangeQuery {
896                 /// The node_id of this message recipient
897                 node_id: PublicKey,
898                 /// The query_channel_range which should be sent.
899                 msg: msgs::QueryChannelRange,
900         },
901         /// Request routing gossip messages from a peer for a list of channels identified by
902         /// their short_channel_ids.
903         SendShortIdsQuery {
904                 /// The node_id of this message recipient
905                 node_id: PublicKey,
906                 /// The query_short_channel_ids which should be sent.
907                 msg: msgs::QueryShortChannelIds,
908         },
909         /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
910         /// emitted during processing of the query.
911         SendReplyChannelRange {
912                 /// The node_id of this message recipient
913                 node_id: PublicKey,
914                 /// The reply_channel_range which should be sent.
915                 msg: msgs::ReplyChannelRange,
916         },
917         /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
918         /// enable receiving gossip messages from the peer.
919         SendGossipTimestampFilter {
920                 /// The node_id of this message recipient
921                 node_id: PublicKey,
922                 /// The gossip_timestamp_filter which should be sent.
923                 msg: msgs::GossipTimestampFilter,
924         },
925 }
926
927 /// A trait indicating an object may generate message send events
928 pub trait MessageSendEventsProvider {
929         /// Gets the list of pending events which were generated by previous actions, clearing the list
930         /// in the process.
931         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
932 }
933
934 /// A trait indicating an object may generate events.
935 ///
936 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
937 ///
938 /// # Requirements
939 ///
940 /// See [`process_pending_events`] for requirements around event processing.
941 ///
942 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
943 /// event since the last invocation. The handler must either act upon the event immediately
944 /// or preserve it for later handling.
945 ///
946 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
947 /// consult the provider's documentation on the implication of processing events and how a handler
948 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
949 /// [`ChainMonitor::process_pending_events`]).
950 ///
951 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
952 /// own type(s).
953 ///
954 /// [`process_pending_events`]: Self::process_pending_events
955 /// [`handle_event`]: EventHandler::handle_event
956 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
957 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
958 pub trait EventsProvider {
959         /// Processes any events generated since the last call using the given event handler.
960         ///
961         /// Subsequent calls must only process new events. However, handlers must be capable of handling
962         /// duplicate events across process restarts. This may occur if the provider was recovered from
963         /// an old state (i.e., it hadn't been successfully persisted after processing pending events).
964         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
965 }
966
967 /// A trait implemented for objects handling events from [`EventsProvider`].
968 pub trait EventHandler {
969         /// Handles the given [`Event`].
970         ///
971         /// See [`EventsProvider`] for details that must be considered when implementing this method.
972         fn handle_event(&self, event: &Event);
973 }
974
975 impl<F> EventHandler for F where F: Fn(&Event) {
976         fn handle_event(&self, event: &Event) {
977                 self(event)
978         }
979 }
980
981 impl<T: EventHandler> EventHandler for Arc<T> {
982         fn handle_event(&self, event: &Event) {
983                 self.deref().handle_event(event)
984         }
985 }