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