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::{PaymentPathRetry, RouteHop};
26 use bitcoin::blockdata::script::Script;
27 use bitcoin::hashes::Hash;
28 use bitcoin::hashes::sha256::Hash as Sha256;
29 use bitcoin::secp256k1::key::PublicKey;
33 use core::time::Duration;
35 use bitcoin::Transaction;
37 /// Some information provided on receipt of payment depends on whether the payment received is a
38 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
39 #[derive(Clone, Debug)]
40 pub enum PaymentPurpose {
41 /// Information for receiving a payment that we generated an invoice for.
43 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
44 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
45 /// [`ChannelManager::claim_funds`].
47 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
48 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
49 payment_preimage: Option<PaymentPreimage>,
50 /// The "payment secret". This authenticates the sender to the recipient, preventing a
51 /// number of deanonymization attacks during the routing process.
52 /// It is provided here for your reference, however its accuracy is enforced directly by
53 /// [`ChannelManager`] using the values you previously provided to
54 /// [`ChannelManager::create_inbound_payment`] or
55 /// [`ChannelManager::create_inbound_payment_for_hash`].
57 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
58 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
59 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
60 payment_secret: PaymentSecret,
61 /// This is the `user_payment_id` which was provided to
62 /// [`ChannelManager::create_inbound_payment_for_hash`] or
63 /// [`ChannelManager::create_inbound_payment`]. It has no meaning inside of LDK and is
64 /// simply copied here. It may be used to correlate PaymentReceived events with invoice
65 /// metadata stored elsewhere.
67 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
68 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
71 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
72 /// (the payee) providing a preimage.
73 SpontaneousPayment(PaymentPreimage),
76 #[derive(Clone, Debug, PartialEq)]
77 /// The reason the channel was closed. See individual variants more details.
78 pub enum ClosureReason {
79 /// Closure generated from receiving a peer error message.
81 /// Our counterparty may have broadcasted their latest commitment state, and we have
83 CounterpartyForceClosed {
84 /// The error which the peer sent us.
86 /// The string should be sanitized before it is used (e.g emitted to logs
87 /// or printed to stdout). Otherwise, a well crafted error message may exploit
88 /// a security vulnerability in the terminal emulator or the logging subsystem.
91 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
93 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
95 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
96 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
97 //TODO: split between CounterpartyInitiated/LocallyInitiated
99 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
100 /// commitment transaction came from our counterparty, but it may also have come from
101 /// a copy of our own `ChannelMonitor`.
102 CommitmentTxConfirmed,
103 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
105 /// A developer-readable error message which we generated.
108 /// The `PeerManager` informed us that we've disconnected from the peer. We close channels
109 /// if the `PeerManager` informed us that it is unlikely we'll be able to connect to the
110 /// peer again in the future or if the peer disconnected before we finished negotiating
111 /// the channel open. The first case may be caused by incompatible features which our
112 /// counterparty, or we, require.
113 //TODO: split between PeerUnconnectable/PeerDisconnected ?
115 /// Closure generated from `ChannelManager::read` if the ChannelMonitor is newer than
116 /// the ChannelManager deserialized.
117 OutdatedChannelManager
120 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
121 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
122 (2, HolderForceClosed) => {},
123 (6, CommitmentTxConfirmed) => {},
124 (4, CooperativeClosure) => {},
125 (8, ProcessingError) => { (1, err, required) },
126 (10, DisconnectedPeer) => {},
127 (12, OutdatedChannelManager) => {},
130 /// An Event which you should probably take some action in response to.
132 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
133 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
134 /// written as it makes no sense to respond to it after reconnecting to peers).
135 #[derive(Clone, Debug)]
137 /// Used to indicate that the client should generate a funding transaction with the given
138 /// parameters and then call ChannelManager::funding_transaction_generated.
139 /// Generated in ChannelManager message handling.
140 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
141 /// counterparty can steal your funds!
142 FundingGenerationReady {
143 /// The random channel_id we picked which you'll need to pass into
144 /// ChannelManager::funding_transaction_generated.
145 temporary_channel_id: [u8; 32],
146 /// The value, in satoshis, that the output should have.
147 channel_value_satoshis: u64,
148 /// The script which should be used in the transaction output.
149 output_script: Script,
150 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or 0 for
151 /// an inbound channel.
153 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
154 user_channel_id: u64,
156 /// Indicates we've received money! Just gotta dig out that payment preimage and feed it to
157 /// [`ChannelManager::claim_funds`] to get it....
158 /// Note that if the preimage is not known, you should call
159 /// [`ChannelManager::fail_htlc_backwards`] to free up resources for this HTLC and avoid
160 /// network congestion.
161 /// If you fail to call either [`ChannelManager::claim_funds`] or
162 /// [`ChannelManager::fail_htlc_backwards`] within the HTLC's timeout, the HTLC will be
163 /// automatically failed.
165 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
166 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
168 /// The hash for which the preimage should be handed to the ChannelManager.
169 payment_hash: PaymentHash,
170 /// The value, in thousandths of a satoshi, that this payment is for.
172 /// Information for claiming this received payment, based on whether the purpose of the
173 /// payment is to pay an invoice or to send a spontaneous payment.
174 purpose: PaymentPurpose,
176 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
177 /// and we got back the payment preimage for it).
179 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
180 /// event. In this situation, you SHOULD treat this payment as having succeeded.
182 /// The id returned by [`ChannelManager::send_payment`] and used with
183 /// [`ChannelManager::retry_payment`].
185 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
186 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
187 payment_id: Option<PaymentId>,
188 /// The preimage to the hash given to ChannelManager::send_payment.
189 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
190 /// store it somehow!
191 payment_preimage: PaymentPreimage,
192 /// The hash which was given to [`ChannelManager::send_payment`].
194 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
195 payment_hash: PaymentHash,
197 /// Indicates an outbound payment we made failed. Probably some intermediary node dropped
198 /// something. You may wish to retry with a different route.
200 /// The hash which was given to ChannelManager::send_payment.
201 payment_hash: PaymentHash,
202 /// Indicates the payment was rejected for some reason by the recipient. This implies that
203 /// the payment has failed, not just the route in question. If this is not set, you may
204 /// retry the payment via a different route.
205 rejected_by_dest: bool,
206 /// Any failure information conveyed via the Onion return packet by a node along the failed
209 /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into
210 /// account the update. [`NetGraphMsgHandler`] is capable of doing this.
212 /// [`NetworkGraph`]: crate::routing::network_graph::NetworkGraph
213 /// [`NetGraphMsgHandler`]: crate::routing::network_graph::NetGraphMsgHandler
214 network_update: Option<NetworkUpdate>,
215 /// For both single-path and multi-path payments, this is set if all paths of the payment have
216 /// failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the
217 /// larger MPP payment were still in flight when this event was generated.
218 all_paths_failed: bool,
219 /// The payment path that failed.
221 /// The channel responsible for the failed payment path.
223 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
224 /// retried. May be `None` for older [`Event`] serializations.
225 short_channel_id: Option<u64>,
226 /// Parameters needed to re-compute a [`Route`] for retrying the failed path.
228 /// See [`get_retry_route`] for details.
230 /// [`Route`]: crate::routing::router::Route
231 /// [`get_retry_route`]: crate::routing::router::get_retry_route
232 retry: Option<PaymentPathRetry>,
234 error_code: Option<u16>,
236 error_data: Option<Vec<u8>>,
238 /// Used to indicate that ChannelManager::process_pending_htlc_forwards should be called at a
239 /// time in the future.
240 PendingHTLCsForwardable {
241 /// The minimum amount of time that should be waited prior to calling
242 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
243 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
244 /// now + 5*time_forwardable).
245 time_forwardable: Duration,
247 /// Used to indicate that an output which you should know how to spend was confirmed on chain
248 /// and is now spendable.
249 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
250 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
251 /// somewhere and spend them when you create on-chain transactions.
253 /// The outputs which you should store as spendable by you.
254 outputs: Vec<SpendableOutputDescriptor>,
256 /// This event is generated when a payment has been successfully forwarded through us and a
257 /// forwarding fee earned.
259 /// The fee, in milli-satoshis, which was earned as a result of the payment.
261 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
262 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
263 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
264 /// claimed the full value in millisatoshis from the source. In this case,
265 /// `claim_from_onchain_tx` will be set.
267 /// If the channel which sent us the payment has been force-closed, we will claim the funds
268 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
269 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
270 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
272 fee_earned_msat: Option<u64>,
273 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
275 claim_from_onchain_tx: bool,
277 /// Used to indicate that a channel with the given `channel_id` is in the process of closure.
279 /// The channel_id of the channel which has been closed. Note that on-chain transactions
280 /// resolving the channel are likely still awaiting confirmation.
281 channel_id: [u8; 32],
282 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or 0 for
283 /// an inbound channel. This will always be zero for objects serialized with LDK versions
284 /// prior to 0.0.102.
286 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
287 user_channel_id: u64,
288 /// The reason the channel was closed.
289 reason: ClosureReason
291 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
292 /// inputs for another purpose.
294 /// The channel_id of the channel which has been closed.
295 channel_id: [u8; 32],
296 /// The full transaction received from the user
297 transaction: Transaction
301 impl Writeable for Event {
302 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
304 &Event::FundingGenerationReady { .. } => {
306 // We never write out FundingGenerationReady events as, upon disconnection, peers
307 // drop any channels which have not yet exchanged funding_signed.
309 &Event::PaymentReceived { ref payment_hash, ref amt, ref purpose } => {
311 let mut payment_secret = None;
312 let mut user_payment_id = None;
313 let payment_preimage;
315 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret, user_payment_id: id } => {
316 payment_secret = Some(secret);
317 payment_preimage = *preimage;
318 user_payment_id = Some(id);
320 PaymentPurpose::SpontaneousPayment(preimage) => {
321 payment_preimage = Some(*preimage);
324 write_tlv_fields!(writer, {
325 (0, payment_hash, required),
326 (2, payment_secret, option),
328 (6, user_payment_id, option),
329 (8, payment_preimage, option),
332 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash} => {
334 write_tlv_fields!(writer, {
335 (0, payment_preimage, required),
336 (1, payment_hash, required),
337 (3, payment_id, option),
340 &Event::PaymentPathFailed {
341 ref payment_hash, ref rejected_by_dest, ref network_update,
342 ref all_paths_failed, ref path, ref short_channel_id, ref retry,
350 error_code.write(writer)?;
352 error_data.write(writer)?;
353 write_tlv_fields!(writer, {
354 (0, payment_hash, required),
355 (1, network_update, option),
356 (2, rejected_by_dest, required),
357 (3, all_paths_failed, required),
359 (7, short_channel_id, option),
363 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
365 // Note that we now ignore these on the read end as we'll re-generate them in
366 // ChannelManager, we write them here only for backwards compatibility.
368 &Event::SpendableOutputs { ref outputs } => {
370 write_tlv_fields!(writer, {
371 (0, VecWriteWrapper(outputs), required),
374 &Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
376 write_tlv_fields!(writer, {
377 (0, fee_earned_msat, option),
378 (2, claim_from_onchain_tx, required),
381 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
383 write_tlv_fields!(writer, {
384 (0, channel_id, required),
385 (1, user_channel_id, required),
386 (2, reason, required)
389 &Event::DiscardFunding { ref channel_id, ref transaction } => {
391 write_tlv_fields!(writer, {
392 (0, channel_id, required),
393 (2, transaction, required)
396 // Note that, going forward, all new events must only write data inside of
397 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
398 // data via `write_tlv_fields`.
403 impl MaybeReadable for Event {
404 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
405 match Readable::read(reader)? {
406 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
407 // unlike all other events, thus we return immediately here.
411 let mut payment_hash = PaymentHash([0; 32]);
412 let mut payment_preimage = None;
413 let mut payment_secret = None;
415 let mut user_payment_id = None;
416 read_tlv_fields!(reader, {
417 (0, payment_hash, required),
418 (2, payment_secret, option),
420 (6, user_payment_id, option),
421 (8, payment_preimage, option),
423 let purpose = match payment_secret {
424 Some(secret) => PaymentPurpose::InvoicePayment {
426 payment_secret: secret,
427 user_payment_id: if let Some(id) = user_payment_id {
429 } else { return Err(msgs::DecodeError::InvalidValue) }
431 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
432 None => return Err(msgs::DecodeError::InvalidValue),
434 Ok(Some(Event::PaymentReceived {
444 let mut payment_preimage = PaymentPreimage([0; 32]);
445 let mut payment_hash = None;
446 let mut payment_id = None;
447 read_tlv_fields!(reader, {
448 (0, payment_preimage, required),
449 (1, payment_hash, option),
450 (3, payment_id, option),
452 if payment_hash.is_none() {
453 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
455 Ok(Some(Event::PaymentSent {
458 payment_hash: payment_hash.unwrap(),
466 let error_code = Readable::read(reader)?;
468 let error_data = Readable::read(reader)?;
469 let mut payment_hash = PaymentHash([0; 32]);
470 let mut rejected_by_dest = false;
471 let mut network_update = None;
472 let mut all_paths_failed = Some(true);
473 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
474 let mut short_channel_id = None;
475 let mut retry = None;
476 read_tlv_fields!(reader, {
477 (0, payment_hash, required),
478 (1, network_update, ignorable),
479 (2, rejected_by_dest, required),
480 (3, all_paths_failed, option),
482 (7, short_channel_id, option),
485 Ok(Some(Event::PaymentPathFailed {
489 all_paths_failed: all_paths_failed.unwrap(),
504 let mut outputs = VecReadWrapper(Vec::new());
505 read_tlv_fields!(reader, {
506 (0, outputs, required),
508 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
514 let mut fee_earned_msat = None;
515 let mut claim_from_onchain_tx = false;
516 read_tlv_fields!(reader, {
517 (0, fee_earned_msat, option),
518 (2, claim_from_onchain_tx, required),
520 Ok(Some(Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx }))
526 let mut channel_id = [0; 32];
527 let mut reason = None;
528 let mut user_channel_id_opt = None;
529 read_tlv_fields!(reader, {
530 (0, channel_id, required),
531 (1, user_channel_id_opt, option),
532 (2, reason, ignorable),
534 if reason.is_none() { return Ok(None); }
535 let user_channel_id = if let Some(id) = user_channel_id_opt { id } else { 0 };
536 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: reason.unwrap() }))
542 let mut channel_id = [0; 32];
543 let mut transaction = Transaction{ version: 2, lock_time: 0, input: Vec::new(), output: Vec::new() };
544 read_tlv_fields!(reader, {
545 (0, channel_id, required),
546 (2, transaction, required),
548 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
552 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
553 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
556 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
557 // which prefixes the whole thing with a length BigSize. Because the event is
558 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
559 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
560 // exactly the number of bytes specified, ignoring them entirely.
561 let tlv_len: BigSize = Readable::read(reader)?;
562 FixedLengthReader::new(reader, tlv_len.0)
563 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
566 _ => Err(msgs::DecodeError::InvalidValue)
571 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
572 /// broadcast to most peers).
573 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
574 #[derive(Clone, Debug)]
575 pub enum MessageSendEvent {
576 /// Used to indicate that we've accepted a channel open and should send the accept_channel
577 /// message provided to the given peer.
579 /// The node_id of the node which should receive this message
581 /// The message which should be sent.
582 msg: msgs::AcceptChannel,
584 /// Used to indicate that we've initiated a channel open and should send the open_channel
585 /// message provided to the given peer.
587 /// The node_id of the node which should receive this message
589 /// The message which should be sent.
590 msg: msgs::OpenChannel,
592 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
594 /// The node_id of the node which should receive this message
596 /// The message which should be sent.
597 msg: msgs::FundingCreated,
599 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
601 /// The node_id of the node which should receive this message
603 /// The message which should be sent.
604 msg: msgs::FundingSigned,
606 /// Used to indicate that a funding_locked message should be sent to the peer with the given node_id.
608 /// The node_id of the node which should receive these message(s)
610 /// The funding_locked message which should be sent.
611 msg: msgs::FundingLocked,
613 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
614 SendAnnouncementSignatures {
615 /// The node_id of the node which should receive these message(s)
617 /// The announcement_signatures message which should be sent.
618 msg: msgs::AnnouncementSignatures,
620 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
621 /// message should be sent to the peer with the given node_id.
623 /// The node_id of the node which should receive these message(s)
625 /// The update messages which should be sent. ALL messages in the struct should be sent!
626 updates: msgs::CommitmentUpdate,
628 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
630 /// The node_id of the node which should receive this message
632 /// The message which should be sent.
633 msg: msgs::RevokeAndACK,
635 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
637 /// The node_id of the node which should receive this message
639 /// The message which should be sent.
640 msg: msgs::ClosingSigned,
642 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
644 /// The node_id of the node which should receive this message
646 /// The message which should be sent.
649 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
650 SendChannelReestablish {
651 /// The node_id of the node which should receive this message
653 /// The message which should be sent.
654 msg: msgs::ChannelReestablish,
656 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
657 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
659 /// Note that after doing so, you very likely (unless you did so very recently) want to call
660 /// ChannelManager::broadcast_node_announcement to trigger a BroadcastNodeAnnouncement event.
661 /// This ensures that any nodes which see our channel_announcement also have a relevant
662 /// node_announcement, including relevant feature flags which may be important for routing
663 /// through or to us.
664 BroadcastChannelAnnouncement {
665 /// The channel_announcement which should be sent.
666 msg: msgs::ChannelAnnouncement,
667 /// The followup channel_update which should be sent.
668 update_msg: msgs::ChannelUpdate,
670 /// Used to indicate that a node_announcement should be broadcast to all peers.
671 BroadcastNodeAnnouncement {
672 /// The node_announcement which should be sent.
673 msg: msgs::NodeAnnouncement,
675 /// Used to indicate that a channel_update should be broadcast to all peers.
676 BroadcastChannelUpdate {
677 /// The channel_update which should be sent.
678 msg: msgs::ChannelUpdate,
680 /// Used to indicate that a channel_update should be sent to a single peer.
681 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
682 /// private channel and we shouldn't be informing all of our peers of channel parameters.
684 /// The node_id of the node which should receive this message
686 /// The channel_update which should be sent.
687 msg: msgs::ChannelUpdate,
689 /// Broadcast an error downstream to be handled
691 /// The node_id of the node which should receive this message
693 /// The action which should be taken.
694 action: msgs::ErrorAction
696 /// Query a peer for channels with funding transaction UTXOs in a block range.
697 SendChannelRangeQuery {
698 /// The node_id of this message recipient
700 /// The query_channel_range which should be sent.
701 msg: msgs::QueryChannelRange,
703 /// Request routing gossip messages from a peer for a list of channels identified by
704 /// their short_channel_ids.
706 /// The node_id of this message recipient
708 /// The query_short_channel_ids which should be sent.
709 msg: msgs::QueryShortChannelIds,
711 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
712 /// emitted during processing of the query.
713 SendReplyChannelRange {
714 /// The node_id of this message recipient
716 /// The reply_channel_range which should be sent.
717 msg: msgs::ReplyChannelRange,
721 /// A trait indicating an object may generate message send events
722 pub trait MessageSendEventsProvider {
723 /// Gets the list of pending events which were generated by previous actions, clearing the list
725 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
728 /// A trait indicating an object may generate events.
730 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
734 /// See [`process_pending_events`] for requirements around event processing.
736 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
737 /// event since the last invocation. The handler must either act upon the event immediately
738 /// or preserve it for later handling.
740 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
741 /// consult the provider's documentation on the implication of processing events and how a handler
742 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
743 /// [`ChainMonitor::process_pending_events`]).
745 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
748 /// [`process_pending_events`]: Self::process_pending_events
749 /// [`handle_event`]: EventHandler::handle_event
750 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
751 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
752 pub trait EventsProvider {
753 /// Processes any events generated since the last call using the given event handler.
755 /// Subsequent calls must only process new events. However, handlers must be capable of handling
756 /// duplicate events across process restarts. This may occur if the provider was recovered from
757 /// an old state (i.e., it hadn't been successfully persisted after processing pending events).
758 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
761 /// A trait implemented for objects handling events from [`EventsProvider`].
762 pub trait EventHandler {
763 /// Handles the given [`Event`].
765 /// See [`EventsProvider`] for details that must be considered when implementing this method.
766 fn handle_event(&self, event: &Event);
769 impl<F> EventHandler for F where F: Fn(&Event) {
770 fn handle_event(&self, event: &Event) {