Add failing short channel id to PaymentPathFailed
[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::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, VecReadWrapper, VecWriteWrapper};
23 use routing::router::RouteHop;
24
25 use bitcoin::blockdata::script::Script;
26
27 use bitcoin::secp256k1::key::PublicKey;
28
29 use io;
30 use prelude::*;
31 use core::time::Duration;
32 use core::ops::Deref;
33
34 /// Some information provided on receipt of payment depends on whether the payment received is a
35 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
36 #[derive(Clone, Debug)]
37 pub enum PaymentPurpose {
38         /// Information for receiving a payment that we generated an invoice for.
39         InvoicePayment {
40                 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
41                 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
42                 /// [`ChannelManager::claim_funds`].
43                 ///
44                 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
45                 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
46                 payment_preimage: Option<PaymentPreimage>,
47                 /// The "payment secret". This authenticates the sender to the recipient, preventing a
48                 /// number of deanonymization attacks during the routing process.
49                 /// It is provided here for your reference, however its accuracy is enforced directly by
50                 /// [`ChannelManager`] using the values you previously provided to
51                 /// [`ChannelManager::create_inbound_payment`] or
52                 /// [`ChannelManager::create_inbound_payment_for_hash`].
53                 ///
54                 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
55                 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
56                 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
57                 payment_secret: PaymentSecret,
58                 /// This is the `user_payment_id` which was provided to
59                 /// [`ChannelManager::create_inbound_payment_for_hash`] or
60                 /// [`ChannelManager::create_inbound_payment`]. It has no meaning inside of LDK and is
61                 /// simply copied here. It may be used to correlate PaymentReceived events with invoice
62                 /// metadata stored elsewhere.
63                 ///
64                 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
65                 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
66                 user_payment_id: u64,
67         },
68         /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
69         /// (the payee) providing a preimage.
70         SpontaneousPayment(PaymentPreimage),
71 }
72
73 #[derive(Clone, Debug, PartialEq)]
74 /// The reason the channel was closed. See individual variants more details.
75 pub enum ClosureReason {
76         /// Closure generated from receiving a peer error message.
77         ///
78         /// Our counterparty may have broadcasted their latest commitment state, and we have
79         /// as well.
80         CounterpartyForceClosed {
81                 /// The error which the peer sent us.
82                 ///
83                 /// The string should be sanitized before it is used (e.g emitted to logs
84                 /// or printed to stdout). Otherwise, a well crafted error message may exploit
85                 /// a security vulnerability in the terminal emulator or the logging subsystem.
86                 peer_msg: String,
87         },
88         /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
89         ///
90         /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
91         HolderForceClosed,
92         /// The channel was closed after negotiating a cooperative close and we've now broadcasted
93         /// the cooperative close transaction. Note the shutdown may have been initiated by us.
94         //TODO: split between CounterpartyInitiated/LocallyInitiated
95         CooperativeClosure,
96         /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
97         /// commitment transaction came from our counterparty, but it may also have come from
98         /// a copy of our own `ChannelMonitor`.
99         CommitmentTxConfirmed,
100         /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
101         ProcessingError {
102                 /// A developer-readable error message which we generated.
103                 err: String,
104         },
105         /// The `PeerManager` informed us that we've disconnected from the peer. We close channels
106         /// if the `PeerManager` informed us that it is unlikely we'll be able to connect to the
107         /// peer again in the future or if the peer disconnected before we finished negotiating
108         /// the channel open. The first case may be caused by incompatible features which our
109         /// counterparty, or we, require.
110         //TODO: split between PeerUnconnectable/PeerDisconnected ?
111         DisconnectedPeer,
112         /// Closure generated from `ChannelManager::read` if the ChannelMonitor is newer than
113         /// the ChannelManager deserialized.
114         OutdatedChannelManager
115 }
116
117 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
118         (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
119         (2, HolderForceClosed) => {},
120         (6, CommitmentTxConfirmed) => {},
121         (4, CooperativeClosure) => {},
122         (8, ProcessingError) => { (1, err, required) },
123         (10, DisconnectedPeer) => {},
124         (12, OutdatedChannelManager) => {},
125 );
126
127 /// An Event which you should probably take some action in response to.
128 ///
129 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
130 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
131 /// written as it makes no sense to respond to it after reconnecting to peers).
132 #[derive(Clone, Debug)]
133 pub enum Event {
134         /// Used to indicate that the client should generate a funding transaction with the given
135         /// parameters and then call ChannelManager::funding_transaction_generated.
136         /// Generated in ChannelManager message handling.
137         /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
138         /// counterparty can steal your funds!
139         FundingGenerationReady {
140                 /// The random channel_id we picked which you'll need to pass into
141                 /// ChannelManager::funding_transaction_generated.
142                 temporary_channel_id: [u8; 32],
143                 /// The value, in satoshis, that the output should have.
144                 channel_value_satoshis: u64,
145                 /// The script which should be used in the transaction output.
146                 output_script: Script,
147                 /// The value passed in to ChannelManager::create_channel
148                 user_channel_id: u64,
149         },
150         /// Indicates we've received money! Just gotta dig out that payment preimage and feed it to
151         /// ChannelManager::claim_funds to get it....
152         /// Note that if the preimage is not known or the amount paid is incorrect, you should call
153         /// ChannelManager::fail_htlc_backwards to free up resources for this HTLC and avoid
154         /// network congestion.
155         /// The amount paid should be considered 'incorrect' when it is less than or more than twice
156         /// the amount expected.
157         /// If you fail to call either ChannelManager::claim_funds or
158         /// ChannelManager::fail_htlc_backwards within the HTLC's timeout, the HTLC will be
159         /// automatically failed.
160         PaymentReceived {
161                 /// The hash for which the preimage should be handed to the ChannelManager.
162                 payment_hash: PaymentHash,
163                 /// The value, in thousandths of a satoshi, that this payment is for. Note that you must
164                 /// compare this to the expected value before accepting the payment (as otherwise you are
165                 /// providing proof-of-payment for less than the value you expected!).
166                 amt: u64,
167                 /// Information for claiming this received payment, based on whether the purpose of the
168                 /// payment is to pay an invoice or to send a spontaneous payment.
169                 purpose: PaymentPurpose,
170         },
171         /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
172         /// and we got back the payment preimage for it).
173         ///
174         /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
175         /// event. In this situation, you SHOULD treat this payment as having succeeded.
176         PaymentSent {
177                 /// The preimage to the hash given to ChannelManager::send_payment.
178                 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
179                 /// store it somehow!
180                 payment_preimage: PaymentPreimage,
181         },
182         /// Indicates an outbound payment we made failed. Probably some intermediary node dropped
183         /// something. You may wish to retry with a different route.
184         PaymentPathFailed {
185                 /// The hash which was given to ChannelManager::send_payment.
186                 payment_hash: PaymentHash,
187                 /// Indicates the payment was rejected for some reason by the recipient. This implies that
188                 /// the payment has failed, not just the route in question. If this is not set, you may
189                 /// retry the payment via a different route.
190                 rejected_by_dest: bool,
191                 /// Any failure information conveyed via the Onion return packet by a node along the failed
192                 /// payment route.
193                 ///
194                 /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into
195                 /// account the update. [`NetGraphMsgHandler`] is capable of doing this.
196                 ///
197                 /// [`NetworkGraph`]: crate::routing::network_graph::NetworkGraph
198                 /// [`NetGraphMsgHandler`]: crate::routing::network_graph::NetGraphMsgHandler
199                 network_update: Option<NetworkUpdate>,
200                 /// For both single-path and multi-path payments, this is set if all paths of the payment have
201                 /// failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the
202                 /// larger MPP payment were still in flight when this event was generated.
203                 all_paths_failed: bool,
204                 /// The payment path that failed.
205                 path: Vec<RouteHop>,
206                 /// The channel responsible for the failed payment path.
207                 ///
208                 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
209                 /// retried. May be `None` for older [`Event`] serializations.
210                 short_channel_id: Option<u64>,
211 #[cfg(test)]
212                 error_code: Option<u16>,
213 #[cfg(test)]
214                 error_data: Option<Vec<u8>>,
215         },
216         /// Used to indicate that ChannelManager::process_pending_htlc_forwards should be called at a
217         /// time in the future.
218         PendingHTLCsForwardable {
219                 /// The minimum amount of time that should be waited prior to calling
220                 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
221                 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
222                 /// now + 5*time_forwardable).
223                 time_forwardable: Duration,
224         },
225         /// Used to indicate that an output which you should know how to spend was confirmed on chain
226         /// and is now spendable.
227         /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
228         /// counterparty spending them due to some kind of timeout. Thus, you need to store them
229         /// somewhere and spend them when you create on-chain transactions.
230         SpendableOutputs {
231                 /// The outputs which you should store as spendable by you.
232                 outputs: Vec<SpendableOutputDescriptor>,
233         },
234         /// This event is generated when a payment has been successfully forwarded through us and a
235         /// forwarding fee earned.
236         PaymentForwarded {
237                 /// The fee, in milli-satoshis, which was earned as a result of the payment.
238                 ///
239                 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
240                 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
241                 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
242                 /// claimed the full value in millisatoshis from the source. In this case,
243                 /// `claim_from_onchain_tx` will be set.
244                 ///
245                 /// If the channel which sent us the payment has been force-closed, we will claim the funds
246                 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
247                 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
248                 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
249                 /// `None`.
250                 fee_earned_msat: Option<u64>,
251                 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
252                 /// transaction.
253                 claim_from_onchain_tx: bool,
254         },
255         /// Used to indicate that a channel with the given `channel_id` is in the process of closure.
256         ChannelClosed  {
257                 /// The channel_id of the channel which has been closed. Note that on-chain transactions
258                 /// resolving the channel are likely still awaiting confirmation.
259                 channel_id: [u8; 32],
260                 /// The reason the channel was closed.
261                 reason: ClosureReason
262         }
263 }
264
265 impl Writeable for Event {
266         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
267                 match self {
268                         &Event::FundingGenerationReady { .. } => {
269                                 0u8.write(writer)?;
270                                 // We never write out FundingGenerationReady events as, upon disconnection, peers
271                                 // drop any channels which have not yet exchanged funding_signed.
272                         },
273                         &Event::PaymentReceived { ref payment_hash, ref amt, ref purpose } => {
274                                 1u8.write(writer)?;
275                                 let mut payment_secret = None;
276                                 let mut user_payment_id = None;
277                                 let payment_preimage;
278                                 match &purpose {
279                                         PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret, user_payment_id: id } => {
280                                                 payment_secret = Some(secret);
281                                                 payment_preimage = *preimage;
282                                                 user_payment_id = Some(id);
283                                         },
284                                         PaymentPurpose::SpontaneousPayment(preimage) => {
285                                                 payment_preimage = Some(*preimage);
286                                         }
287                                 }
288                                 write_tlv_fields!(writer, {
289                                         (0, payment_hash, required),
290                                         (2, payment_secret, option),
291                                         (4, amt, required),
292                                         (6, user_payment_id, option),
293                                         (8, payment_preimage, option),
294                                 });
295                         },
296                         &Event::PaymentSent { ref payment_preimage } => {
297                                 2u8.write(writer)?;
298                                 write_tlv_fields!(writer, {
299                                         (0, payment_preimage, required),
300                                 });
301                         },
302                         &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update,
303                                                     ref all_paths_failed, ref path, ref short_channel_id,
304                                 #[cfg(test)]
305                                 ref error_code,
306                                 #[cfg(test)]
307                                 ref error_data,
308                         } => {
309                                 3u8.write(writer)?;
310                                 #[cfg(test)]
311                                 error_code.write(writer)?;
312                                 #[cfg(test)]
313                                 error_data.write(writer)?;
314                                 write_tlv_fields!(writer, {
315                                         (0, payment_hash, required),
316                                         (1, network_update, option),
317                                         (2, rejected_by_dest, required),
318                                         (3, all_paths_failed, required),
319                                         (5, path, vec_type),
320                                         (7, short_channel_id, option),
321                                 });
322                         },
323                         &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
324                                 4u8.write(writer)?;
325                                 write_tlv_fields!(writer, {});
326                                 // We don't write the time_fordwardable out at all, as we presume when the user
327                                 // deserializes us at least that much time has elapsed.
328                         },
329                         &Event::SpendableOutputs { ref outputs } => {
330                                 5u8.write(writer)?;
331                                 write_tlv_fields!(writer, {
332                                         (0, VecWriteWrapper(outputs), required),
333                                 });
334                         },
335                         &Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
336                                 7u8.write(writer)?;
337                                 write_tlv_fields!(writer, {
338                                         (0, fee_earned_msat, option),
339                                         (2, claim_from_onchain_tx, required),
340                                 });
341                         },
342                         &Event::ChannelClosed { ref channel_id, ref reason } => {
343                                 9u8.write(writer)?;
344                                 write_tlv_fields!(writer, {
345                                         (0, channel_id, required),
346                                         (2, reason, required)
347                                 });
348                         },
349                         // Note that, going forward, all new events must only write data inside of
350                         // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
351                         // data via `write_tlv_fields`.
352                 }
353                 Ok(())
354         }
355 }
356 impl MaybeReadable for Event {
357         fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
358                 match Readable::read(reader)? {
359                         // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
360                         // unlike all other events, thus we return immediately here.
361                         0u8 => Ok(None),
362                         1u8 => {
363                                 let f = || {
364                                         let mut payment_hash = PaymentHash([0; 32]);
365                                         let mut payment_preimage = None;
366                                         let mut payment_secret = None;
367                                         let mut amt = 0;
368                                         let mut user_payment_id = None;
369                                         read_tlv_fields!(reader, {
370                                                 (0, payment_hash, required),
371                                                 (2, payment_secret, option),
372                                                 (4, amt, required),
373                                                 (6, user_payment_id, option),
374                                                 (8, payment_preimage, option),
375                                         });
376                                         let purpose = match payment_secret {
377                                                 Some(secret) => PaymentPurpose::InvoicePayment {
378                                                         payment_preimage,
379                                                         payment_secret: secret,
380                                                         user_payment_id: if let Some(id) = user_payment_id {
381                                                                 id
382                                                         } else { return Err(msgs::DecodeError::InvalidValue) }
383                                                 },
384                                                 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
385                                                 None => return Err(msgs::DecodeError::InvalidValue),
386                                         };
387                                         Ok(Some(Event::PaymentReceived {
388                                                 payment_hash,
389                                                 amt,
390                                                 purpose,
391                                         }))
392                                 };
393                                 f()
394                         },
395                         2u8 => {
396                                 let f = || {
397                                         let mut payment_preimage = PaymentPreimage([0; 32]);
398                                         read_tlv_fields!(reader, {
399                                                 (0, payment_preimage, required),
400                                         });
401                                         Ok(Some(Event::PaymentSent {
402                                                 payment_preimage,
403                                         }))
404                                 };
405                                 f()
406                         },
407                         3u8 => {
408                                 let f = || {
409                                         #[cfg(test)]
410                                         let error_code = Readable::read(reader)?;
411                                         #[cfg(test)]
412                                         let error_data = Readable::read(reader)?;
413                                         let mut payment_hash = PaymentHash([0; 32]);
414                                         let mut rejected_by_dest = false;
415                                         let mut network_update = None;
416                                         let mut all_paths_failed = Some(true);
417                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
418                                         let mut short_channel_id = None;
419                                         read_tlv_fields!(reader, {
420                                                 (0, payment_hash, required),
421                                                 (1, network_update, ignorable),
422                                                 (2, rejected_by_dest, required),
423                                                 (3, all_paths_failed, option),
424                                                 (5, path, vec_type),
425                                                 (7, short_channel_id, ignorable),
426                                         });
427                                         Ok(Some(Event::PaymentPathFailed {
428                                                 payment_hash,
429                                                 rejected_by_dest,
430                                                 network_update,
431                                                 all_paths_failed: all_paths_failed.unwrap(),
432                                                 path: path.unwrap(),
433                                                 short_channel_id,
434                                                 #[cfg(test)]
435                                                 error_code,
436                                                 #[cfg(test)]
437                                                 error_data,
438                                         }))
439                                 };
440                                 f()
441                         },
442                         4u8 => {
443                                 let f = || {
444                                         read_tlv_fields!(reader, {});
445                                         Ok(Some(Event::PendingHTLCsForwardable {
446                                                 time_forwardable: Duration::from_secs(0)
447                                         }))
448                                 };
449                                 f()
450                         },
451                         5u8 => {
452                                 let f = || {
453                                         let mut outputs = VecReadWrapper(Vec::new());
454                                         read_tlv_fields!(reader, {
455                                                 (0, outputs, required),
456                                         });
457                                         Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
458                                 };
459                                 f()
460                         },
461                         7u8 => {
462                                 let f = || {
463                                         let mut fee_earned_msat = None;
464                                         let mut claim_from_onchain_tx = false;
465                                         read_tlv_fields!(reader, {
466                                                 (0, fee_earned_msat, option),
467                                                 (2, claim_from_onchain_tx, required),
468                                         });
469                                         Ok(Some(Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx }))
470                                 };
471                                 f()
472                         },
473                         9u8 => {
474                                 let mut channel_id = [0; 32];
475                                 let mut reason = None;
476                                 read_tlv_fields!(reader, {
477                                         (0, channel_id, required),
478                                         (2, reason, ignorable),
479                                 });
480                                 if reason.is_none() { return Ok(None); }
481                                 Ok(Some(Event::ChannelClosed { channel_id, reason: reason.unwrap() }))
482                         },
483                         // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
484                         // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
485                         // reads.
486                         x if x % 2 == 1 => {
487                                 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
488                                 // which prefixes the whole thing with a length BigSize. Because the event is
489                                 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
490                                 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
491                                 // exactly the number of bytes specified, ignoring them entirely.
492                                 let tlv_len: BigSize = Readable::read(reader)?;
493                                 FixedLengthReader::new(reader, tlv_len.0)
494                                         .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
495                                 Ok(None)
496                         },
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 }