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