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