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