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