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