Adds DiscardFunding event
[rust-lightning] / lightning / src / util / events.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Events are returned from various bits in the library which indicate some action must be taken
11 //! by the client.
12 //!
13 //! Because we don't have a built-in runtime, it's up to the client to call events at a time in the
14 //! future, as well as generate and broadcast funding transactions handle payment preimages and a
15 //! few other things.
16
17 use chain::keysinterface::SpendableOutputDescriptor;
18 use ln::msgs;
19 use ln::msgs::DecodeError;
20 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
21 use routing::network_graph::NetworkUpdate;
22 use util::ser::{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 use bitcoin::Transaction;
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 or the amount paid is incorrect, you should call
154         /// ChannelManager::fail_htlc_backwards to free up resources for this HTLC and avoid
155         /// network congestion.
156         /// The amount paid should be considered 'incorrect' when it is less than or more than twice
157         /// the amount expected.
158         /// If you fail to call either ChannelManager::claim_funds or
159         /// ChannelManager::fail_htlc_backwards within the HTLC's timeout, the HTLC will be
160         /// automatically failed.
161         PaymentReceived {
162                 /// The hash for which the preimage should be handed to the ChannelManager.
163                 payment_hash: PaymentHash,
164                 /// The value, in thousandths of a satoshi, that this payment is for. Note that you must
165                 /// compare this to the expected value before accepting the payment (as otherwise you are
166                 /// providing proof-of-payment for less than the value you expected!).
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         },
183         /// Indicates an outbound payment we made failed. Probably some intermediary node dropped
184         /// something. You may wish to retry with a different route.
185         PaymentPathFailed {
186                 /// The hash which was given to ChannelManager::send_payment.
187                 payment_hash: PaymentHash,
188                 /// Indicates the payment was rejected for some reason by the recipient. This implies that
189                 /// the payment has failed, not just the route in question. If this is not set, you may
190                 /// retry the payment via a different route.
191                 rejected_by_dest: bool,
192                 /// Any failure information conveyed via the Onion return packet by a node along the failed
193                 /// payment route.
194                 ///
195                 /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into
196                 /// account the update. [`NetGraphMsgHandler`] is capable of doing this.
197                 ///
198                 /// [`NetworkGraph`]: crate::routing::network_graph::NetworkGraph
199                 /// [`NetGraphMsgHandler`]: crate::routing::network_graph::NetGraphMsgHandler
200                 network_update: Option<NetworkUpdate>,
201                 /// For both single-path and multi-path payments, this is set if all paths of the payment have
202                 /// failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the
203                 /// larger MPP payment were still in flight when this event was generated.
204                 all_paths_failed: bool,
205                 /// The payment path that failed.
206                 path: Vec<RouteHop>,
207 #[cfg(test)]
208                 error_code: Option<u16>,
209 #[cfg(test)]
210                 error_data: Option<Vec<u8>>,
211         },
212         /// Used to indicate that ChannelManager::process_pending_htlc_forwards should be called at a
213         /// time in the future.
214         PendingHTLCsForwardable {
215                 /// The minimum amount of time that should be waited prior to calling
216                 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
217                 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
218                 /// now + 5*time_forwardable).
219                 time_forwardable: Duration,
220         },
221         /// Used to indicate that an output which you should know how to spend was confirmed on chain
222         /// and is now spendable.
223         /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
224         /// counterparty spending them due to some kind of timeout. Thus, you need to store them
225         /// somewhere and spend them when you create on-chain transactions.
226         SpendableOutputs {
227                 /// The outputs which you should store as spendable by you.
228                 outputs: Vec<SpendableOutputDescriptor>,
229         },
230         /// This event is generated when a payment has been successfully forwarded through us and a
231         /// forwarding fee earned.
232         PaymentForwarded {
233                 /// The fee, in milli-satoshis, which was earned as a result of the payment.
234                 ///
235                 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
236                 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
237                 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
238                 /// claimed the full value in millisatoshis from the source. In this case,
239                 /// `claim_from_onchain_tx` will be set.
240                 ///
241                 /// If the channel which sent us the payment has been force-closed, we will claim the funds
242                 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
243                 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
244                 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
245                 /// `None`.
246                 fee_earned_msat: Option<u64>,
247                 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
248                 /// transaction.
249                 claim_from_onchain_tx: bool,
250         },
251         /// Used to indicate that a channel with the given `channel_id` is in the process of closure.
252         ChannelClosed  {
253                 /// The channel_id of the channel which has been closed. Note that on-chain transactions
254                 /// resolving the channel are likely still awaiting confirmation.
255                 channel_id: [u8; 32],
256                 /// The reason the channel was closed.
257                 reason: ClosureReason
258         },
259         /// Used to indicate to the user that they can abandon the funding transaction and recycle the
260         /// inputs for another purpose.
261         DiscardFunding {
262                 /// The channel_id of the channel which has been closed.
263                 channel_id: [u8; 32],
264                 /// The full transaction received from the user
265                 transaction: Transaction
266         }
267 }
268
269 impl Writeable for Event {
270         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
271                 match self {
272                         &Event::FundingGenerationReady { .. } => {
273                                 0u8.write(writer)?;
274                                 // We never write out FundingGenerationReady events as, upon disconnection, peers
275                                 // drop any channels which have not yet exchanged funding_signed.
276                         },
277                         &Event::PaymentReceived { ref payment_hash, ref amt, ref purpose } => {
278                                 1u8.write(writer)?;
279                                 let mut payment_secret = None;
280                                 let mut user_payment_id = None;
281                                 let payment_preimage;
282                                 match &purpose {
283                                         PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret, user_payment_id: id } => {
284                                                 payment_secret = Some(secret);
285                                                 payment_preimage = *preimage;
286                                                 user_payment_id = Some(id);
287                                         },
288                                         PaymentPurpose::SpontaneousPayment(preimage) => {
289                                                 payment_preimage = Some(*preimage);
290                                         }
291                                 }
292                                 write_tlv_fields!(writer, {
293                                         (0, payment_hash, required),
294                                         (2, payment_secret, option),
295                                         (4, amt, required),
296                                         (6, user_payment_id, option),
297                                         (8, payment_preimage, option),
298                                 });
299                         },
300                         &Event::PaymentSent { ref payment_preimage } => {
301                                 2u8.write(writer)?;
302                                 write_tlv_fields!(writer, {
303                                         (0, payment_preimage, required),
304                                 });
305                         },
306                         &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update,
307                                                     ref all_paths_failed, ref path,
308                                 #[cfg(test)]
309                                 ref error_code,
310                                 #[cfg(test)]
311                                 ref error_data,
312                         } => {
313                                 3u8.write(writer)?;
314                                 #[cfg(test)]
315                                 error_code.write(writer)?;
316                                 #[cfg(test)]
317                                 error_data.write(writer)?;
318                                 write_tlv_fields!(writer, {
319                                         (0, payment_hash, required),
320                                         (1, network_update, option),
321                                         (2, rejected_by_dest, required),
322                                         (3, all_paths_failed, required),
323                                         (5, path, vec_type),
324                                 });
325                         },
326                         &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
327                                 4u8.write(writer)?;
328                                 write_tlv_fields!(writer, {});
329                                 // We don't write the time_fordwardable out at all, as we presume when the user
330                                 // deserializes us at least that much time has elapsed.
331                         },
332                         &Event::SpendableOutputs { ref outputs } => {
333                                 5u8.write(writer)?;
334                                 write_tlv_fields!(writer, {
335                                         (0, VecWriteWrapper(outputs), required),
336                                 });
337                         },
338                         &Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
339                                 7u8.write(writer)?;
340                                 write_tlv_fields!(writer, {
341                                         (0, fee_earned_msat, option),
342                                         (2, claim_from_onchain_tx, required),
343                                 });
344                         },
345                         &Event::ChannelClosed { ref channel_id, ref reason } => {
346                                 9u8.write(writer)?;
347                                 write_tlv_fields!(writer, {
348                                         (0, channel_id, required),
349                                         (2, reason, required)
350                                 });
351                         },
352                         &Event::DiscardFunding { ref channel_id, ref transaction } => {
353                                 11u8.write(writer)?;
354                                 write_tlv_fields!(writer, {
355                                         (0, channel_id, required),
356                                         (2, transaction, required)
357                                 })
358                         },
359                         // Note that, going forward, all new events must only write data inside of
360                         // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
361                         // data via `write_tlv_fields`.
362                 }
363                 Ok(())
364         }
365 }
366 impl MaybeReadable for Event {
367         fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
368                 match Readable::read(reader)? {
369                         // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
370                         // unlike all other events, thus we return immediately here.
371                         0u8 => Ok(None),
372                         1u8 => {
373                                 let f = || {
374                                         let mut payment_hash = PaymentHash([0; 32]);
375                                         let mut payment_preimage = None;
376                                         let mut payment_secret = None;
377                                         let mut amt = 0;
378                                         let mut user_payment_id = None;
379                                         read_tlv_fields!(reader, {
380                                                 (0, payment_hash, required),
381                                                 (2, payment_secret, option),
382                                                 (4, amt, required),
383                                                 (6, user_payment_id, option),
384                                                 (8, payment_preimage, option),
385                                         });
386                                         let purpose = match payment_secret {
387                                                 Some(secret) => PaymentPurpose::InvoicePayment {
388                                                         payment_preimage,
389                                                         payment_secret: secret,
390                                                         user_payment_id: if let Some(id) = user_payment_id {
391                                                                 id
392                                                         } else { return Err(msgs::DecodeError::InvalidValue) }
393                                                 },
394                                                 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
395                                                 None => return Err(msgs::DecodeError::InvalidValue),
396                                         };
397                                         Ok(Some(Event::PaymentReceived {
398                                                 payment_hash,
399                                                 amt,
400                                                 purpose,
401                                         }))
402                                 };
403                                 f()
404                         },
405                         2u8 => {
406                                 let f = || {
407                                         let mut payment_preimage = PaymentPreimage([0; 32]);
408                                         read_tlv_fields!(reader, {
409                                                 (0, payment_preimage, required),
410                                         });
411                                         Ok(Some(Event::PaymentSent {
412                                                 payment_preimage,
413                                         }))
414                                 };
415                                 f()
416                         },
417                         3u8 => {
418                                 let f = || {
419                                         #[cfg(test)]
420                                         let error_code = Readable::read(reader)?;
421                                         #[cfg(test)]
422                                         let error_data = Readable::read(reader)?;
423                                         let mut payment_hash = PaymentHash([0; 32]);
424                                         let mut rejected_by_dest = false;
425                                         let mut network_update = None;
426                                         let mut all_paths_failed = Some(true);
427                                         let mut path: Option<Vec<RouteHop>> = Some(vec![]);
428                                         read_tlv_fields!(reader, {
429                                                 (0, payment_hash, required),
430                                                 (1, network_update, ignorable),
431                                                 (2, rejected_by_dest, required),
432                                                 (3, all_paths_failed, option),
433                                                 (5, path, vec_type),
434                                         });
435                                         Ok(Some(Event::PaymentPathFailed {
436                                                 payment_hash,
437                                                 rejected_by_dest,
438                                                 network_update,
439                                                 all_paths_failed: all_paths_failed.unwrap(),
440                                                 path: path.unwrap(),
441                                                 #[cfg(test)]
442                                                 error_code,
443                                                 #[cfg(test)]
444                                                 error_data,
445                                         }))
446                                 };
447                                 f()
448                         },
449                         4u8 => {
450                                 let f = || {
451                                         read_tlv_fields!(reader, {});
452                                         Ok(Some(Event::PendingHTLCsForwardable {
453                                                 time_forwardable: Duration::from_secs(0)
454                                         }))
455                                 };
456                                 f()
457                         },
458                         5u8 => {
459                                 let f = || {
460                                         let mut outputs = VecReadWrapper(Vec::new());
461                                         read_tlv_fields!(reader, {
462                                                 (0, outputs, required),
463                                         });
464                                         Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
465                                 };
466                                 f()
467                         },
468                         7u8 => {
469                                 let f = || {
470                                         let mut fee_earned_msat = None;
471                                         let mut claim_from_onchain_tx = false;
472                                         read_tlv_fields!(reader, {
473                                                 (0, fee_earned_msat, option),
474                                                 (2, claim_from_onchain_tx, required),
475                                         });
476                                         Ok(Some(Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx }))
477                                 };
478                                 f()
479                         },
480                         9u8 => {
481                                 let mut channel_id = [0; 32];
482                                 let mut reason = None;
483                                 read_tlv_fields!(reader, {
484                                         (0, channel_id, required),
485                                         (2, reason, ignorable),
486                                 });
487                                 if reason.is_none() { return Ok(None); }
488                                 Ok(Some(Event::ChannelClosed { channel_id, reason: reason.unwrap() }))
489                         },
490                         11u8 => {
491                                 let mut channel_id = [0; 32];
492                                 let mut transaction = Transaction{ version: 2, lock_time: 0, input: Vec::new(), output: Vec::new() };
493                                 read_tlv_fields!(reader, {
494                                         (0, channel_id, required),
495                                         (2, transaction, required),
496                                 });
497                                 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
498                         },
499                         // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
500                         // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
501                         // reads.
502                         x if x % 2 == 1 => {
503                                 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
504                                 // which prefixes the whole thing with a length BigSize. Because the event is
505                                 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
506                                 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
507                                 // exactly the number of bytes specified, ignoring them entirely.
508                                 let tlv_len: BigSize = Readable::read(reader)?;
509                                 FixedLengthReader::new(reader, tlv_len.0)
510                                         .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
511                                 Ok(None)
512                         },
513                         _ => Err(msgs::DecodeError::InvalidValue)
514                 }
515         }
516 }
517
518 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
519 /// broadcast to most peers).
520 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
521 #[derive(Clone, Debug)]
522 pub enum MessageSendEvent {
523         /// Used to indicate that we've accepted a channel open and should send the accept_channel
524         /// message provided to the given peer.
525         SendAcceptChannel {
526                 /// The node_id of the node which should receive this message
527                 node_id: PublicKey,
528                 /// The message which should be sent.
529                 msg: msgs::AcceptChannel,
530         },
531         /// Used to indicate that we've initiated a channel open and should send the open_channel
532         /// message provided to the given peer.
533         SendOpenChannel {
534                 /// The node_id of the node which should receive this message
535                 node_id: PublicKey,
536                 /// The message which should be sent.
537                 msg: msgs::OpenChannel,
538         },
539         /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
540         SendFundingCreated {
541                 /// The node_id of the node which should receive this message
542                 node_id: PublicKey,
543                 /// The message which should be sent.
544                 msg: msgs::FundingCreated,
545         },
546         /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
547         SendFundingSigned {
548                 /// The node_id of the node which should receive this message
549                 node_id: PublicKey,
550                 /// The message which should be sent.
551                 msg: msgs::FundingSigned,
552         },
553         /// Used to indicate that a funding_locked message should be sent to the peer with the given node_id.
554         SendFundingLocked {
555                 /// The node_id of the node which should receive these message(s)
556                 node_id: PublicKey,
557                 /// The funding_locked message which should be sent.
558                 msg: msgs::FundingLocked,
559         },
560         /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
561         SendAnnouncementSignatures {
562                 /// The node_id of the node which should receive these message(s)
563                 node_id: PublicKey,
564                 /// The announcement_signatures message which should be sent.
565                 msg: msgs::AnnouncementSignatures,
566         },
567         /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
568         /// message should be sent to the peer with the given node_id.
569         UpdateHTLCs {
570                 /// The node_id of the node which should receive these message(s)
571                 node_id: PublicKey,
572                 /// The update messages which should be sent. ALL messages in the struct should be sent!
573                 updates: msgs::CommitmentUpdate,
574         },
575         /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
576         SendRevokeAndACK {
577                 /// The node_id of the node which should receive this message
578                 node_id: PublicKey,
579                 /// The message which should be sent.
580                 msg: msgs::RevokeAndACK,
581         },
582         /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
583         SendClosingSigned {
584                 /// The node_id of the node which should receive this message
585                 node_id: PublicKey,
586                 /// The message which should be sent.
587                 msg: msgs::ClosingSigned,
588         },
589         /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
590         SendShutdown {
591                 /// The node_id of the node which should receive this message
592                 node_id: PublicKey,
593                 /// The message which should be sent.
594                 msg: msgs::Shutdown,
595         },
596         /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
597         SendChannelReestablish {
598                 /// The node_id of the node which should receive this message
599                 node_id: PublicKey,
600                 /// The message which should be sent.
601                 msg: msgs::ChannelReestablish,
602         },
603         /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
604         /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
605         ///
606         /// Note that after doing so, you very likely (unless you did so very recently) want to call
607         /// ChannelManager::broadcast_node_announcement to trigger a BroadcastNodeAnnouncement event.
608         /// This ensures that any nodes which see our channel_announcement also have a relevant
609         /// node_announcement, including relevant feature flags which may be important for routing
610         /// through or to us.
611         BroadcastChannelAnnouncement {
612                 /// The channel_announcement which should be sent.
613                 msg: msgs::ChannelAnnouncement,
614                 /// The followup channel_update which should be sent.
615                 update_msg: msgs::ChannelUpdate,
616         },
617         /// Used to indicate that a node_announcement should be broadcast to all peers.
618         BroadcastNodeAnnouncement {
619                 /// The node_announcement which should be sent.
620                 msg: msgs::NodeAnnouncement,
621         },
622         /// Used to indicate that a channel_update should be broadcast to all peers.
623         BroadcastChannelUpdate {
624                 /// The channel_update which should be sent.
625                 msg: msgs::ChannelUpdate,
626         },
627         /// Used to indicate that a channel_update should be sent to a single peer.
628         /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
629         /// private channel and we shouldn't be informing all of our peers of channel parameters.
630         SendChannelUpdate {
631                 /// The node_id of the node which should receive this message
632                 node_id: PublicKey,
633                 /// The channel_update which should be sent.
634                 msg: msgs::ChannelUpdate,
635         },
636         /// Broadcast an error downstream to be handled
637         HandleError {
638                 /// The node_id of the node which should receive this message
639                 node_id: PublicKey,
640                 /// The action which should be taken.
641                 action: msgs::ErrorAction
642         },
643         /// Query a peer for channels with funding transaction UTXOs in a block range.
644         SendChannelRangeQuery {
645                 /// The node_id of this message recipient
646                 node_id: PublicKey,
647                 /// The query_channel_range which should be sent.
648                 msg: msgs::QueryChannelRange,
649         },
650         /// Request routing gossip messages from a peer for a list of channels identified by
651         /// their short_channel_ids.
652         SendShortIdsQuery {
653                 /// The node_id of this message recipient
654                 node_id: PublicKey,
655                 /// The query_short_channel_ids which should be sent.
656                 msg: msgs::QueryShortChannelIds,
657         },
658         /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
659         /// emitted during processing of the query.
660         SendReplyChannelRange {
661                 /// The node_id of this message recipient
662                 node_id: PublicKey,
663                 /// The reply_channel_range which should be sent.
664                 msg: msgs::ReplyChannelRange,
665         }
666 }
667
668 /// A trait indicating an object may generate message send events
669 pub trait MessageSendEventsProvider {
670         /// Gets the list of pending events which were generated by previous actions, clearing the list
671         /// in the process.
672         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
673 }
674
675 /// A trait indicating an object may generate events.
676 ///
677 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
678 ///
679 /// # Requirements
680 ///
681 /// See [`process_pending_events`] for requirements around event processing.
682 ///
683 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
684 /// event since the last invocation. The handler must either act upon the event immediately
685 /// or preserve it for later handling.
686 ///
687 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
688 /// consult the provider's documentation on the implication of processing events and how a handler
689 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
690 /// [`ChainMonitor::process_pending_events`]).
691 ///
692 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
693 /// own type(s).
694 ///
695 /// [`process_pending_events`]: Self::process_pending_events
696 /// [`handle_event`]: EventHandler::handle_event
697 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
698 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
699 pub trait EventsProvider {
700         /// Processes any events generated since the last call using the given event handler.
701         ///
702         /// Subsequent calls must only process new events. However, handlers must be capable of handling
703         /// duplicate events across process restarts. This may occur if the provider was recovered from
704         /// an old state (i.e., it hadn't been successfully persisted after processing pending events).
705         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
706 }
707
708 /// A trait implemented for objects handling events from [`EventsProvider`].
709 pub trait EventHandler {
710         /// Handles the given [`Event`].
711         ///
712         /// See [`EventsProvider`] for details that must be considered when implementing this method.
713         fn handle_event(&self, event: &Event);
714 }
715
716 impl<F> EventHandler for F where F: Fn(&Event) {
717         fn handle_event(&self, event: &Event) {
718                 self(event)
719         }
720 }