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