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