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::msgs::DecodeError;
20 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
21 use routing::network_graph::NetworkUpdate;
22 use util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, VecReadWrapper, VecWriteWrapper};
23 use routing::router::RouteHop;
25 use bitcoin::blockdata::script::Script;
26 use bitcoin::hashes::Hash;
27 use bitcoin::hashes::sha256::Hash as Sha256;
28 use bitcoin::secp256k1::key::PublicKey;
32 use core::time::Duration;
34 use bitcoin::Transaction;
36 /// Some information provided on receipt of payment depends on whether the payment received is a
37 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
38 #[derive(Clone, Debug)]
39 pub enum PaymentPurpose {
40 /// Information for receiving a payment that we generated an invoice for.
42 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
43 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
44 /// [`ChannelManager::claim_funds`].
46 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
47 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
48 payment_preimage: Option<PaymentPreimage>,
49 /// The "payment secret". This authenticates the sender to the recipient, preventing a
50 /// number of deanonymization attacks during the routing process.
51 /// It is provided here for your reference, however its accuracy is enforced directly by
52 /// [`ChannelManager`] using the values you previously provided to
53 /// [`ChannelManager::create_inbound_payment`] or
54 /// [`ChannelManager::create_inbound_payment_for_hash`].
56 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
57 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
58 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
59 payment_secret: PaymentSecret,
60 /// This is the `user_payment_id` which was provided to
61 /// [`ChannelManager::create_inbound_payment_for_hash`] or
62 /// [`ChannelManager::create_inbound_payment`]. It has no meaning inside of LDK and is
63 /// simply copied here. It may be used to correlate PaymentReceived events with invoice
64 /// metadata stored elsewhere.
66 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
67 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
70 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
71 /// (the payee) providing a preimage.
72 SpontaneousPayment(PaymentPreimage),
75 #[derive(Clone, Debug, PartialEq)]
76 /// The reason the channel was closed. See individual variants more details.
77 pub enum ClosureReason {
78 /// Closure generated from receiving a peer error message.
80 /// Our counterparty may have broadcasted their latest commitment state, and we have
82 CounterpartyForceClosed {
83 /// The error which the peer sent us.
85 /// The string should be sanitized before it is used (e.g emitted to logs
86 /// or printed to stdout). Otherwise, a well crafted error message may exploit
87 /// a security vulnerability in the terminal emulator or the logging subsystem.
90 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
92 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
94 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
95 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
96 //TODO: split between CounterpartyInitiated/LocallyInitiated
98 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
99 /// commitment transaction came from our counterparty, but it may also have come from
100 /// a copy of our own `ChannelMonitor`.
101 CommitmentTxConfirmed,
102 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
104 /// A developer-readable error message which we generated.
107 /// The `PeerManager` informed us that we've disconnected from the peer. We close channels
108 /// if the `PeerManager` informed us that it is unlikely we'll be able to connect to the
109 /// peer again in the future or if the peer disconnected before we finished negotiating
110 /// the channel open. The first case may be caused by incompatible features which our
111 /// counterparty, or we, require.
112 //TODO: split between PeerUnconnectable/PeerDisconnected ?
114 /// Closure generated from `ChannelManager::read` if the ChannelMonitor is newer than
115 /// the ChannelManager deserialized.
116 OutdatedChannelManager
119 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
120 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
121 (2, HolderForceClosed) => {},
122 (6, CommitmentTxConfirmed) => {},
123 (4, CooperativeClosure) => {},
124 (8, ProcessingError) => { (1, err, required) },
125 (10, DisconnectedPeer) => {},
126 (12, OutdatedChannelManager) => {},
129 /// An Event which you should probably take some action in response to.
131 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
132 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
133 /// written as it makes no sense to respond to it after reconnecting to peers).
134 #[derive(Clone, Debug)]
136 /// Used to indicate that the client should generate a funding transaction with the given
137 /// parameters and then call ChannelManager::funding_transaction_generated.
138 /// Generated in ChannelManager message handling.
139 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
140 /// counterparty can steal your funds!
141 FundingGenerationReady {
142 /// The random channel_id we picked which you'll need to pass into
143 /// ChannelManager::funding_transaction_generated.
144 temporary_channel_id: [u8; 32],
145 /// The value, in satoshis, that the output should have.
146 channel_value_satoshis: u64,
147 /// The script which should be used in the transaction output.
148 output_script: Script,
149 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or 0 for
150 /// an inbound channel.
152 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
153 user_channel_id: u64,
155 /// Indicates we've received money! Just gotta dig out that payment preimage and feed it to
156 /// [`ChannelManager::claim_funds`] to get it....
157 /// Note that if the preimage is not known, you should call
158 /// [`ChannelManager::fail_htlc_backwards`] to free up resources for this HTLC and avoid
159 /// network congestion.
160 /// If you fail to call either [`ChannelManager::claim_funds`] or
161 /// [`ChannelManager::fail_htlc_backwards`] within the HTLC's timeout, the HTLC will be
162 /// automatically failed.
164 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
165 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
167 /// The hash for which the preimage should be handed to the ChannelManager.
168 payment_hash: PaymentHash,
169 /// The value, in thousandths of a satoshi, that this payment is for.
171 /// Information for claiming this received payment, based on whether the purpose of the
172 /// payment is to pay an invoice or to send a spontaneous payment.
173 purpose: PaymentPurpose,
175 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
176 /// and we got back the payment preimage for it).
178 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
179 /// event. In this situation, you SHOULD treat this payment as having succeeded.
181 /// The preimage to the hash given to ChannelManager::send_payment.
182 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
183 /// store it somehow!
184 payment_preimage: PaymentPreimage,
185 /// The hash which was given to [`ChannelManager::send_payment`].
187 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
188 payment_hash: PaymentHash,
190 /// Indicates an outbound payment we made failed. Probably some intermediary node dropped
191 /// something. You may wish to retry with a different route.
193 /// The hash which was given to ChannelManager::send_payment.
194 payment_hash: PaymentHash,
195 /// Indicates the payment was rejected for some reason by the recipient. This implies that
196 /// the payment has failed, not just the route in question. If this is not set, you may
197 /// retry the payment via a different route.
198 rejected_by_dest: bool,
199 /// Any failure information conveyed via the Onion return packet by a node along the failed
202 /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into
203 /// account the update. [`NetGraphMsgHandler`] is capable of doing this.
205 /// [`NetworkGraph`]: crate::routing::network_graph::NetworkGraph
206 /// [`NetGraphMsgHandler`]: crate::routing::network_graph::NetGraphMsgHandler
207 network_update: Option<NetworkUpdate>,
208 /// For both single-path and multi-path payments, this is set if all paths of the payment have
209 /// failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the
210 /// larger MPP payment were still in flight when this event was generated.
211 all_paths_failed: bool,
212 /// The payment path that failed.
214 /// The channel responsible for the failed payment path.
216 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
217 /// retried. May be `None` for older [`Event`] serializations.
218 short_channel_id: Option<u64>,
220 error_code: Option<u16>,
222 error_data: Option<Vec<u8>>,
224 /// Used to indicate that ChannelManager::process_pending_htlc_forwards should be called at a
225 /// time in the future.
226 PendingHTLCsForwardable {
227 /// The minimum amount of time that should be waited prior to calling
228 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
229 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
230 /// now + 5*time_forwardable).
231 time_forwardable: Duration,
233 /// Used to indicate that an output which you should know how to spend was confirmed on chain
234 /// and is now spendable.
235 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
236 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
237 /// somewhere and spend them when you create on-chain transactions.
239 /// The outputs which you should store as spendable by you.
240 outputs: Vec<SpendableOutputDescriptor>,
242 /// This event is generated when a payment has been successfully forwarded through us and a
243 /// forwarding fee earned.
245 /// The fee, in milli-satoshis, which was earned as a result of the payment.
247 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
248 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
249 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
250 /// claimed the full value in millisatoshis from the source. In this case,
251 /// `claim_from_onchain_tx` will be set.
253 /// If the channel which sent us the payment has been force-closed, we will claim the funds
254 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
255 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
256 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
258 fee_earned_msat: Option<u64>,
259 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
261 claim_from_onchain_tx: bool,
263 /// Used to indicate that a channel with the given `channel_id` is in the process of closure.
265 /// The channel_id of the channel which has been closed. Note that on-chain transactions
266 /// resolving the channel are likely still awaiting confirmation.
267 channel_id: [u8; 32],
268 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or 0 for
269 /// an inbound channel. This will always be zero for objects serialized with LDK versions
270 /// prior to 0.0.102.
272 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
273 user_channel_id: u64,
274 /// The reason the channel was closed.
275 reason: ClosureReason
277 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
278 /// inputs for another purpose.
280 /// The channel_id of the channel which has been closed.
281 channel_id: [u8; 32],
282 /// The full transaction received from the user
283 transaction: Transaction
287 impl Writeable for Event {
288 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
290 &Event::FundingGenerationReady { .. } => {
292 // We never write out FundingGenerationReady events as, upon disconnection, peers
293 // drop any channels which have not yet exchanged funding_signed.
295 &Event::PaymentReceived { ref payment_hash, ref amt, ref purpose } => {
297 let mut payment_secret = None;
298 let mut user_payment_id = None;
299 let payment_preimage;
301 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret, user_payment_id: id } => {
302 payment_secret = Some(secret);
303 payment_preimage = *preimage;
304 user_payment_id = Some(id);
306 PaymentPurpose::SpontaneousPayment(preimage) => {
307 payment_preimage = Some(*preimage);
310 write_tlv_fields!(writer, {
311 (0, payment_hash, required),
312 (2, payment_secret, option),
314 (6, user_payment_id, option),
315 (8, payment_preimage, option),
318 &Event::PaymentSent { ref payment_preimage, ref payment_hash} => {
320 write_tlv_fields!(writer, {
321 (0, payment_preimage, required),
322 (1, payment_hash, required),
325 &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update,
326 ref all_paths_failed, ref path, ref short_channel_id,
334 error_code.write(writer)?;
336 error_data.write(writer)?;
337 write_tlv_fields!(writer, {
338 (0, payment_hash, required),
339 (1, network_update, option),
340 (2, rejected_by_dest, required),
341 (3, all_paths_failed, required),
343 (7, short_channel_id, option),
346 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
348 // Note that we now ignore these on the read end as we'll re-generate them in
349 // ChannelManager, we write them here only for backwards compatibility.
351 &Event::SpendableOutputs { ref outputs } => {
353 write_tlv_fields!(writer, {
354 (0, VecWriteWrapper(outputs), required),
357 &Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
359 write_tlv_fields!(writer, {
360 (0, fee_earned_msat, option),
361 (2, claim_from_onchain_tx, required),
364 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
366 write_tlv_fields!(writer, {
367 (0, channel_id, required),
368 (1, user_channel_id, required),
369 (2, reason, required)
372 &Event::DiscardFunding { ref channel_id, ref transaction } => {
374 write_tlv_fields!(writer, {
375 (0, channel_id, required),
376 (2, transaction, required)
379 // Note that, going forward, all new events must only write data inside of
380 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
381 // data via `write_tlv_fields`.
386 impl MaybeReadable for Event {
387 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
388 match Readable::read(reader)? {
389 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
390 // unlike all other events, thus we return immediately here.
394 let mut payment_hash = PaymentHash([0; 32]);
395 let mut payment_preimage = None;
396 let mut payment_secret = None;
398 let mut user_payment_id = None;
399 read_tlv_fields!(reader, {
400 (0, payment_hash, required),
401 (2, payment_secret, option),
403 (6, user_payment_id, option),
404 (8, payment_preimage, option),
406 let purpose = match payment_secret {
407 Some(secret) => PaymentPurpose::InvoicePayment {
409 payment_secret: secret,
410 user_payment_id: if let Some(id) = user_payment_id {
412 } else { return Err(msgs::DecodeError::InvalidValue) }
414 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
415 None => return Err(msgs::DecodeError::InvalidValue),
417 Ok(Some(Event::PaymentReceived {
427 let mut payment_preimage = PaymentPreimage([0; 32]);
428 let mut payment_hash = None;
429 read_tlv_fields!(reader, {
430 (0, payment_preimage, required),
431 (1, payment_hash, option),
433 if payment_hash.is_none() {
434 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
436 Ok(Some(Event::PaymentSent {
438 payment_hash: payment_hash.unwrap(),
446 let error_code = Readable::read(reader)?;
448 let error_data = Readable::read(reader)?;
449 let mut payment_hash = PaymentHash([0; 32]);
450 let mut rejected_by_dest = false;
451 let mut network_update = None;
452 let mut all_paths_failed = Some(true);
453 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
454 let mut short_channel_id = None;
455 read_tlv_fields!(reader, {
456 (0, payment_hash, required),
457 (1, network_update, ignorable),
458 (2, rejected_by_dest, required),
459 (3, all_paths_failed, option),
461 (7, short_channel_id, ignorable),
463 Ok(Some(Event::PaymentPathFailed {
467 all_paths_failed: all_paths_failed.unwrap(),
481 let mut outputs = VecReadWrapper(Vec::new());
482 read_tlv_fields!(reader, {
483 (0, outputs, required),
485 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
491 let mut fee_earned_msat = None;
492 let mut claim_from_onchain_tx = false;
493 read_tlv_fields!(reader, {
494 (0, fee_earned_msat, option),
495 (2, claim_from_onchain_tx, required),
497 Ok(Some(Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx }))
503 let mut channel_id = [0; 32];
504 let mut reason = None;
505 let mut user_channel_id_opt = None;
506 read_tlv_fields!(reader, {
507 (0, channel_id, required),
508 (1, user_channel_id_opt, option),
509 (2, reason, ignorable),
511 if reason.is_none() { return Ok(None); }
512 let user_channel_id = if let Some(id) = user_channel_id_opt { id } else { 0 };
513 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: reason.unwrap() }))
519 let mut channel_id = [0; 32];
520 let mut transaction = Transaction{ version: 2, lock_time: 0, input: Vec::new(), output: Vec::new() };
521 read_tlv_fields!(reader, {
522 (0, channel_id, required),
523 (2, transaction, required),
525 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
529 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
530 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
533 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
534 // which prefixes the whole thing with a length BigSize. Because the event is
535 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
536 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
537 // exactly the number of bytes specified, ignoring them entirely.
538 let tlv_len: BigSize = Readable::read(reader)?;
539 FixedLengthReader::new(reader, tlv_len.0)
540 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
543 _ => Err(msgs::DecodeError::InvalidValue)
548 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
549 /// broadcast to most peers).
550 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
551 #[derive(Clone, Debug)]
552 pub enum MessageSendEvent {
553 /// Used to indicate that we've accepted a channel open and should send the accept_channel
554 /// message provided to the given peer.
556 /// The node_id of the node which should receive this message
558 /// The message which should be sent.
559 msg: msgs::AcceptChannel,
561 /// Used to indicate that we've initiated a channel open and should send the open_channel
562 /// message provided to the given peer.
564 /// The node_id of the node which should receive this message
566 /// The message which should be sent.
567 msg: msgs::OpenChannel,
569 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
571 /// The node_id of the node which should receive this message
573 /// The message which should be sent.
574 msg: msgs::FundingCreated,
576 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
578 /// The node_id of the node which should receive this message
580 /// The message which should be sent.
581 msg: msgs::FundingSigned,
583 /// Used to indicate that a funding_locked message should be sent to the peer with the given node_id.
585 /// The node_id of the node which should receive these message(s)
587 /// The funding_locked message which should be sent.
588 msg: msgs::FundingLocked,
590 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
591 SendAnnouncementSignatures {
592 /// The node_id of the node which should receive these message(s)
594 /// The announcement_signatures message which should be sent.
595 msg: msgs::AnnouncementSignatures,
597 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
598 /// message should be sent to the peer with the given node_id.
600 /// The node_id of the node which should receive these message(s)
602 /// The update messages which should be sent. ALL messages in the struct should be sent!
603 updates: msgs::CommitmentUpdate,
605 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
607 /// The node_id of the node which should receive this message
609 /// The message which should be sent.
610 msg: msgs::RevokeAndACK,
612 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
614 /// The node_id of the node which should receive this message
616 /// The message which should be sent.
617 msg: msgs::ClosingSigned,
619 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
621 /// The node_id of the node which should receive this message
623 /// The message which should be sent.
626 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
627 SendChannelReestablish {
628 /// The node_id of the node which should receive this message
630 /// The message which should be sent.
631 msg: msgs::ChannelReestablish,
633 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
634 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
636 /// Note that after doing so, you very likely (unless you did so very recently) want to call
637 /// ChannelManager::broadcast_node_announcement to trigger a BroadcastNodeAnnouncement event.
638 /// This ensures that any nodes which see our channel_announcement also have a relevant
639 /// node_announcement, including relevant feature flags which may be important for routing
640 /// through or to us.
641 BroadcastChannelAnnouncement {
642 /// The channel_announcement which should be sent.
643 msg: msgs::ChannelAnnouncement,
644 /// The followup channel_update which should be sent.
645 update_msg: msgs::ChannelUpdate,
647 /// Used to indicate that a node_announcement should be broadcast to all peers.
648 BroadcastNodeAnnouncement {
649 /// The node_announcement which should be sent.
650 msg: msgs::NodeAnnouncement,
652 /// Used to indicate that a channel_update should be broadcast to all peers.
653 BroadcastChannelUpdate {
654 /// The channel_update which should be sent.
655 msg: msgs::ChannelUpdate,
657 /// Used to indicate that a channel_update should be sent to a single peer.
658 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
659 /// private channel and we shouldn't be informing all of our peers of channel parameters.
661 /// The node_id of the node which should receive this message
663 /// The channel_update which should be sent.
664 msg: msgs::ChannelUpdate,
666 /// Broadcast an error downstream to be handled
668 /// The node_id of the node which should receive this message
670 /// The action which should be taken.
671 action: msgs::ErrorAction
673 /// Query a peer for channels with funding transaction UTXOs in a block range.
674 SendChannelRangeQuery {
675 /// The node_id of this message recipient
677 /// The query_channel_range which should be sent.
678 msg: msgs::QueryChannelRange,
680 /// Request routing gossip messages from a peer for a list of channels identified by
681 /// their short_channel_ids.
683 /// The node_id of this message recipient
685 /// The query_short_channel_ids which should be sent.
686 msg: msgs::QueryShortChannelIds,
688 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
689 /// emitted during processing of the query.
690 SendReplyChannelRange {
691 /// The node_id of this message recipient
693 /// The reply_channel_range which should be sent.
694 msg: msgs::ReplyChannelRange,
698 /// A trait indicating an object may generate message send events
699 pub trait MessageSendEventsProvider {
700 /// Gets the list of pending events which were generated by previous actions, clearing the list
702 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
705 /// A trait indicating an object may generate events.
707 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
711 /// See [`process_pending_events`] for requirements around event processing.
713 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
714 /// event since the last invocation. The handler must either act upon the event immediately
715 /// or preserve it for later handling.
717 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
718 /// consult the provider's documentation on the implication of processing events and how a handler
719 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
720 /// [`ChainMonitor::process_pending_events`]).
722 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
725 /// [`process_pending_events`]: Self::process_pending_events
726 /// [`handle_event`]: EventHandler::handle_event
727 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
728 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
729 pub trait EventsProvider {
730 /// Processes any events generated since the last call using the given event handler.
732 /// Subsequent calls must only process new events. However, handlers must be capable of handling
733 /// duplicate events across process restarts. This may occur if the provider was recovered from
734 /// an old state (i.e., it hadn't been successfully persisted after processing pending events).
735 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
738 /// A trait implemented for objects handling events from [`EventsProvider`].
739 pub trait EventHandler {
740 /// Handles the given [`Event`].
742 /// See [`EventsProvider`] for details that must be considered when implementing this method.
743 fn handle_event(&self, event: &Event);
746 impl<F> EventHandler for F where F: Fn(&Event) {
747 fn handle_event(&self, event: &Event) {