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,
197 /// The total fee which was spent at intermediate hops in this payment, across all paths.
199 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
200 /// overpayment to the recipient node.
202 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
203 /// overstate the amount paid, though this is unlikely.
205 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
206 fee_paid_msat: Option<u64>,
208 /// Indicates an outbound payment we made failed. Probably some intermediary node dropped
209 /// something. You may wish to retry with a different route.
211 /// The id returned by [`ChannelManager::send_payment`] and used with
212 /// [`ChannelManager::retry_payment`].
214 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
215 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
216 payment_id: Option<PaymentId>,
217 /// The hash which was given to ChannelManager::send_payment.
218 payment_hash: PaymentHash,
219 /// Indicates the payment was rejected for some reason by the recipient. This implies that
220 /// the payment has failed, not just the route in question. If this is not set, you may
221 /// retry the payment via a different route.
222 rejected_by_dest: bool,
223 /// Any failure information conveyed via the Onion return packet by a node along the failed
226 /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into
227 /// account the update. [`NetGraphMsgHandler`] is capable of doing this.
229 /// [`NetworkGraph`]: crate::routing::network_graph::NetworkGraph
230 /// [`NetGraphMsgHandler`]: crate::routing::network_graph::NetGraphMsgHandler
231 network_update: Option<NetworkUpdate>,
232 /// For both single-path and multi-path payments, this is set if all paths of the payment have
233 /// failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the
234 /// larger MPP payment were still in flight when this event was generated.
235 all_paths_failed: bool,
236 /// The payment path that failed.
238 /// The channel responsible for the failed payment path.
240 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
241 /// retried. May be `None` for older [`Event`] serializations.
242 short_channel_id: Option<u64>,
243 /// Parameters needed to compute a new [`Route`] when retrying the failed payment path.
245 /// See [`find_route`] for details.
247 /// [`Route`]: crate::routing::router::Route
248 /// [`find_route`]: crate::routing::router::find_route
249 retry: Option<RouteParameters>,
251 error_code: Option<u16>,
253 error_data: Option<Vec<u8>>,
255 /// Used to indicate that ChannelManager::process_pending_htlc_forwards should be called at a
256 /// time in the future.
257 PendingHTLCsForwardable {
258 /// The minimum amount of time that should be waited prior to calling
259 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
260 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
261 /// now + 5*time_forwardable).
262 time_forwardable: Duration,
264 /// Used to indicate that an output which you should know how to spend was confirmed on chain
265 /// and is now spendable.
266 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
267 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
268 /// somewhere and spend them when you create on-chain transactions.
270 /// The outputs which you should store as spendable by you.
271 outputs: Vec<SpendableOutputDescriptor>,
273 /// This event is generated when a payment has been successfully forwarded through us and a
274 /// forwarding fee earned.
276 /// The fee, in milli-satoshis, which was earned as a result of the payment.
278 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
279 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
280 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
281 /// claimed the full value in millisatoshis from the source. In this case,
282 /// `claim_from_onchain_tx` will be set.
284 /// If the channel which sent us the payment has been force-closed, we will claim the funds
285 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
286 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
287 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
289 fee_earned_msat: Option<u64>,
290 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
292 claim_from_onchain_tx: bool,
294 /// Used to indicate that a channel with the given `channel_id` is in the process of closure.
296 /// The channel_id of the channel which has been closed. Note that on-chain transactions
297 /// resolving the channel are likely still awaiting confirmation.
298 channel_id: [u8; 32],
299 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or 0 for
300 /// an inbound channel. This will always be zero for objects serialized with LDK versions
301 /// prior to 0.0.102.
303 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
304 user_channel_id: u64,
305 /// The reason the channel was closed.
306 reason: ClosureReason
308 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
309 /// inputs for another purpose.
311 /// The channel_id of the channel which has been closed.
312 channel_id: [u8; 32],
313 /// The full transaction received from the user
314 transaction: Transaction
318 impl Writeable for Event {
319 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
321 &Event::FundingGenerationReady { .. } => {
323 // We never write out FundingGenerationReady events as, upon disconnection, peers
324 // drop any channels which have not yet exchanged funding_signed.
326 &Event::PaymentReceived { ref payment_hash, ref amt, ref purpose } => {
328 let mut payment_secret = None;
329 let mut user_payment_id = None;
330 let payment_preimage;
332 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret, user_payment_id: id } => {
333 payment_secret = Some(secret);
334 payment_preimage = *preimage;
335 user_payment_id = Some(id);
337 PaymentPurpose::SpontaneousPayment(preimage) => {
338 payment_preimage = Some(*preimage);
341 write_tlv_fields!(writer, {
342 (0, payment_hash, required),
343 (2, payment_secret, option),
345 (6, user_payment_id, option),
346 (8, payment_preimage, option),
349 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
351 write_tlv_fields!(writer, {
352 (0, payment_preimage, required),
353 (1, payment_hash, required),
354 (3, payment_id, option),
355 (5, fee_paid_msat, option),
358 &Event::PaymentPathFailed {
359 ref payment_id, ref payment_hash, ref rejected_by_dest, ref network_update,
360 ref all_paths_failed, ref path, ref short_channel_id, ref retry,
368 error_code.write(writer)?;
370 error_data.write(writer)?;
371 write_tlv_fields!(writer, {
372 (0, payment_hash, required),
373 (1, network_update, option),
374 (2, rejected_by_dest, required),
375 (3, all_paths_failed, required),
377 (7, short_channel_id, option),
379 (11, payment_id, option),
382 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
384 // Note that we now ignore these on the read end as we'll re-generate them in
385 // ChannelManager, we write them here only for backwards compatibility.
387 &Event::SpendableOutputs { ref outputs } => {
389 write_tlv_fields!(writer, {
390 (0, VecWriteWrapper(outputs), required),
393 &Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
395 write_tlv_fields!(writer, {
396 (0, fee_earned_msat, option),
397 (2, claim_from_onchain_tx, required),
400 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
402 write_tlv_fields!(writer, {
403 (0, channel_id, required),
404 (1, user_channel_id, required),
405 (2, reason, required)
408 &Event::DiscardFunding { ref channel_id, ref transaction } => {
410 write_tlv_fields!(writer, {
411 (0, channel_id, required),
412 (2, transaction, required)
415 // Note that, going forward, all new events must only write data inside of
416 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
417 // data via `write_tlv_fields`.
422 impl MaybeReadable for Event {
423 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
424 match Readable::read(reader)? {
425 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
426 // unlike all other events, thus we return immediately here.
430 let mut payment_hash = PaymentHash([0; 32]);
431 let mut payment_preimage = None;
432 let mut payment_secret = None;
434 let mut user_payment_id = None;
435 read_tlv_fields!(reader, {
436 (0, payment_hash, required),
437 (2, payment_secret, option),
439 (6, user_payment_id, option),
440 (8, payment_preimage, option),
442 let purpose = match payment_secret {
443 Some(secret) => PaymentPurpose::InvoicePayment {
445 payment_secret: secret,
446 user_payment_id: if let Some(id) = user_payment_id {
448 } else { return Err(msgs::DecodeError::InvalidValue) }
450 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
451 None => return Err(msgs::DecodeError::InvalidValue),
453 Ok(Some(Event::PaymentReceived {
463 let mut payment_preimage = PaymentPreimage([0; 32]);
464 let mut payment_hash = None;
465 let mut payment_id = None;
466 let mut fee_paid_msat = None;
467 read_tlv_fields!(reader, {
468 (0, payment_preimage, required),
469 (1, payment_hash, option),
470 (3, payment_id, option),
471 (5, fee_paid_msat, option),
473 if payment_hash.is_none() {
474 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
476 Ok(Some(Event::PaymentSent {
479 payment_hash: payment_hash.unwrap(),
488 let error_code = Readable::read(reader)?;
490 let error_data = Readable::read(reader)?;
491 let mut payment_hash = PaymentHash([0; 32]);
492 let mut rejected_by_dest = false;
493 let mut network_update = None;
494 let mut all_paths_failed = Some(true);
495 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
496 let mut short_channel_id = None;
497 let mut retry = None;
498 let mut payment_id = None;
499 read_tlv_fields!(reader, {
500 (0, payment_hash, required),
501 (1, network_update, ignorable),
502 (2, rejected_by_dest, required),
503 (3, all_paths_failed, option),
505 (7, short_channel_id, option),
507 (11, payment_id, option),
509 Ok(Some(Event::PaymentPathFailed {
514 all_paths_failed: all_paths_failed.unwrap(),
529 let mut outputs = VecReadWrapper(Vec::new());
530 read_tlv_fields!(reader, {
531 (0, outputs, required),
533 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
539 let mut fee_earned_msat = None;
540 let mut claim_from_onchain_tx = false;
541 read_tlv_fields!(reader, {
542 (0, fee_earned_msat, option),
543 (2, claim_from_onchain_tx, required),
545 Ok(Some(Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx }))
551 let mut channel_id = [0; 32];
552 let mut reason = None;
553 let mut user_channel_id_opt = None;
554 read_tlv_fields!(reader, {
555 (0, channel_id, required),
556 (1, user_channel_id_opt, option),
557 (2, reason, ignorable),
559 if reason.is_none() { return Ok(None); }
560 let user_channel_id = if let Some(id) = user_channel_id_opt { id } else { 0 };
561 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: reason.unwrap() }))
567 let mut channel_id = [0; 32];
568 let mut transaction = Transaction{ version: 2, lock_time: 0, input: Vec::new(), output: Vec::new() };
569 read_tlv_fields!(reader, {
570 (0, channel_id, required),
571 (2, transaction, required),
573 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
577 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
578 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
581 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
582 // which prefixes the whole thing with a length BigSize. Because the event is
583 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
584 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
585 // exactly the number of bytes specified, ignoring them entirely.
586 let tlv_len: BigSize = Readable::read(reader)?;
587 FixedLengthReader::new(reader, tlv_len.0)
588 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
591 _ => Err(msgs::DecodeError::InvalidValue)
596 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
597 /// broadcast to most peers).
598 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
599 #[derive(Clone, Debug)]
600 pub enum MessageSendEvent {
601 /// Used to indicate that we've accepted a channel open and should send the accept_channel
602 /// message provided to the given peer.
604 /// The node_id of the node which should receive this message
606 /// The message which should be sent.
607 msg: msgs::AcceptChannel,
609 /// Used to indicate that we've initiated a channel open and should send the open_channel
610 /// message provided to the given peer.
612 /// The node_id of the node which should receive this message
614 /// The message which should be sent.
615 msg: msgs::OpenChannel,
617 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
619 /// The node_id of the node which should receive this message
621 /// The message which should be sent.
622 msg: msgs::FundingCreated,
624 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
626 /// The node_id of the node which should receive this message
628 /// The message which should be sent.
629 msg: msgs::FundingSigned,
631 /// Used to indicate that a funding_locked 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 funding_locked message which should be sent.
636 msg: msgs::FundingLocked,
638 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
639 SendAnnouncementSignatures {
640 /// The node_id of the node which should receive these message(s)
642 /// The announcement_signatures message which should be sent.
643 msg: msgs::AnnouncementSignatures,
645 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
646 /// message should be sent to the peer with the given node_id.
648 /// The node_id of the node which should receive these message(s)
650 /// The update messages which should be sent. ALL messages in the struct should be sent!
651 updates: msgs::CommitmentUpdate,
653 /// Used to indicate that a revoke_and_ack 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.
658 msg: msgs::RevokeAndACK,
660 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
662 /// The node_id of the node which should receive this message
664 /// The message which should be sent.
665 msg: msgs::ClosingSigned,
667 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
669 /// The node_id of the node which should receive this message
671 /// The message which should be sent.
674 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
675 SendChannelReestablish {
676 /// The node_id of the node which should receive this message
678 /// The message which should be sent.
679 msg: msgs::ChannelReestablish,
681 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
682 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
684 /// Note that after doing so, you very likely (unless you did so very recently) want to call
685 /// ChannelManager::broadcast_node_announcement to trigger a BroadcastNodeAnnouncement event.
686 /// This ensures that any nodes which see our channel_announcement also have a relevant
687 /// node_announcement, including relevant feature flags which may be important for routing
688 /// through or to us.
689 BroadcastChannelAnnouncement {
690 /// The channel_announcement which should be sent.
691 msg: msgs::ChannelAnnouncement,
692 /// The followup channel_update which should be sent.
693 update_msg: msgs::ChannelUpdate,
695 /// Used to indicate that a node_announcement should be broadcast to all peers.
696 BroadcastNodeAnnouncement {
697 /// The node_announcement which should be sent.
698 msg: msgs::NodeAnnouncement,
700 /// Used to indicate that a channel_update should be broadcast to all peers.
701 BroadcastChannelUpdate {
702 /// The channel_update which should be sent.
703 msg: msgs::ChannelUpdate,
705 /// Used to indicate that a channel_update should be sent to a single peer.
706 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
707 /// private channel and we shouldn't be informing all of our peers of channel parameters.
709 /// The node_id of the node which should receive this message
711 /// The channel_update which should be sent.
712 msg: msgs::ChannelUpdate,
714 /// Broadcast an error downstream to be handled
716 /// The node_id of the node which should receive this message
718 /// The action which should be taken.
719 action: msgs::ErrorAction
721 /// Query a peer for channels with funding transaction UTXOs in a block range.
722 SendChannelRangeQuery {
723 /// The node_id of this message recipient
725 /// The query_channel_range which should be sent.
726 msg: msgs::QueryChannelRange,
728 /// Request routing gossip messages from a peer for a list of channels identified by
729 /// their short_channel_ids.
731 /// The node_id of this message recipient
733 /// The query_short_channel_ids which should be sent.
734 msg: msgs::QueryShortChannelIds,
736 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
737 /// emitted during processing of the query.
738 SendReplyChannelRange {
739 /// The node_id of this message recipient
741 /// The reply_channel_range which should be sent.
742 msg: msgs::ReplyChannelRange,
746 /// A trait indicating an object may generate message send events
747 pub trait MessageSendEventsProvider {
748 /// Gets the list of pending events which were generated by previous actions, clearing the list
750 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
753 /// A trait indicating an object may generate events.
755 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
759 /// See [`process_pending_events`] for requirements around event processing.
761 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
762 /// event since the last invocation. The handler must either act upon the event immediately
763 /// or preserve it for later handling.
765 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
766 /// consult the provider's documentation on the implication of processing events and how a handler
767 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
768 /// [`ChainMonitor::process_pending_events`]).
770 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
773 /// [`process_pending_events`]: Self::process_pending_events
774 /// [`handle_event`]: EventHandler::handle_event
775 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
776 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
777 pub trait EventsProvider {
778 /// Processes any events generated since the last call using the given event handler.
780 /// Subsequent calls must only process new events. However, handlers must be capable of handling
781 /// duplicate events across process restarts. This may occur if the provider was recovered from
782 /// an old state (i.e., it hadn't been successfully persisted after processing pending events).
783 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
786 /// A trait implemented for objects handling events from [`EventsProvider`].
787 pub trait EventHandler {
788 /// Handles the given [`Event`].
790 /// See [`EventsProvider`] for details that must be considered when implementing this method.
791 fn handle_event(&self, event: &Event);
794 impl<F> EventHandler for F where F: Fn(&Event) {
795 fn handle_event(&self, event: &Event) {
800 impl<T: EventHandler> EventHandler for Arc<T> {
801 fn handle_event(&self, event: &Event) {
802 self.deref().handle_event(event)