Refactor PaymentReceived event for keysend receives
[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 ln::msgs;
18 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
19 use chain::keysinterface::SpendableOutputDescriptor;
20 use util::ser::{Writeable, Writer, MaybeReadable, Readable, VecReadWrapper, VecWriteWrapper};
21
22 use bitcoin::blockdata::script::Script;
23
24 use bitcoin::secp256k1::key::PublicKey;
25
26 use prelude::*;
27 use core::time::Duration;
28 use core::ops::Deref;
29
30 /// Some information provided on receipt of payment depends on whether the payment received is a
31 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
32 #[derive(Clone, Debug)]
33 pub enum PaymentPurpose {
34         /// Information for receiving a payment that we generated an invoice for.
35         InvoicePayment {
36                 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
37                 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
38                 /// [`ChannelManager::claim_funds`].
39                 ///
40                 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
41                 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
42                 payment_preimage: Option<PaymentPreimage>,
43                 /// The "payment secret". This authenticates the sender to the recipient, preventing a
44                 /// number of deanonymization attacks during the routing process.
45                 /// It is provided here for your reference, however its accuracy is enforced directly by
46                 /// [`ChannelManager`] using the values you previously provided to
47                 /// [`ChannelManager::create_inbound_payment`] or
48                 /// [`ChannelManager::create_inbound_payment_for_hash`].
49                 ///
50                 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
51                 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
52                 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
53                 payment_secret: PaymentSecret,
54                 /// This is the `user_payment_id` which was provided to
55                 /// [`ChannelManager::create_inbound_payment_for_hash`] or
56                 /// [`ChannelManager::create_inbound_payment`]. It has no meaning inside of LDK and is
57                 /// simply copied here. It may be used to correlate PaymentReceived events with invoice
58                 /// metadata stored elsewhere.
59                 ///
60                 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
61                 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
62                 user_payment_id: u64,
63         },
64         /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
65         /// (the payee) providing a preimage.
66         SpontaneousPayment(PaymentPreimage),
67 }
68
69 /// An Event which you should probably take some action in response to.
70 ///
71 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
72 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
73 /// written as it makes no sense to respond to it after reconnecting to peers).
74 #[derive(Clone, Debug)]
75 pub enum Event {
76         /// Used to indicate that the client should generate a funding transaction with the given
77         /// parameters and then call ChannelManager::funding_transaction_generated.
78         /// Generated in ChannelManager message handling.
79         /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
80         /// counterparty can steal your funds!
81         FundingGenerationReady {
82                 /// The random channel_id we picked which you'll need to pass into
83                 /// ChannelManager::funding_transaction_generated.
84                 temporary_channel_id: [u8; 32],
85                 /// The value, in satoshis, that the output should have.
86                 channel_value_satoshis: u64,
87                 /// The script which should be used in the transaction output.
88                 output_script: Script,
89                 /// The value passed in to ChannelManager::create_channel
90                 user_channel_id: u64,
91         },
92         /// Indicates we've received money! Just gotta dig out that payment preimage and feed it to
93         /// ChannelManager::claim_funds to get it....
94         /// Note that if the preimage is not known or the amount paid is incorrect, you should call
95         /// ChannelManager::fail_htlc_backwards to free up resources for this HTLC and avoid
96         /// network congestion.
97         /// The amount paid should be considered 'incorrect' when it is less than or more than twice
98         /// the amount expected.
99         /// If you fail to call either ChannelManager::claim_funds or
100         /// ChannelManager::fail_htlc_backwards within the HTLC's timeout, the HTLC will be
101         /// automatically failed.
102         PaymentReceived {
103                 /// The hash for which the preimage should be handed to the ChannelManager.
104                 payment_hash: PaymentHash,
105                 /// The value, in thousandths of a satoshi, that this payment is for. Note that you must
106                 /// compare this to the expected value before accepting the payment (as otherwise you are
107                 /// providing proof-of-payment for less than the value you expected!).
108                 amt: u64,
109                 /// Information for claiming this received payment, based on whether the purpose of the
110                 /// payment is to pay an invoice or to send a spontaneous payment.
111                 purpose: PaymentPurpose,
112         },
113         /// Indicates an outbound payment we made succeeded (ie it made it all the way to its target
114         /// and we got back the payment preimage for it).
115         PaymentSent {
116                 /// The preimage to the hash given to ChannelManager::send_payment.
117                 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
118                 /// store it somehow!
119                 payment_preimage: PaymentPreimage,
120         },
121         /// Indicates an outbound payment we made failed. Probably some intermediary node dropped
122         /// something. You may wish to retry with a different route.
123         PaymentFailed {
124                 /// The hash which was given to ChannelManager::send_payment.
125                 payment_hash: PaymentHash,
126                 /// Indicates the payment was rejected for some reason by the recipient. This implies that
127                 /// the payment has failed, not just the route in question. If this is not set, you may
128                 /// retry the payment via a different route.
129                 rejected_by_dest: bool,
130 #[cfg(test)]
131                 error_code: Option<u16>,
132 #[cfg(test)]
133                 error_data: Option<Vec<u8>>,
134         },
135         /// Used to indicate that ChannelManager::process_pending_htlc_forwards should be called at a
136         /// time in the future.
137         PendingHTLCsForwardable {
138                 /// The minimum amount of time that should be waited prior to calling
139                 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
140                 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
141                 /// now + 5*time_forwardable).
142                 time_forwardable: Duration,
143         },
144         /// Used to indicate that an output which you should know how to spend was confirmed on chain
145         /// and is now spendable.
146         /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
147         /// counterparty spending them due to some kind of timeout. Thus, you need to store them
148         /// somewhere and spend them when you create on-chain transactions.
149         SpendableOutputs {
150                 /// The outputs which you should store as spendable by you.
151                 outputs: Vec<SpendableOutputDescriptor>,
152         },
153 }
154
155 impl Writeable for Event {
156         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
157                 match self {
158                         &Event::FundingGenerationReady { .. } => {
159                                 0u8.write(writer)?;
160                                 // We never write out FundingGenerationReady events as, upon disconnection, peers
161                                 // drop any channels which have not yet exchanged funding_signed.
162                         },
163                         &Event::PaymentReceived { ref payment_hash, ref amt, ref purpose } => {
164                                 1u8.write(writer)?;
165                                 let mut payment_secret = None;
166                                 let mut user_payment_id = None;
167                                 let payment_preimage;
168                                 match &purpose {
169                                         PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret, user_payment_id: id } => {
170                                                 payment_secret = Some(secret);
171                                                 payment_preimage = *preimage;
172                                                 user_payment_id = Some(id);
173                                         },
174                                         PaymentPurpose::SpontaneousPayment(preimage) => {
175                                                 payment_preimage = Some(*preimage);
176                                         }
177                                 }
178                                 write_tlv_fields!(writer, {
179                                         (0, payment_hash, required),
180                                         (2, payment_secret, option),
181                                         (4, amt, required),
182                                         (6, user_payment_id, option),
183                                         (8, payment_preimage, option),
184                                 });
185                         },
186                         &Event::PaymentSent { ref payment_preimage } => {
187                                 2u8.write(writer)?;
188                                 write_tlv_fields!(writer, {
189                                         (0, payment_preimage, required),
190                                 });
191                         },
192                         &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest,
193                                 #[cfg(test)]
194                                 ref error_code,
195                                 #[cfg(test)]
196                                 ref error_data,
197                         } => {
198                                 3u8.write(writer)?;
199                                 #[cfg(test)]
200                                 error_code.write(writer)?;
201                                 #[cfg(test)]
202                                 error_data.write(writer)?;
203                                 write_tlv_fields!(writer, {
204                                         (0, payment_hash, required),
205                                         (2, rejected_by_dest, required),
206                                 });
207                         },
208                         &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
209                                 4u8.write(writer)?;
210                                 write_tlv_fields!(writer, {});
211                                 // We don't write the time_fordwardable out at all, as we presume when the user
212                                 // deserializes us at least that much time has elapsed.
213                         },
214                         &Event::SpendableOutputs { ref outputs } => {
215                                 5u8.write(writer)?;
216                                 write_tlv_fields!(writer, {
217                                         (0, VecWriteWrapper(outputs), required),
218                                 });
219                         },
220                 }
221                 Ok(())
222         }
223 }
224 impl MaybeReadable for Event {
225         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
226                 match Readable::read(reader)? {
227                         0u8 => Ok(None),
228                         1u8 => {
229                                 let f = || {
230                                         let mut payment_hash = PaymentHash([0; 32]);
231                                         let mut payment_preimage = None;
232                                         let mut payment_secret = None;
233                                         let mut amt = 0;
234                                         let mut user_payment_id = None;
235                                         read_tlv_fields!(reader, {
236                                                 (0, payment_hash, required),
237                                                 (2, payment_secret, option),
238                                                 (4, amt, required),
239                                                 (6, user_payment_id, option),
240                                                 (8, payment_preimage, option),
241                                         });
242                                         let purpose = match payment_secret {
243                                                 Some(secret) => PaymentPurpose::InvoicePayment {
244                                                         payment_preimage,
245                                                         payment_secret: secret,
246                                                         user_payment_id: if let Some(id) = user_payment_id {
247                                                                 id
248                                                         } else { return Err(msgs::DecodeError::InvalidValue) }
249                                                 },
250                                                 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
251                                                 None => return Err(msgs::DecodeError::InvalidValue),
252                                         };
253                                         Ok(Some(Event::PaymentReceived {
254                                                 payment_hash,
255                                                 amt,
256                                                 purpose,
257                                         }))
258                                 };
259                                 f()
260                         },
261                         2u8 => {
262                                 let f = || {
263                                         let mut payment_preimage = PaymentPreimage([0; 32]);
264                                         read_tlv_fields!(reader, {
265                                                 (0, payment_preimage, required),
266                                         });
267                                         Ok(Some(Event::PaymentSent {
268                                                 payment_preimage,
269                                         }))
270                                 };
271                                 f()
272                         },
273                         3u8 => {
274                                 let f = || {
275                                         #[cfg(test)]
276                                         let error_code = Readable::read(reader)?;
277                                         #[cfg(test)]
278                                         let error_data = Readable::read(reader)?;
279                                         let mut payment_hash = PaymentHash([0; 32]);
280                                         let mut rejected_by_dest = false;
281                                         read_tlv_fields!(reader, {
282                                                 (0, payment_hash, required),
283                                                 (2, rejected_by_dest, required),
284                                         });
285                                         Ok(Some(Event::PaymentFailed {
286                                                 payment_hash,
287                                                 rejected_by_dest,
288                                                 #[cfg(test)]
289                                                 error_code,
290                                                 #[cfg(test)]
291                                                 error_data,
292                                         }))
293                                 };
294                                 f()
295                         },
296                         4u8 => {
297                                 let f = || {
298                                         read_tlv_fields!(reader, {});
299                                         Ok(Some(Event::PendingHTLCsForwardable {
300                                                 time_forwardable: Duration::from_secs(0)
301                                         }))
302                                 };
303                                 f()
304                         },
305                         5u8 => {
306                                 let f = || {
307                                         let mut outputs = VecReadWrapper(Vec::new());
308                                         read_tlv_fields!(reader, {
309                                                 (0, outputs, required),
310                                         });
311                                         Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
312                                 };
313                                 f()
314                         },
315                         _ => Err(msgs::DecodeError::InvalidValue)
316                 }
317         }
318 }
319
320 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
321 /// broadcast to most peers).
322 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
323 #[derive(Clone, Debug)]
324 pub enum MessageSendEvent {
325         /// Used to indicate that we've accepted a channel open and should send the accept_channel
326         /// message provided to the given peer.
327         SendAcceptChannel {
328                 /// The node_id of the node which should receive this message
329                 node_id: PublicKey,
330                 /// The message which should be sent.
331                 msg: msgs::AcceptChannel,
332         },
333         /// Used to indicate that we've initiated a channel open and should send the open_channel
334         /// message provided to the given peer.
335         SendOpenChannel {
336                 /// The node_id of the node which should receive this message
337                 node_id: PublicKey,
338                 /// The message which should be sent.
339                 msg: msgs::OpenChannel,
340         },
341         /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
342         SendFundingCreated {
343                 /// The node_id of the node which should receive this message
344                 node_id: PublicKey,
345                 /// The message which should be sent.
346                 msg: msgs::FundingCreated,
347         },
348         /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
349         SendFundingSigned {
350                 /// The node_id of the node which should receive this message
351                 node_id: PublicKey,
352                 /// The message which should be sent.
353                 msg: msgs::FundingSigned,
354         },
355         /// Used to indicate that a funding_locked message should be sent to the peer with the given node_id.
356         SendFundingLocked {
357                 /// The node_id of the node which should receive these message(s)
358                 node_id: PublicKey,
359                 /// The funding_locked message which should be sent.
360                 msg: msgs::FundingLocked,
361         },
362         /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
363         SendAnnouncementSignatures {
364                 /// The node_id of the node which should receive these message(s)
365                 node_id: PublicKey,
366                 /// The announcement_signatures message which should be sent.
367                 msg: msgs::AnnouncementSignatures,
368         },
369         /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
370         /// message should be sent to the peer with the given node_id.
371         UpdateHTLCs {
372                 /// The node_id of the node which should receive these message(s)
373                 node_id: PublicKey,
374                 /// The update messages which should be sent. ALL messages in the struct should be sent!
375                 updates: msgs::CommitmentUpdate,
376         },
377         /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
378         SendRevokeAndACK {
379                 /// The node_id of the node which should receive this message
380                 node_id: PublicKey,
381                 /// The message which should be sent.
382                 msg: msgs::RevokeAndACK,
383         },
384         /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
385         SendClosingSigned {
386                 /// The node_id of the node which should receive this message
387                 node_id: PublicKey,
388                 /// The message which should be sent.
389                 msg: msgs::ClosingSigned,
390         },
391         /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
392         SendShutdown {
393                 /// The node_id of the node which should receive this message
394                 node_id: PublicKey,
395                 /// The message which should be sent.
396                 msg: msgs::Shutdown,
397         },
398         /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
399         SendChannelReestablish {
400                 /// The node_id of the node which should receive this message
401                 node_id: PublicKey,
402                 /// The message which should be sent.
403                 msg: msgs::ChannelReestablish,
404         },
405         /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
406         /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
407         ///
408         /// Note that after doing so, you very likely (unless you did so very recently) want to call
409         /// ChannelManager::broadcast_node_announcement to trigger a BroadcastNodeAnnouncement event.
410         /// This ensures that any nodes which see our channel_announcement also have a relevant
411         /// node_announcement, including relevant feature flags which may be important for routing
412         /// through or to us.
413         BroadcastChannelAnnouncement {
414                 /// The channel_announcement which should be sent.
415                 msg: msgs::ChannelAnnouncement,
416                 /// The followup channel_update which should be sent.
417                 update_msg: msgs::ChannelUpdate,
418         },
419         /// Used to indicate that a node_announcement should be broadcast to all peers.
420         BroadcastNodeAnnouncement {
421                 /// The node_announcement which should be sent.
422                 msg: msgs::NodeAnnouncement,
423         },
424         /// Used to indicate that a channel_update should be broadcast to all peers.
425         BroadcastChannelUpdate {
426                 /// The channel_update which should be sent.
427                 msg: msgs::ChannelUpdate,
428         },
429         /// Used to indicate that a channel_update should be sent to a single peer.
430         /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
431         /// private channel and we shouldn't be informing all of our peers of channel parameters.
432         SendChannelUpdate {
433                 /// The node_id of the node which should receive this message
434                 node_id: PublicKey,
435                 /// The channel_update which should be sent.
436                 msg: msgs::ChannelUpdate,
437         },
438         /// Broadcast an error downstream to be handled
439         HandleError {
440                 /// The node_id of the node which should receive this message
441                 node_id: PublicKey,
442                 /// The action which should be taken.
443                 action: msgs::ErrorAction
444         },
445         /// When a payment fails we may receive updates back from the hop where it failed. In such
446         /// cases this event is generated so that we can inform the network graph of this information.
447         PaymentFailureNetworkUpdate {
448                 /// The channel/node update which should be sent to NetGraphMsgHandler
449                 update: msgs::HTLCFailChannelUpdate,
450         },
451         /// Query a peer for channels with funding transaction UTXOs in a block range.
452         SendChannelRangeQuery {
453                 /// The node_id of this message recipient
454                 node_id: PublicKey,
455                 /// The query_channel_range which should be sent.
456                 msg: msgs::QueryChannelRange,
457         },
458         /// Request routing gossip messages from a peer for a list of channels identified by
459         /// their short_channel_ids.
460         SendShortIdsQuery {
461                 /// The node_id of this message recipient
462                 node_id: PublicKey,
463                 /// The query_short_channel_ids which should be sent.
464                 msg: msgs::QueryShortChannelIds,
465         },
466         /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
467         /// emitted during processing of the query.
468         SendReplyChannelRange {
469                 /// The node_id of this message recipient
470                 node_id: PublicKey,
471                 /// The reply_channel_range which should be sent.
472                 msg: msgs::ReplyChannelRange,
473         }
474 }
475
476 /// A trait indicating an object may generate message send events
477 pub trait MessageSendEventsProvider {
478         /// Gets the list of pending events which were generated by previous actions, clearing the list
479         /// in the process.
480         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
481 }
482
483 /// A trait indicating an object may generate events.
484 ///
485 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
486 ///
487 /// # Requirements
488 ///
489 /// See [`process_pending_events`] for requirements around event processing.
490 ///
491 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
492 /// event since the last invocation. The handler must either act upon the event immediately
493 /// or preserve it for later handling.
494 ///
495 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
496 /// consult the provider's documentation on the implication of processing events and how a handler
497 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
498 /// [`ChainMonitor::process_pending_events`]).
499 ///
500 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
501 /// own type(s).
502 ///
503 /// [`process_pending_events`]: Self::process_pending_events
504 /// [`handle_event`]: EventHandler::handle_event
505 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
506 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
507 pub trait EventsProvider {
508         /// Processes any events generated since the last call using the given event handler.
509         ///
510         /// Subsequent calls must only process new events. However, handlers must be capable of handling
511         /// duplicate events across process restarts. This may occur if the provider was recovered from
512         /// an old state (i.e., it hadn't been successfully persisted after processing pending events).
513         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
514 }
515
516 /// A trait implemented for objects handling events from [`EventsProvider`].
517 pub trait EventHandler {
518         /// Handles the given [`Event`].
519         ///
520         /// See [`EventsProvider`] for details that must be considered when implementing this method.
521         fn handle_event(&self, event: Event);
522 }
523
524 impl<F> EventHandler for F where F: Fn(Event) {
525         fn handle_event(&self, event: Event) {
526                 self(event)
527         }
528 }