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