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 id returned by [`ChannelManager::send_payment`] and used with
201 /// [`ChannelManager::retry_payment`].
203 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
204 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
205 payment_id: Option<PaymentId>,
206 /// The hash which was given to ChannelManager::send_payment.
207 payment_hash: PaymentHash,
208 /// Indicates the payment was rejected for some reason by the recipient. This implies that
209 /// the payment has failed, not just the route in question. If this is not set, you may
210 /// retry the payment via a different route.
211 rejected_by_dest: bool,
212 /// Any failure information conveyed via the Onion return packet by a node along the failed
215 /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into
216 /// account the update. [`NetGraphMsgHandler`] is capable of doing this.
218 /// [`NetworkGraph`]: crate::routing::network_graph::NetworkGraph
219 /// [`NetGraphMsgHandler`]: crate::routing::network_graph::NetGraphMsgHandler
220 network_update: Option<NetworkUpdate>,
221 /// For both single-path and multi-path payments, this is set if all paths of the payment have
222 /// failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the
223 /// larger MPP payment were still in flight when this event was generated.
224 all_paths_failed: bool,
225 /// The payment path that failed.
227 /// The channel responsible for the failed payment path.
229 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
230 /// retried. May be `None` for older [`Event`] serializations.
231 short_channel_id: Option<u64>,
232 /// Parameters needed to re-compute a [`Route`] for retrying the failed path.
234 /// See [`get_retry_route`] for details.
236 /// [`Route`]: crate::routing::router::Route
237 /// [`get_retry_route`]: crate::routing::router::get_retry_route
238 retry: Option<PaymentPathRetry>,
240 error_code: Option<u16>,
242 error_data: Option<Vec<u8>>,
244 /// Used to indicate that ChannelManager::process_pending_htlc_forwards should be called at a
245 /// time in the future.
246 PendingHTLCsForwardable {
247 /// The minimum amount of time that should be waited prior to calling
248 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
249 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
250 /// now + 5*time_forwardable).
251 time_forwardable: Duration,
253 /// Used to indicate that an output which you should know how to spend was confirmed on chain
254 /// and is now spendable.
255 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
256 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
257 /// somewhere and spend them when you create on-chain transactions.
259 /// The outputs which you should store as spendable by you.
260 outputs: Vec<SpendableOutputDescriptor>,
262 /// This event is generated when a payment has been successfully forwarded through us and a
263 /// forwarding fee earned.
265 /// The fee, in milli-satoshis, which was earned as a result of the payment.
267 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
268 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
269 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
270 /// claimed the full value in millisatoshis from the source. In this case,
271 /// `claim_from_onchain_tx` will be set.
273 /// If the channel which sent us the payment has been force-closed, we will claim the funds
274 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
275 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
276 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
278 fee_earned_msat: Option<u64>,
279 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
281 claim_from_onchain_tx: bool,
283 /// Used to indicate that a channel with the given `channel_id` is in the process of closure.
285 /// The channel_id of the channel which has been closed. Note that on-chain transactions
286 /// resolving the channel are likely still awaiting confirmation.
287 channel_id: [u8; 32],
288 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or 0 for
289 /// an inbound channel. This will always be zero for objects serialized with LDK versions
290 /// prior to 0.0.102.
292 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
293 user_channel_id: u64,
294 /// The reason the channel was closed.
295 reason: ClosureReason
297 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
298 /// inputs for another purpose.
300 /// The channel_id of the channel which has been closed.
301 channel_id: [u8; 32],
302 /// The full transaction received from the user
303 transaction: Transaction
307 impl Writeable for Event {
308 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
310 &Event::FundingGenerationReady { .. } => {
312 // We never write out FundingGenerationReady events as, upon disconnection, peers
313 // drop any channels which have not yet exchanged funding_signed.
315 &Event::PaymentReceived { ref payment_hash, ref amt, ref purpose } => {
317 let mut payment_secret = None;
318 let mut user_payment_id = None;
319 let payment_preimage;
321 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret, user_payment_id: id } => {
322 payment_secret = Some(secret);
323 payment_preimage = *preimage;
324 user_payment_id = Some(id);
326 PaymentPurpose::SpontaneousPayment(preimage) => {
327 payment_preimage = Some(*preimage);
330 write_tlv_fields!(writer, {
331 (0, payment_hash, required),
332 (2, payment_secret, option),
334 (6, user_payment_id, option),
335 (8, payment_preimage, option),
338 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash} => {
340 write_tlv_fields!(writer, {
341 (0, payment_preimage, required),
342 (1, payment_hash, required),
343 (3, payment_id, option),
346 &Event::PaymentPathFailed {
347 ref payment_id, ref payment_hash, ref rejected_by_dest, ref network_update,
348 ref all_paths_failed, ref path, ref short_channel_id, ref retry,
356 error_code.write(writer)?;
358 error_data.write(writer)?;
359 write_tlv_fields!(writer, {
360 (0, payment_hash, required),
361 (1, network_update, option),
362 (2, rejected_by_dest, required),
363 (3, all_paths_failed, required),
365 (7, short_channel_id, option),
367 (11, payment_id, option),
370 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
372 // Note that we now ignore these on the read end as we'll re-generate them in
373 // ChannelManager, we write them here only for backwards compatibility.
375 &Event::SpendableOutputs { ref outputs } => {
377 write_tlv_fields!(writer, {
378 (0, VecWriteWrapper(outputs), required),
381 &Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
383 write_tlv_fields!(writer, {
384 (0, fee_earned_msat, option),
385 (2, claim_from_onchain_tx, required),
388 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
390 write_tlv_fields!(writer, {
391 (0, channel_id, required),
392 (1, user_channel_id, required),
393 (2, reason, required)
396 &Event::DiscardFunding { ref channel_id, ref transaction } => {
398 write_tlv_fields!(writer, {
399 (0, channel_id, required),
400 (2, transaction, required)
403 // Note that, going forward, all new events must only write data inside of
404 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
405 // data via `write_tlv_fields`.
410 impl MaybeReadable for Event {
411 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
412 match Readable::read(reader)? {
413 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
414 // unlike all other events, thus we return immediately here.
418 let mut payment_hash = PaymentHash([0; 32]);
419 let mut payment_preimage = None;
420 let mut payment_secret = None;
422 let mut user_payment_id = None;
423 read_tlv_fields!(reader, {
424 (0, payment_hash, required),
425 (2, payment_secret, option),
427 (6, user_payment_id, option),
428 (8, payment_preimage, option),
430 let purpose = match payment_secret {
431 Some(secret) => PaymentPurpose::InvoicePayment {
433 payment_secret: secret,
434 user_payment_id: if let Some(id) = user_payment_id {
436 } else { return Err(msgs::DecodeError::InvalidValue) }
438 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
439 None => return Err(msgs::DecodeError::InvalidValue),
441 Ok(Some(Event::PaymentReceived {
451 let mut payment_preimage = PaymentPreimage([0; 32]);
452 let mut payment_hash = None;
453 let mut payment_id = None;
454 read_tlv_fields!(reader, {
455 (0, payment_preimage, required),
456 (1, payment_hash, option),
457 (3, payment_id, option),
459 if payment_hash.is_none() {
460 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
462 Ok(Some(Event::PaymentSent {
465 payment_hash: payment_hash.unwrap(),
473 let error_code = Readable::read(reader)?;
475 let error_data = Readable::read(reader)?;
476 let mut payment_hash = PaymentHash([0; 32]);
477 let mut rejected_by_dest = false;
478 let mut network_update = None;
479 let mut all_paths_failed = Some(true);
480 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
481 let mut short_channel_id = None;
482 let mut retry = None;
483 let mut payment_id = None;
484 read_tlv_fields!(reader, {
485 (0, payment_hash, required),
486 (1, network_update, ignorable),
487 (2, rejected_by_dest, required),
488 (3, all_paths_failed, option),
490 (7, short_channel_id, option),
492 (11, payment_id, option),
494 Ok(Some(Event::PaymentPathFailed {
499 all_paths_failed: all_paths_failed.unwrap(),
514 let mut outputs = VecReadWrapper(Vec::new());
515 read_tlv_fields!(reader, {
516 (0, outputs, required),
518 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
524 let mut fee_earned_msat = None;
525 let mut claim_from_onchain_tx = false;
526 read_tlv_fields!(reader, {
527 (0, fee_earned_msat, option),
528 (2, claim_from_onchain_tx, required),
530 Ok(Some(Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx }))
536 let mut channel_id = [0; 32];
537 let mut reason = None;
538 let mut user_channel_id_opt = None;
539 read_tlv_fields!(reader, {
540 (0, channel_id, required),
541 (1, user_channel_id_opt, option),
542 (2, reason, ignorable),
544 if reason.is_none() { return Ok(None); }
545 let user_channel_id = if let Some(id) = user_channel_id_opt { id } else { 0 };
546 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: reason.unwrap() }))
552 let mut channel_id = [0; 32];
553 let mut transaction = Transaction{ version: 2, lock_time: 0, input: Vec::new(), output: Vec::new() };
554 read_tlv_fields!(reader, {
555 (0, channel_id, required),
556 (2, transaction, required),
558 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
562 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
563 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
566 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
567 // which prefixes the whole thing with a length BigSize. Because the event is
568 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
569 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
570 // exactly the number of bytes specified, ignoring them entirely.
571 let tlv_len: BigSize = Readable::read(reader)?;
572 FixedLengthReader::new(reader, tlv_len.0)
573 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
576 _ => Err(msgs::DecodeError::InvalidValue)
581 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
582 /// broadcast to most peers).
583 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
584 #[derive(Clone, Debug)]
585 pub enum MessageSendEvent {
586 /// Used to indicate that we've accepted a channel open and should send the accept_channel
587 /// message provided to the given peer.
589 /// The node_id of the node which should receive this message
591 /// The message which should be sent.
592 msg: msgs::AcceptChannel,
594 /// Used to indicate that we've initiated a channel open and should send the open_channel
595 /// message provided to the given peer.
597 /// The node_id of the node which should receive this message
599 /// The message which should be sent.
600 msg: msgs::OpenChannel,
602 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
604 /// The node_id of the node which should receive this message
606 /// The message which should be sent.
607 msg: msgs::FundingCreated,
609 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
611 /// The node_id of the node which should receive this message
613 /// The message which should be sent.
614 msg: msgs::FundingSigned,
616 /// Used to indicate that a funding_locked message should be sent to the peer with the given node_id.
618 /// The node_id of the node which should receive these message(s)
620 /// The funding_locked message which should be sent.
621 msg: msgs::FundingLocked,
623 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
624 SendAnnouncementSignatures {
625 /// The node_id of the node which should receive these message(s)
627 /// The announcement_signatures message which should be sent.
628 msg: msgs::AnnouncementSignatures,
630 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
631 /// message should be sent to the peer with the given node_id.
633 /// The node_id of the node which should receive these message(s)
635 /// The update messages which should be sent. ALL messages in the struct should be sent!
636 updates: msgs::CommitmentUpdate,
638 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
640 /// The node_id of the node which should receive this message
642 /// The message which should be sent.
643 msg: msgs::RevokeAndACK,
645 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
647 /// The node_id of the node which should receive this message
649 /// The message which should be sent.
650 msg: msgs::ClosingSigned,
652 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
654 /// The node_id of the node which should receive this message
656 /// The message which should be sent.
659 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
660 SendChannelReestablish {
661 /// The node_id of the node which should receive this message
663 /// The message which should be sent.
664 msg: msgs::ChannelReestablish,
666 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
667 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
669 /// Note that after doing so, you very likely (unless you did so very recently) want to call
670 /// ChannelManager::broadcast_node_announcement to trigger a BroadcastNodeAnnouncement event.
671 /// This ensures that any nodes which see our channel_announcement also have a relevant
672 /// node_announcement, including relevant feature flags which may be important for routing
673 /// through or to us.
674 BroadcastChannelAnnouncement {
675 /// The channel_announcement which should be sent.
676 msg: msgs::ChannelAnnouncement,
677 /// The followup channel_update which should be sent.
678 update_msg: msgs::ChannelUpdate,
680 /// Used to indicate that a node_announcement should be broadcast to all peers.
681 BroadcastNodeAnnouncement {
682 /// The node_announcement which should be sent.
683 msg: msgs::NodeAnnouncement,
685 /// Used to indicate that a channel_update should be broadcast to all peers.
686 BroadcastChannelUpdate {
687 /// The channel_update which should be sent.
688 msg: msgs::ChannelUpdate,
690 /// Used to indicate that a channel_update should be sent to a single peer.
691 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
692 /// private channel and we shouldn't be informing all of our peers of channel parameters.
694 /// The node_id of the node which should receive this message
696 /// The channel_update which should be sent.
697 msg: msgs::ChannelUpdate,
699 /// Broadcast an error downstream to be handled
701 /// The node_id of the node which should receive this message
703 /// The action which should be taken.
704 action: msgs::ErrorAction
706 /// Query a peer for channels with funding transaction UTXOs in a block range.
707 SendChannelRangeQuery {
708 /// The node_id of this message recipient
710 /// The query_channel_range which should be sent.
711 msg: msgs::QueryChannelRange,
713 /// Request routing gossip messages from a peer for a list of channels identified by
714 /// their short_channel_ids.
716 /// The node_id of this message recipient
718 /// The query_short_channel_ids which should be sent.
719 msg: msgs::QueryShortChannelIds,
721 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
722 /// emitted during processing of the query.
723 SendReplyChannelRange {
724 /// The node_id of this message recipient
726 /// The reply_channel_range which should be sent.
727 msg: msgs::ReplyChannelRange,
731 /// A trait indicating an object may generate message send events
732 pub trait MessageSendEventsProvider {
733 /// Gets the list of pending events which were generated by previous actions, clearing the list
735 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
738 /// A trait indicating an object may generate events.
740 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
744 /// See [`process_pending_events`] for requirements around event processing.
746 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
747 /// event since the last invocation. The handler must either act upon the event immediately
748 /// or preserve it for later handling.
750 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
751 /// consult the provider's documentation on the implication of processing events and how a handler
752 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
753 /// [`ChainMonitor::process_pending_events`]).
755 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
758 /// [`process_pending_events`]: Self::process_pending_events
759 /// [`handle_event`]: EventHandler::handle_event
760 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
761 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
762 pub trait EventsProvider {
763 /// Processes any events generated since the last call using the given event handler.
765 /// Subsequent calls must only process new events. However, handlers must be capable of handling
766 /// duplicate events across process restarts. This may occur if the provider was recovered from
767 /// an old state (i.e., it hadn't been successfully persisted after processing pending events).
768 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
771 /// A trait implemented for objects handling events from [`EventsProvider`].
772 pub trait EventHandler {
773 /// Handles the given [`Event`].
775 /// See [`EventsProvider`] for details that must be considered when implementing this method.
776 fn handle_event(&self, event: &Event);
779 impl<F> EventHandler for F where F: Fn(&Event) {
780 fn handle_event(&self, event: &Event) {