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