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