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