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;
18 use ln::channelmanager::PaymentId;
20 use ln::msgs::DecodeError;
21 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
22 use routing::network_graph::NetworkUpdate;
23 use util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, VecReadWrapper, VecWriteWrapper};
24 use routing::router::{RouteHop, RouteParameters};
26 use bitcoin::Transaction;
27 use bitcoin::blockdata::script::Script;
28 use bitcoin::hashes::Hash;
29 use bitcoin::hashes::sha256::Hash as Sha256;
30 use bitcoin::secp256k1::key::PublicKey;
34 use core::time::Duration;
38 /// Some information provided on receipt of payment depends on whether the payment received is a
39 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
40 #[derive(Clone, Debug)]
41 pub enum PaymentPurpose {
42 /// Information for receiving a payment that we generated an invoice for.
44 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
45 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
46 /// [`ChannelManager::claim_funds`].
48 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
49 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
50 payment_preimage: Option<PaymentPreimage>,
51 /// The "payment secret". This authenticates the sender to the recipient, preventing a
52 /// number of deanonymization attacks during the routing process.
53 /// It is provided here for your reference, however its accuracy is enforced directly by
54 /// [`ChannelManager`] using the values you previously provided to
55 /// [`ChannelManager::create_inbound_payment`] or
56 /// [`ChannelManager::create_inbound_payment_for_hash`].
58 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
59 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
60 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
61 payment_secret: PaymentSecret,
62 /// This is the `user_payment_id` which was provided to
63 /// [`ChannelManager::create_inbound_payment_for_hash`] or
64 /// [`ChannelManager::create_inbound_payment`]. It has no meaning inside of LDK and is
65 /// simply copied here. It may be used to correlate PaymentReceived events with invoice
66 /// metadata stored elsewhere.
68 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
69 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
72 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
73 /// (the payee) providing a preimage.
74 SpontaneousPayment(PaymentPreimage),
77 #[derive(Clone, Debug, PartialEq)]
78 /// The reason the channel was closed. See individual variants more details.
79 pub enum ClosureReason {
80 /// Closure generated from receiving a peer error message.
82 /// Our counterparty may have broadcasted their latest commitment state, and we have
84 CounterpartyForceClosed {
85 /// The error which the peer sent us.
87 /// The string should be sanitized before it is used (e.g emitted to logs
88 /// or printed to stdout). Otherwise, a well crafted error message may exploit
89 /// a security vulnerability in the terminal emulator or the logging subsystem.
92 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
94 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
96 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
97 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
98 //TODO: split between CounterpartyInitiated/LocallyInitiated
100 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
101 /// commitment transaction came from our counterparty, but it may also have come from
102 /// a copy of our own `ChannelMonitor`.
103 CommitmentTxConfirmed,
104 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
106 /// A developer-readable error message which we generated.
109 /// The `PeerManager` informed us that we've disconnected from the peer. We close channels
110 /// if the `PeerManager` informed us that it is unlikely we'll be able to connect to the
111 /// peer again in the future or if the peer disconnected before we finished negotiating
112 /// the channel open. The first case may be caused by incompatible features which our
113 /// counterparty, or we, require.
114 //TODO: split between PeerUnconnectable/PeerDisconnected ?
116 /// Closure generated from `ChannelManager::read` if the ChannelMonitor is newer than
117 /// the ChannelManager deserialized.
118 OutdatedChannelManager
121 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
122 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
123 (2, HolderForceClosed) => {},
124 (6, CommitmentTxConfirmed) => {},
125 (4, CooperativeClosure) => {},
126 (8, ProcessingError) => { (1, err, required) },
127 (10, DisconnectedPeer) => {},
128 (12, OutdatedChannelManager) => {},
131 /// An Event which you should probably take some action in response to.
133 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
134 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
135 /// written as it makes no sense to respond to it after reconnecting to peers).
136 #[derive(Clone, Debug)]
138 /// Used to indicate that the client should generate a funding transaction with the given
139 /// parameters and then call ChannelManager::funding_transaction_generated.
140 /// Generated in ChannelManager message handling.
141 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
142 /// counterparty can steal your funds!
143 FundingGenerationReady {
144 /// The random channel_id we picked which you'll need to pass into
145 /// ChannelManager::funding_transaction_generated.
146 temporary_channel_id: [u8; 32],
147 /// The value, in satoshis, that the output should have.
148 channel_value_satoshis: u64,
149 /// The script which should be used in the transaction output.
150 output_script: Script,
151 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or 0 for
152 /// an inbound channel.
154 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
155 user_channel_id: u64,
157 /// Indicates we've received money! Just gotta dig out that payment preimage and feed it to
158 /// [`ChannelManager::claim_funds`] to get it....
159 /// Note that if the preimage is not known, you should call
160 /// [`ChannelManager::fail_htlc_backwards`] to free up resources for this HTLC and avoid
161 /// network congestion.
162 /// If you fail to call either [`ChannelManager::claim_funds`] or
163 /// [`ChannelManager::fail_htlc_backwards`] within the HTLC's timeout, the HTLC will be
164 /// automatically failed.
166 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
167 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
169 /// The hash for which the preimage should be handed to the ChannelManager.
170 payment_hash: PaymentHash,
171 /// The value, in thousandths of a satoshi, that this payment is for.
173 /// Information for claiming this received payment, based on whether the purpose of the
174 /// payment is to pay an invoice or to send a spontaneous payment.
175 purpose: PaymentPurpose,
177 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
178 /// and we got back the payment preimage for it).
180 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
181 /// event. In this situation, you SHOULD treat this payment as having succeeded.
183 /// The id returned by [`ChannelManager::send_payment`] and used with
184 /// [`ChannelManager::retry_payment`].
186 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
187 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
188 payment_id: Option<PaymentId>,
189 /// The preimage to the hash given to ChannelManager::send_payment.
190 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
191 /// store it somehow!
192 payment_preimage: PaymentPreimage,
193 /// The hash which was given to [`ChannelManager::send_payment`].
195 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
196 payment_hash: PaymentHash,
198 /// Indicates an outbound payment we made failed. Probably some intermediary node dropped
199 /// something. You may wish to retry with a different route.
201 /// The id returned by [`ChannelManager::send_payment`] and used with
202 /// [`ChannelManager::retry_payment`].
204 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
205 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
206 payment_id: Option<PaymentId>,
207 /// The hash which was given to ChannelManager::send_payment.
208 payment_hash: PaymentHash,
209 /// Indicates the payment was rejected for some reason by the recipient. This implies that
210 /// the payment has failed, not just the route in question. If this is not set, you may
211 /// retry the payment via a different route.
212 rejected_by_dest: bool,
213 /// Any failure information conveyed via the Onion return packet by a node along the failed
216 /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into
217 /// account the update. [`NetGraphMsgHandler`] is capable of doing this.
219 /// [`NetworkGraph`]: crate::routing::network_graph::NetworkGraph
220 /// [`NetGraphMsgHandler`]: crate::routing::network_graph::NetGraphMsgHandler
221 network_update: Option<NetworkUpdate>,
222 /// For both single-path and multi-path payments, this is set if all paths of the payment have
223 /// failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the
224 /// larger MPP payment were still in flight when this event was generated.
225 all_paths_failed: bool,
226 /// The payment path that failed.
228 /// The channel responsible for the failed payment path.
230 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
231 /// retried. May be `None` for older [`Event`] serializations.
232 short_channel_id: Option<u64>,
233 /// Parameters needed to compute a new [`Route`] when retrying the failed payment path.
235 /// See [`find_route`] for details.
237 /// [`Route`]: crate::routing::router::Route
238 /// [`find_route`]: crate::routing::router::find_route
239 retry: Option<RouteParameters>,
241 error_code: Option<u16>,
243 error_data: Option<Vec<u8>>,
245 /// Used to indicate that ChannelManager::process_pending_htlc_forwards should be called at a
246 /// time in the future.
247 PendingHTLCsForwardable {
248 /// The minimum amount of time that should be waited prior to calling
249 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
250 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
251 /// now + 5*time_forwardable).
252 time_forwardable: Duration,
254 /// Used to indicate that an output which you should know how to spend was confirmed on chain
255 /// and is now spendable.
256 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
257 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
258 /// somewhere and spend them when you create on-chain transactions.
260 /// The outputs which you should store as spendable by you.
261 outputs: Vec<SpendableOutputDescriptor>,
263 /// This event is generated when a payment has been successfully forwarded through us and a
264 /// forwarding fee earned.
266 /// The fee, in milli-satoshis, which was earned as a result of the payment.
268 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
269 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
270 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
271 /// claimed the full value in millisatoshis from the source. In this case,
272 /// `claim_from_onchain_tx` will be set.
274 /// If the channel which sent us the payment has been force-closed, we will claim the funds
275 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
276 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
277 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
279 fee_earned_msat: Option<u64>,
280 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
282 claim_from_onchain_tx: bool,
284 /// Used to indicate that a channel with the given `channel_id` is in the process of closure.
286 /// The channel_id of the channel which has been closed. Note that on-chain transactions
287 /// resolving the channel are likely still awaiting confirmation.
288 channel_id: [u8; 32],
289 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or 0 for
290 /// an inbound channel. This will always be zero for objects serialized with LDK versions
291 /// prior to 0.0.102.
293 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
294 user_channel_id: u64,
295 /// The reason the channel was closed.
296 reason: ClosureReason
298 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
299 /// inputs for another purpose.
301 /// The channel_id of the channel which has been closed.
302 channel_id: [u8; 32],
303 /// The full transaction received from the user
304 transaction: Transaction
308 impl Writeable for Event {
309 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
311 &Event::FundingGenerationReady { .. } => {
313 // We never write out FundingGenerationReady events as, upon disconnection, peers
314 // drop any channels which have not yet exchanged funding_signed.
316 &Event::PaymentReceived { ref payment_hash, ref amt, ref purpose } => {
318 let mut payment_secret = None;
319 let mut user_payment_id = None;
320 let payment_preimage;
322 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret, user_payment_id: id } => {
323 payment_secret = Some(secret);
324 payment_preimage = *preimage;
325 user_payment_id = Some(id);
327 PaymentPurpose::SpontaneousPayment(preimage) => {
328 payment_preimage = Some(*preimage);
331 write_tlv_fields!(writer, {
332 (0, payment_hash, required),
333 (2, payment_secret, option),
335 (6, user_payment_id, option),
336 (8, payment_preimage, option),
339 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash} => {
341 write_tlv_fields!(writer, {
342 (0, payment_preimage, required),
343 (1, payment_hash, required),
344 (3, payment_id, option),
347 &Event::PaymentPathFailed {
348 ref payment_id, ref payment_hash, ref rejected_by_dest, ref network_update,
349 ref all_paths_failed, ref path, ref short_channel_id, ref retry,
357 error_code.write(writer)?;
359 error_data.write(writer)?;
360 write_tlv_fields!(writer, {
361 (0, payment_hash, required),
362 (1, network_update, option),
363 (2, rejected_by_dest, required),
364 (3, all_paths_failed, required),
366 (7, short_channel_id, option),
368 (11, payment_id, option),
371 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
373 // Note that we now ignore these on the read end as we'll re-generate them in
374 // ChannelManager, we write them here only for backwards compatibility.
376 &Event::SpendableOutputs { ref outputs } => {
378 write_tlv_fields!(writer, {
379 (0, VecWriteWrapper(outputs), required),
382 &Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
384 write_tlv_fields!(writer, {
385 (0, fee_earned_msat, option),
386 (2, claim_from_onchain_tx, required),
389 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
391 write_tlv_fields!(writer, {
392 (0, channel_id, required),
393 (1, user_channel_id, required),
394 (2, reason, required)
397 &Event::DiscardFunding { ref channel_id, ref transaction } => {
399 write_tlv_fields!(writer, {
400 (0, channel_id, required),
401 (2, transaction, required)
404 // Note that, going forward, all new events must only write data inside of
405 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
406 // data via `write_tlv_fields`.
411 impl MaybeReadable for Event {
412 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
413 match Readable::read(reader)? {
414 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
415 // unlike all other events, thus we return immediately here.
419 let mut payment_hash = PaymentHash([0; 32]);
420 let mut payment_preimage = None;
421 let mut payment_secret = None;
423 let mut user_payment_id = None;
424 read_tlv_fields!(reader, {
425 (0, payment_hash, required),
426 (2, payment_secret, option),
428 (6, user_payment_id, option),
429 (8, payment_preimage, option),
431 let purpose = match payment_secret {
432 Some(secret) => PaymentPurpose::InvoicePayment {
434 payment_secret: secret,
435 user_payment_id: if let Some(id) = user_payment_id {
437 } else { return Err(msgs::DecodeError::InvalidValue) }
439 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
440 None => return Err(msgs::DecodeError::InvalidValue),
442 Ok(Some(Event::PaymentReceived {
452 let mut payment_preimage = PaymentPreimage([0; 32]);
453 let mut payment_hash = None;
454 let mut payment_id = None;
455 read_tlv_fields!(reader, {
456 (0, payment_preimage, required),
457 (1, payment_hash, option),
458 (3, payment_id, option),
460 if payment_hash.is_none() {
461 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
463 Ok(Some(Event::PaymentSent {
466 payment_hash: payment_hash.unwrap(),
474 let error_code = Readable::read(reader)?;
476 let error_data = Readable::read(reader)?;
477 let mut payment_hash = PaymentHash([0; 32]);
478 let mut rejected_by_dest = false;
479 let mut network_update = None;
480 let mut all_paths_failed = Some(true);
481 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
482 let mut short_channel_id = None;
483 let mut retry = None;
484 let mut payment_id = None;
485 read_tlv_fields!(reader, {
486 (0, payment_hash, required),
487 (1, network_update, ignorable),
488 (2, rejected_by_dest, required),
489 (3, all_paths_failed, option),
491 (7, short_channel_id, option),
493 (11, payment_id, option),
495 Ok(Some(Event::PaymentPathFailed {
500 all_paths_failed: all_paths_failed.unwrap(),
515 let mut outputs = VecReadWrapper(Vec::new());
516 read_tlv_fields!(reader, {
517 (0, outputs, required),
519 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
525 let mut fee_earned_msat = None;
526 let mut claim_from_onchain_tx = false;
527 read_tlv_fields!(reader, {
528 (0, fee_earned_msat, option),
529 (2, claim_from_onchain_tx, required),
531 Ok(Some(Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx }))
537 let mut channel_id = [0; 32];
538 let mut reason = None;
539 let mut user_channel_id_opt = None;
540 read_tlv_fields!(reader, {
541 (0, channel_id, required),
542 (1, user_channel_id_opt, option),
543 (2, reason, ignorable),
545 if reason.is_none() { return Ok(None); }
546 let user_channel_id = if let Some(id) = user_channel_id_opt { id } else { 0 };
547 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: reason.unwrap() }))
553 let mut channel_id = [0; 32];
554 let mut transaction = Transaction{ version: 2, lock_time: 0, input: Vec::new(), output: Vec::new() };
555 read_tlv_fields!(reader, {
556 (0, channel_id, required),
557 (2, transaction, required),
559 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
563 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
564 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
567 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
568 // which prefixes the whole thing with a length BigSize. Because the event is
569 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
570 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
571 // exactly the number of bytes specified, ignoring them entirely.
572 let tlv_len: BigSize = Readable::read(reader)?;
573 FixedLengthReader::new(reader, tlv_len.0)
574 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
577 _ => Err(msgs::DecodeError::InvalidValue)
582 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
583 /// broadcast to most peers).
584 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
585 #[derive(Clone, Debug)]
586 pub enum MessageSendEvent {
587 /// Used to indicate that we've accepted a channel open and should send the accept_channel
588 /// message provided to the given peer.
590 /// The node_id of the node which should receive this message
592 /// The message which should be sent.
593 msg: msgs::AcceptChannel,
595 /// Used to indicate that we've initiated a channel open and should send the open_channel
596 /// message provided to the given peer.
598 /// The node_id of the node which should receive this message
600 /// The message which should be sent.
601 msg: msgs::OpenChannel,
603 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
605 /// The node_id of the node which should receive this message
607 /// The message which should be sent.
608 msg: msgs::FundingCreated,
610 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
612 /// The node_id of the node which should receive this message
614 /// The message which should be sent.
615 msg: msgs::FundingSigned,
617 /// Used to indicate that a funding_locked message should be sent to the peer with the given node_id.
619 /// The node_id of the node which should receive these message(s)
621 /// The funding_locked message which should be sent.
622 msg: msgs::FundingLocked,
624 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
625 SendAnnouncementSignatures {
626 /// The node_id of the node which should receive these message(s)
628 /// The announcement_signatures message which should be sent.
629 msg: msgs::AnnouncementSignatures,
631 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
632 /// message should be sent to the peer with the given node_id.
634 /// The node_id of the node which should receive these message(s)
636 /// The update messages which should be sent. ALL messages in the struct should be sent!
637 updates: msgs::CommitmentUpdate,
639 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
641 /// The node_id of the node which should receive this message
643 /// The message which should be sent.
644 msg: msgs::RevokeAndACK,
646 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
648 /// The node_id of the node which should receive this message
650 /// The message which should be sent.
651 msg: msgs::ClosingSigned,
653 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
655 /// The node_id of the node which should receive this message
657 /// The message which should be sent.
660 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
661 SendChannelReestablish {
662 /// The node_id of the node which should receive this message
664 /// The message which should be sent.
665 msg: msgs::ChannelReestablish,
667 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
668 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
670 /// Note that after doing so, you very likely (unless you did so very recently) want to call
671 /// ChannelManager::broadcast_node_announcement to trigger a BroadcastNodeAnnouncement event.
672 /// This ensures that any nodes which see our channel_announcement also have a relevant
673 /// node_announcement, including relevant feature flags which may be important for routing
674 /// through or to us.
675 BroadcastChannelAnnouncement {
676 /// The channel_announcement which should be sent.
677 msg: msgs::ChannelAnnouncement,
678 /// The followup channel_update which should be sent.
679 update_msg: msgs::ChannelUpdate,
681 /// Used to indicate that a node_announcement should be broadcast to all peers.
682 BroadcastNodeAnnouncement {
683 /// The node_announcement which should be sent.
684 msg: msgs::NodeAnnouncement,
686 /// Used to indicate that a channel_update should be broadcast to all peers.
687 BroadcastChannelUpdate {
688 /// The channel_update which should be sent.
689 msg: msgs::ChannelUpdate,
691 /// Used to indicate that a channel_update should be sent to a single peer.
692 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
693 /// private channel and we shouldn't be informing all of our peers of channel parameters.
695 /// The node_id of the node which should receive this message
697 /// The channel_update which should be sent.
698 msg: msgs::ChannelUpdate,
700 /// Broadcast an error downstream to be handled
702 /// The node_id of the node which should receive this message
704 /// The action which should be taken.
705 action: msgs::ErrorAction
707 /// Query a peer for channels with funding transaction UTXOs in a block range.
708 SendChannelRangeQuery {
709 /// The node_id of this message recipient
711 /// The query_channel_range which should be sent.
712 msg: msgs::QueryChannelRange,
714 /// Request routing gossip messages from a peer for a list of channels identified by
715 /// their short_channel_ids.
717 /// The node_id of this message recipient
719 /// The query_short_channel_ids which should be sent.
720 msg: msgs::QueryShortChannelIds,
722 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
723 /// emitted during processing of the query.
724 SendReplyChannelRange {
725 /// The node_id of this message recipient
727 /// The reply_channel_range which should be sent.
728 msg: msgs::ReplyChannelRange,
732 /// A trait indicating an object may generate message send events
733 pub trait MessageSendEventsProvider {
734 /// Gets the list of pending events which were generated by previous actions, clearing the list
736 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
739 /// A trait indicating an object may generate events.
741 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
745 /// See [`process_pending_events`] for requirements around event processing.
747 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
748 /// event since the last invocation. The handler must either act upon the event immediately
749 /// or preserve it for later handling.
751 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
752 /// consult the provider's documentation on the implication of processing events and how a handler
753 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
754 /// [`ChainMonitor::process_pending_events`]).
756 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
759 /// [`process_pending_events`]: Self::process_pending_events
760 /// [`handle_event`]: EventHandler::handle_event
761 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
762 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
763 pub trait EventsProvider {
764 /// Processes any events generated since the last call using the given event handler.
766 /// Subsequent calls must only process new events. However, handlers must be capable of handling
767 /// duplicate events across process restarts. This may occur if the provider was recovered from
768 /// an old state (i.e., it hadn't been successfully persisted after processing pending events).
769 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
772 /// A trait implemented for objects handling events from [`EventsProvider`].
773 pub trait EventHandler {
774 /// Handles the given [`Event`].
776 /// See [`EventsProvider`] for details that must be considered when implementing this method.
777 fn handle_event(&self, event: &Event);
780 impl<F> EventHandler for F where F: Fn(&Event) {
781 fn handle_event(&self, event: &Event) {
786 impl<T: EventHandler> EventHandler for Arc<T> {
787 fn handle_event(&self, event: &Event) {
788 self.deref().handle_event(event)