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