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