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