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