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