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