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
17 use chain::keysinterface::SpendableOutputDescriptor;
19 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
20 use routing::network_graph::NetworkUpdate;
21 use util::ser::{Writeable, Writer, MaybeReadable, Readable, VecReadWrapper, VecWriteWrapper};
23 use bitcoin::blockdata::script::Script;
25 use bitcoin::secp256k1::key::PublicKey;
29 use core::time::Duration;
32 /// Some information provided on receipt of payment depends on whether the payment received is a
33 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
34 #[derive(Clone, Debug)]
35 pub enum PaymentPurpose {
36 /// Information for receiving a payment that we generated an invoice for.
38 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
39 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
40 /// [`ChannelManager::claim_funds`].
42 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
43 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
44 payment_preimage: Option<PaymentPreimage>,
45 /// The "payment secret". This authenticates the sender to the recipient, preventing a
46 /// number of deanonymization attacks during the routing process.
47 /// It is provided here for your reference, however its accuracy is enforced directly by
48 /// [`ChannelManager`] using the values you previously provided to
49 /// [`ChannelManager::create_inbound_payment`] or
50 /// [`ChannelManager::create_inbound_payment_for_hash`].
52 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
53 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
54 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
55 payment_secret: PaymentSecret,
56 /// This is the `user_payment_id` which was provided to
57 /// [`ChannelManager::create_inbound_payment_for_hash`] or
58 /// [`ChannelManager::create_inbound_payment`]. It has no meaning inside of LDK and is
59 /// simply copied here. It may be used to correlate PaymentReceived events with invoice
60 /// metadata stored elsewhere.
62 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
63 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
66 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
67 /// (the payee) providing a preimage.
68 SpontaneousPayment(PaymentPreimage),
71 /// An Event which you should probably take some action in response to.
73 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
74 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
75 /// written as it makes no sense to respond to it after reconnecting to peers).
76 #[derive(Clone, Debug)]
78 /// Used to indicate that the client should generate a funding transaction with the given
79 /// parameters and then call ChannelManager::funding_transaction_generated.
80 /// Generated in ChannelManager message handling.
81 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
82 /// counterparty can steal your funds!
83 FundingGenerationReady {
84 /// The random channel_id we picked which you'll need to pass into
85 /// ChannelManager::funding_transaction_generated.
86 temporary_channel_id: [u8; 32],
87 /// The value, in satoshis, that the output should have.
88 channel_value_satoshis: u64,
89 /// The script which should be used in the transaction output.
90 output_script: Script,
91 /// The value passed in to ChannelManager::create_channel
94 /// Indicates we've received money! Just gotta dig out that payment preimage and feed it to
95 /// ChannelManager::claim_funds to get it....
96 /// Note that if the preimage is not known or the amount paid is incorrect, you should call
97 /// ChannelManager::fail_htlc_backwards to free up resources for this HTLC and avoid
98 /// network congestion.
99 /// The amount paid should be considered 'incorrect' when it is less than or more than twice
100 /// the amount expected.
101 /// If you fail to call either ChannelManager::claim_funds or
102 /// ChannelManager::fail_htlc_backwards within the HTLC's timeout, the HTLC will be
103 /// automatically failed.
105 /// The hash for which the preimage should be handed to the ChannelManager.
106 payment_hash: PaymentHash,
107 /// The value, in thousandths of a satoshi, that this payment is for. Note that you must
108 /// compare this to the expected value before accepting the payment (as otherwise you are
109 /// providing proof-of-payment for less than the value you expected!).
111 /// Information for claiming this received payment, based on whether the purpose of the
112 /// payment is to pay an invoice or to send a spontaneous payment.
113 purpose: PaymentPurpose,
115 /// Indicates an outbound payment we made succeeded (ie it made it all the way to its target
116 /// and we got back the payment preimage for it).
118 /// The preimage to the hash given to ChannelManager::send_payment.
119 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
120 /// store it somehow!
121 payment_preimage: PaymentPreimage,
123 /// Indicates an outbound payment we made failed. Probably some intermediary node dropped
124 /// something. You may wish to retry with a different route.
126 /// The hash which was given to ChannelManager::send_payment.
127 payment_hash: PaymentHash,
128 /// Indicates the payment was rejected for some reason by the recipient. This implies that
129 /// the payment has failed, not just the route in question. If this is not set, you may
130 /// retry the payment via a different route.
131 rejected_by_dest: bool,
132 /// Any failure information conveyed via the Onion return packet by a node along the failed
135 /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into
136 /// account the update. [`NetGraphMsgHandler`] is capable of doing this.
138 /// [`NetworkGraph`]: crate::routing::network_graph::NetworkGraph
139 /// [`NetGraphMsgHandler`]: crate::routing::network_graph::NetGraphMsgHandler
140 network_update: Option<NetworkUpdate>,
142 error_code: Option<u16>,
144 error_data: Option<Vec<u8>>,
146 /// Used to indicate that ChannelManager::process_pending_htlc_forwards should be called at a
147 /// time in the future.
148 PendingHTLCsForwardable {
149 /// The minimum amount of time that should be waited prior to calling
150 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
151 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
152 /// now + 5*time_forwardable).
153 time_forwardable: Duration,
155 /// Used to indicate that an output which you should know how to spend was confirmed on chain
156 /// and is now spendable.
157 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
158 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
159 /// somewhere and spend them when you create on-chain transactions.
161 /// The outputs which you should store as spendable by you.
162 outputs: Vec<SpendableOutputDescriptor>,
164 /// This event is generated when a payment has been successfully forwarded through us and a
165 /// forwarding fee earned.
167 /// The fee, in milli-satoshis, which was earned as a result of the payment.
169 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
170 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
171 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
172 /// claimed the full value in millisatoshis from the source. In this case,
173 /// `claim_from_onchain_tx` will be set.
175 /// If the channel which sent us the payment has been force-closed, we will claim the funds
176 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
177 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
178 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
180 fee_earned_msat: Option<u64>,
181 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
183 claim_from_onchain_tx: bool,
187 impl Writeable for Event {
188 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
190 &Event::FundingGenerationReady { .. } => {
192 // We never write out FundingGenerationReady events as, upon disconnection, peers
193 // drop any channels which have not yet exchanged funding_signed.
195 &Event::PaymentReceived { ref payment_hash, ref amt, ref purpose } => {
197 let mut payment_secret = None;
198 let mut user_payment_id = None;
199 let payment_preimage;
201 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret, user_payment_id: id } => {
202 payment_secret = Some(secret);
203 payment_preimage = *preimage;
204 user_payment_id = Some(id);
206 PaymentPurpose::SpontaneousPayment(preimage) => {
207 payment_preimage = Some(*preimage);
210 write_tlv_fields!(writer, {
211 (0, payment_hash, required),
212 (2, payment_secret, option),
214 (6, user_payment_id, option),
215 (8, payment_preimage, option),
218 &Event::PaymentSent { ref payment_preimage } => {
220 write_tlv_fields!(writer, {
221 (0, payment_preimage, required),
224 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref network_update,
232 error_code.write(writer)?;
234 error_data.write(writer)?;
235 write_tlv_fields!(writer, {
236 (0, payment_hash, required),
237 (1, network_update, option),
238 (2, rejected_by_dest, required),
241 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
243 // Note that we now ignore these on the read end as we'll re-generate them in
244 // ChannelManager, we write them here only for backwards compatibility.
246 &Event::SpendableOutputs { ref outputs } => {
248 write_tlv_fields!(writer, {
249 (0, VecWriteWrapper(outputs), required),
252 &Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
254 write_tlv_fields!(writer, {
255 (0, fee_earned_msat, option),
256 (2, claim_from_onchain_tx, required),
263 impl MaybeReadable for Event {
264 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
265 match Readable::read(reader)? {
269 let mut payment_hash = PaymentHash([0; 32]);
270 let mut payment_preimage = None;
271 let mut payment_secret = None;
273 let mut user_payment_id = None;
274 read_tlv_fields!(reader, {
275 (0, payment_hash, required),
276 (2, payment_secret, option),
278 (6, user_payment_id, option),
279 (8, payment_preimage, option),
281 let purpose = match payment_secret {
282 Some(secret) => PaymentPurpose::InvoicePayment {
284 payment_secret: secret,
285 user_payment_id: if let Some(id) = user_payment_id {
287 } else { return Err(msgs::DecodeError::InvalidValue) }
289 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
290 None => return Err(msgs::DecodeError::InvalidValue),
292 Ok(Some(Event::PaymentReceived {
302 let mut payment_preimage = PaymentPreimage([0; 32]);
303 read_tlv_fields!(reader, {
304 (0, payment_preimage, required),
306 Ok(Some(Event::PaymentSent {
315 let error_code = Readable::read(reader)?;
317 let error_data = Readable::read(reader)?;
318 let mut payment_hash = PaymentHash([0; 32]);
319 let mut rejected_by_dest = false;
320 let mut network_update = None;
321 read_tlv_fields!(reader, {
322 (0, payment_hash, required),
323 (1, network_update, ignorable),
324 (2, rejected_by_dest, required),
326 Ok(Some(Event::PaymentFailed {
341 let mut outputs = VecReadWrapper(Vec::new());
342 read_tlv_fields!(reader, {
343 (0, outputs, required),
345 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
351 let mut fee_earned_msat = None;
352 let mut claim_from_onchain_tx = false;
353 read_tlv_fields!(reader, {
354 (0, fee_earned_msat, option),
355 (2, claim_from_onchain_tx, required),
357 Ok(Some(Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx }))
361 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
362 x if x % 2 == 1 => Ok(None),
363 _ => Err(msgs::DecodeError::InvalidValue)
368 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
369 /// broadcast to most peers).
370 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
371 #[derive(Clone, Debug)]
372 pub enum MessageSendEvent {
373 /// Used to indicate that we've accepted a channel open and should send the accept_channel
374 /// message provided to the given peer.
376 /// The node_id of the node which should receive this message
378 /// The message which should be sent.
379 msg: msgs::AcceptChannel,
381 /// Used to indicate that we've initiated a channel open and should send the open_channel
382 /// message provided to the given peer.
384 /// The node_id of the node which should receive this message
386 /// The message which should be sent.
387 msg: msgs::OpenChannel,
389 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
391 /// The node_id of the node which should receive this message
393 /// The message which should be sent.
394 msg: msgs::FundingCreated,
396 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
398 /// The node_id of the node which should receive this message
400 /// The message which should be sent.
401 msg: msgs::FundingSigned,
403 /// Used to indicate that a funding_locked message should be sent to the peer with the given node_id.
405 /// The node_id of the node which should receive these message(s)
407 /// The funding_locked message which should be sent.
408 msg: msgs::FundingLocked,
410 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
411 SendAnnouncementSignatures {
412 /// The node_id of the node which should receive these message(s)
414 /// The announcement_signatures message which should be sent.
415 msg: msgs::AnnouncementSignatures,
417 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
418 /// message should be sent to the peer with the given node_id.
420 /// The node_id of the node which should receive these message(s)
422 /// The update messages which should be sent. ALL messages in the struct should be sent!
423 updates: msgs::CommitmentUpdate,
425 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
427 /// The node_id of the node which should receive this message
429 /// The message which should be sent.
430 msg: msgs::RevokeAndACK,
432 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
434 /// The node_id of the node which should receive this message
436 /// The message which should be sent.
437 msg: msgs::ClosingSigned,
439 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
441 /// The node_id of the node which should receive this message
443 /// The message which should be sent.
446 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
447 SendChannelReestablish {
448 /// The node_id of the node which should receive this message
450 /// The message which should be sent.
451 msg: msgs::ChannelReestablish,
453 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
454 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
456 /// Note that after doing so, you very likely (unless you did so very recently) want to call
457 /// ChannelManager::broadcast_node_announcement to trigger a BroadcastNodeAnnouncement event.
458 /// This ensures that any nodes which see our channel_announcement also have a relevant
459 /// node_announcement, including relevant feature flags which may be important for routing
460 /// through or to us.
461 BroadcastChannelAnnouncement {
462 /// The channel_announcement which should be sent.
463 msg: msgs::ChannelAnnouncement,
464 /// The followup channel_update which should be sent.
465 update_msg: msgs::ChannelUpdate,
467 /// Used to indicate that a node_announcement should be broadcast to all peers.
468 BroadcastNodeAnnouncement {
469 /// The node_announcement which should be sent.
470 msg: msgs::NodeAnnouncement,
472 /// Used to indicate that a channel_update should be broadcast to all peers.
473 BroadcastChannelUpdate {
474 /// The channel_update which should be sent.
475 msg: msgs::ChannelUpdate,
477 /// Used to indicate that a channel_update should be sent to a single peer.
478 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
479 /// private channel and we shouldn't be informing all of our peers of channel parameters.
481 /// The node_id of the node which should receive this message
483 /// The channel_update which should be sent.
484 msg: msgs::ChannelUpdate,
486 /// Broadcast an error downstream to be handled
488 /// The node_id of the node which should receive this message
490 /// The action which should be taken.
491 action: msgs::ErrorAction
493 /// Query a peer for channels with funding transaction UTXOs in a block range.
494 SendChannelRangeQuery {
495 /// The node_id of this message recipient
497 /// The query_channel_range which should be sent.
498 msg: msgs::QueryChannelRange,
500 /// Request routing gossip messages from a peer for a list of channels identified by
501 /// their short_channel_ids.
503 /// The node_id of this message recipient
505 /// The query_short_channel_ids which should be sent.
506 msg: msgs::QueryShortChannelIds,
508 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
509 /// emitted during processing of the query.
510 SendReplyChannelRange {
511 /// The node_id of this message recipient
513 /// The reply_channel_range which should be sent.
514 msg: msgs::ReplyChannelRange,
518 /// A trait indicating an object may generate message send events
519 pub trait MessageSendEventsProvider {
520 /// Gets the list of pending events which were generated by previous actions, clearing the list
522 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
525 /// A trait indicating an object may generate events.
527 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
531 /// See [`process_pending_events`] for requirements around event processing.
533 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
534 /// event since the last invocation. The handler must either act upon the event immediately
535 /// or preserve it for later handling.
537 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
538 /// consult the provider's documentation on the implication of processing events and how a handler
539 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
540 /// [`ChainMonitor::process_pending_events`]).
542 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
545 /// [`process_pending_events`]: Self::process_pending_events
546 /// [`handle_event`]: EventHandler::handle_event
547 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
548 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
549 pub trait EventsProvider {
550 /// Processes any events generated since the last call using the given event handler.
552 /// Subsequent calls must only process new events. However, handlers must be capable of handling
553 /// duplicate events across process restarts. This may occur if the provider was recovered from
554 /// an old state (i.e., it hadn't been successfully persisted after processing pending events).
555 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
558 /// A trait implemented for objects handling events from [`EventsProvider`].
559 pub trait EventHandler {
560 /// Handles the given [`Event`].
562 /// See [`EventsProvider`] for details that must be considered when implementing this method.
563 fn handle_event(&self, event: &Event);
566 impl<F> EventHandler for F where F: Fn(&Event) {
567 fn handle_event(&self, event: &Event) {