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