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 core::fmt::Display for ClosureReason {
122 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
123 f.write_str("Channel closed because ")?;
125 ClosureReason::CounterpartyForceClosed { peer_msg } => {
126 f.write_str("counterparty force-closed with message ")?;
127 f.write_str(&peer_msg)
129 ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
130 ClosureReason::CooperativeClosure => f.write_str("the channel was cooperatively closed"),
131 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
132 ClosureReason::ProcessingError { err } => {
133 f.write_str("of an exception: ")?;
136 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
137 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
142 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
143 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
144 (2, HolderForceClosed) => {},
145 (6, CommitmentTxConfirmed) => {},
146 (4, CooperativeClosure) => {},
147 (8, ProcessingError) => { (1, err, required) },
148 (10, DisconnectedPeer) => {},
149 (12, OutdatedChannelManager) => {},
152 /// An Event which you should probably take some action in response to.
154 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
155 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
156 /// written as it makes no sense to respond to it after reconnecting to peers).
157 #[derive(Clone, Debug)]
159 /// Used to indicate that the client should generate a funding transaction with the given
160 /// parameters and then call ChannelManager::funding_transaction_generated.
161 /// Generated in ChannelManager message handling.
162 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
163 /// counterparty can steal your funds!
164 FundingGenerationReady {
165 /// The random channel_id we picked which you'll need to pass into
166 /// ChannelManager::funding_transaction_generated.
167 temporary_channel_id: [u8; 32],
168 /// The value, in satoshis, that the output should have.
169 channel_value_satoshis: u64,
170 /// The script which should be used in the transaction output.
171 output_script: Script,
172 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or 0 for
173 /// an inbound channel.
175 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
176 user_channel_id: u64,
178 /// Indicates we've received money! Just gotta dig out that payment preimage and feed it to
179 /// [`ChannelManager::claim_funds`] to get it....
180 /// Note that if the preimage is not known, you should call
181 /// [`ChannelManager::fail_htlc_backwards`] to free up resources for this HTLC and avoid
182 /// network congestion.
183 /// If you fail to call either [`ChannelManager::claim_funds`] or
184 /// [`ChannelManager::fail_htlc_backwards`] within the HTLC's timeout, the HTLC will be
185 /// automatically failed.
187 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
188 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
190 /// The hash for which the preimage should be handed to the ChannelManager.
191 payment_hash: PaymentHash,
192 /// The value, in thousandths of a satoshi, that this payment is for.
194 /// Information for claiming this received payment, based on whether the purpose of the
195 /// payment is to pay an invoice or to send a spontaneous payment.
196 purpose: PaymentPurpose,
198 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
199 /// and we got back the payment preimage for it).
201 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
202 /// event. In this situation, you SHOULD treat this payment as having succeeded.
204 /// The id returned by [`ChannelManager::send_payment`] and used with
205 /// [`ChannelManager::retry_payment`].
207 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
208 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
209 payment_id: Option<PaymentId>,
210 /// The preimage to the hash given to ChannelManager::send_payment.
211 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
212 /// store it somehow!
213 payment_preimage: PaymentPreimage,
214 /// The hash which was given to [`ChannelManager::send_payment`].
216 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
217 payment_hash: PaymentHash,
218 /// The total fee which was spent at intermediate hops in this payment, across all paths.
220 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
221 /// overpayment to the recipient node.
223 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
224 /// overstate the amount paid, though this is unlikely.
226 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
227 fee_paid_msat: Option<u64>,
229 /// Indicates an outbound payment we made failed. Probably some intermediary node dropped
230 /// something. You may wish to retry with a different route.
232 /// The id returned by [`ChannelManager::send_payment`] and used with
233 /// [`ChannelManager::retry_payment`].
235 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
236 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
237 payment_id: Option<PaymentId>,
238 /// The hash which was given to ChannelManager::send_payment.
239 payment_hash: PaymentHash,
240 /// Indicates the payment was rejected for some reason by the recipient. This implies that
241 /// the payment has failed, not just the route in question. If this is not set, you may
242 /// retry the payment via a different route.
243 rejected_by_dest: bool,
244 /// Any failure information conveyed via the Onion return packet by a node along the failed
247 /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into
248 /// account the update. [`NetGraphMsgHandler`] is capable of doing this.
250 /// [`NetworkGraph`]: crate::routing::network_graph::NetworkGraph
251 /// [`NetGraphMsgHandler`]: crate::routing::network_graph::NetGraphMsgHandler
252 network_update: Option<NetworkUpdate>,
253 /// For both single-path and multi-path payments, this is set if all paths of the payment have
254 /// failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the
255 /// larger MPP payment were still in flight when this event was generated.
256 all_paths_failed: bool,
257 /// The payment path that failed.
259 /// The channel responsible for the failed payment path.
261 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
262 /// retried. May be `None` for older [`Event`] serializations.
263 short_channel_id: Option<u64>,
264 /// Parameters needed to compute a new [`Route`] when retrying the failed payment path.
266 /// See [`find_route`] for details.
268 /// [`Route`]: crate::routing::router::Route
269 /// [`find_route`]: crate::routing::router::find_route
270 retry: Option<RouteParameters>,
272 error_code: Option<u16>,
274 error_data: Option<Vec<u8>>,
276 /// Used to indicate that ChannelManager::process_pending_htlc_forwards should be called at a
277 /// time in the future.
278 PendingHTLCsForwardable {
279 /// The minimum amount of time that should be waited prior to calling
280 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
281 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
282 /// now + 5*time_forwardable).
283 time_forwardable: Duration,
285 /// Used to indicate that an output which you should know how to spend was confirmed on chain
286 /// and is now spendable.
287 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
288 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
289 /// somewhere and spend them when you create on-chain transactions.
291 /// The outputs which you should store as spendable by you.
292 outputs: Vec<SpendableOutputDescriptor>,
294 /// This event is generated when a payment has been successfully forwarded through us and a
295 /// forwarding fee earned.
297 /// The fee, in milli-satoshis, which was earned as a result of the payment.
299 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
300 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
301 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
302 /// claimed the full value in millisatoshis from the source. In this case,
303 /// `claim_from_onchain_tx` will be set.
305 /// If the channel which sent us the payment has been force-closed, we will claim the funds
306 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
307 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
308 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
310 fee_earned_msat: Option<u64>,
311 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
313 claim_from_onchain_tx: bool,
315 /// Used to indicate that a channel with the given `channel_id` is in the process of closure.
317 /// The channel_id of the channel which has been closed. Note that on-chain transactions
318 /// resolving the channel are likely still awaiting confirmation.
319 channel_id: [u8; 32],
320 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or 0 for
321 /// an inbound channel. This will always be zero for objects serialized with LDK versions
322 /// prior to 0.0.102.
324 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
325 user_channel_id: u64,
326 /// The reason the channel was closed.
327 reason: ClosureReason
329 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
330 /// inputs for another purpose.
332 /// The channel_id of the channel which has been closed.
333 channel_id: [u8; 32],
334 /// The full transaction received from the user
335 transaction: Transaction
339 impl Writeable for Event {
340 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
342 &Event::FundingGenerationReady { .. } => {
344 // We never write out FundingGenerationReady events as, upon disconnection, peers
345 // drop any channels which have not yet exchanged funding_signed.
347 &Event::PaymentReceived { ref payment_hash, ref amt, ref purpose } => {
349 let mut payment_secret = None;
350 let mut user_payment_id = None;
351 let payment_preimage;
353 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret, user_payment_id: id } => {
354 payment_secret = Some(secret);
355 payment_preimage = *preimage;
356 user_payment_id = Some(id);
358 PaymentPurpose::SpontaneousPayment(preimage) => {
359 payment_preimage = Some(*preimage);
362 write_tlv_fields!(writer, {
363 (0, payment_hash, required),
364 (2, payment_secret, option),
366 (6, user_payment_id, option),
367 (8, payment_preimage, option),
370 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
372 write_tlv_fields!(writer, {
373 (0, payment_preimage, required),
374 (1, payment_hash, required),
375 (3, payment_id, option),
376 (5, fee_paid_msat, option),
379 &Event::PaymentPathFailed {
380 ref payment_id, ref payment_hash, ref rejected_by_dest, ref network_update,
381 ref all_paths_failed, ref path, ref short_channel_id, ref retry,
389 error_code.write(writer)?;
391 error_data.write(writer)?;
392 write_tlv_fields!(writer, {
393 (0, payment_hash, required),
394 (1, network_update, option),
395 (2, rejected_by_dest, required),
396 (3, all_paths_failed, required),
398 (7, short_channel_id, option),
400 (11, payment_id, option),
403 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
405 // Note that we now ignore these on the read end as we'll re-generate them in
406 // ChannelManager, we write them here only for backwards compatibility.
408 &Event::SpendableOutputs { ref outputs } => {
410 write_tlv_fields!(writer, {
411 (0, VecWriteWrapper(outputs), required),
414 &Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
416 write_tlv_fields!(writer, {
417 (0, fee_earned_msat, option),
418 (2, claim_from_onchain_tx, required),
421 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
423 write_tlv_fields!(writer, {
424 (0, channel_id, required),
425 (1, user_channel_id, required),
426 (2, reason, required)
429 &Event::DiscardFunding { ref channel_id, ref transaction } => {
431 write_tlv_fields!(writer, {
432 (0, channel_id, required),
433 (2, transaction, required)
436 // Note that, going forward, all new events must only write data inside of
437 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
438 // data via `write_tlv_fields`.
443 impl MaybeReadable for Event {
444 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
445 match Readable::read(reader)? {
446 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
447 // unlike all other events, thus we return immediately here.
451 let mut payment_hash = PaymentHash([0; 32]);
452 let mut payment_preimage = None;
453 let mut payment_secret = None;
455 let mut user_payment_id = None;
456 read_tlv_fields!(reader, {
457 (0, payment_hash, required),
458 (2, payment_secret, option),
460 (6, user_payment_id, option),
461 (8, payment_preimage, option),
463 let purpose = match payment_secret {
464 Some(secret) => PaymentPurpose::InvoicePayment {
466 payment_secret: secret,
467 user_payment_id: if let Some(id) = user_payment_id {
469 } else { return Err(msgs::DecodeError::InvalidValue) }
471 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
472 None => return Err(msgs::DecodeError::InvalidValue),
474 Ok(Some(Event::PaymentReceived {
484 let mut payment_preimage = PaymentPreimage([0; 32]);
485 let mut payment_hash = None;
486 let mut payment_id = None;
487 let mut fee_paid_msat = None;
488 read_tlv_fields!(reader, {
489 (0, payment_preimage, required),
490 (1, payment_hash, option),
491 (3, payment_id, option),
492 (5, fee_paid_msat, option),
494 if payment_hash.is_none() {
495 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
497 Ok(Some(Event::PaymentSent {
500 payment_hash: payment_hash.unwrap(),
509 let error_code = Readable::read(reader)?;
511 let error_data = Readable::read(reader)?;
512 let mut payment_hash = PaymentHash([0; 32]);
513 let mut rejected_by_dest = false;
514 let mut network_update = None;
515 let mut all_paths_failed = Some(true);
516 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
517 let mut short_channel_id = None;
518 let mut retry = None;
519 let mut payment_id = None;
520 read_tlv_fields!(reader, {
521 (0, payment_hash, required),
522 (1, network_update, ignorable),
523 (2, rejected_by_dest, required),
524 (3, all_paths_failed, option),
526 (7, short_channel_id, option),
528 (11, payment_id, option),
530 Ok(Some(Event::PaymentPathFailed {
535 all_paths_failed: all_paths_failed.unwrap(),
550 let mut outputs = VecReadWrapper(Vec::new());
551 read_tlv_fields!(reader, {
552 (0, outputs, required),
554 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
560 let mut fee_earned_msat = None;
561 let mut claim_from_onchain_tx = false;
562 read_tlv_fields!(reader, {
563 (0, fee_earned_msat, option),
564 (2, claim_from_onchain_tx, required),
566 Ok(Some(Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx }))
572 let mut channel_id = [0; 32];
573 let mut reason = None;
574 let mut user_channel_id_opt = None;
575 read_tlv_fields!(reader, {
576 (0, channel_id, required),
577 (1, user_channel_id_opt, option),
578 (2, reason, ignorable),
580 if reason.is_none() { return Ok(None); }
581 let user_channel_id = if let Some(id) = user_channel_id_opt { id } else { 0 };
582 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: reason.unwrap() }))
588 let mut channel_id = [0; 32];
589 let mut transaction = Transaction{ version: 2, lock_time: 0, input: Vec::new(), output: Vec::new() };
590 read_tlv_fields!(reader, {
591 (0, channel_id, required),
592 (2, transaction, required),
594 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
598 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
599 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
602 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
603 // which prefixes the whole thing with a length BigSize. Because the event is
604 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
605 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
606 // exactly the number of bytes specified, ignoring them entirely.
607 let tlv_len: BigSize = Readable::read(reader)?;
608 FixedLengthReader::new(reader, tlv_len.0)
609 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
612 _ => Err(msgs::DecodeError::InvalidValue)
617 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
618 /// broadcast to most peers).
619 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
620 #[derive(Clone, Debug)]
621 pub enum MessageSendEvent {
622 /// Used to indicate that we've accepted a channel open and should send the accept_channel
623 /// message provided to the given peer.
625 /// The node_id of the node which should receive this message
627 /// The message which should be sent.
628 msg: msgs::AcceptChannel,
630 /// Used to indicate that we've initiated a channel open and should send the open_channel
631 /// message provided to the given peer.
633 /// The node_id of the node which should receive this message
635 /// The message which should be sent.
636 msg: msgs::OpenChannel,
638 /// Used to indicate that a funding_created 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::FundingCreated,
645 /// Used to indicate that a funding_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::FundingSigned,
652 /// Used to indicate that a funding_locked message should be sent to the peer with the given node_id.
654 /// The node_id of the node which should receive these message(s)
656 /// The funding_locked message which should be sent.
657 msg: msgs::FundingLocked,
659 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
660 SendAnnouncementSignatures {
661 /// The node_id of the node which should receive these message(s)
663 /// The announcement_signatures message which should be sent.
664 msg: msgs::AnnouncementSignatures,
666 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
667 /// message should be sent to the peer with the given node_id.
669 /// The node_id of the node which should receive these message(s)
671 /// The update messages which should be sent. ALL messages in the struct should be sent!
672 updates: msgs::CommitmentUpdate,
674 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
676 /// The node_id of the node which should receive this message
678 /// The message which should be sent.
679 msg: msgs::RevokeAndACK,
681 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
683 /// The node_id of the node which should receive this message
685 /// The message which should be sent.
686 msg: msgs::ClosingSigned,
688 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
690 /// The node_id of the node which should receive this message
692 /// The message which should be sent.
695 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
696 SendChannelReestablish {
697 /// The node_id of the node which should receive this message
699 /// The message which should be sent.
700 msg: msgs::ChannelReestablish,
702 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
703 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
705 /// Note that after doing so, you very likely (unless you did so very recently) want to call
706 /// ChannelManager::broadcast_node_announcement to trigger a BroadcastNodeAnnouncement event.
707 /// This ensures that any nodes which see our channel_announcement also have a relevant
708 /// node_announcement, including relevant feature flags which may be important for routing
709 /// through or to us.
710 BroadcastChannelAnnouncement {
711 /// The channel_announcement which should be sent.
712 msg: msgs::ChannelAnnouncement,
713 /// The followup channel_update which should be sent.
714 update_msg: msgs::ChannelUpdate,
716 /// Used to indicate that a node_announcement should be broadcast to all peers.
717 BroadcastNodeAnnouncement {
718 /// The node_announcement which should be sent.
719 msg: msgs::NodeAnnouncement,
721 /// Used to indicate that a channel_update should be broadcast to all peers.
722 BroadcastChannelUpdate {
723 /// The channel_update which should be sent.
724 msg: msgs::ChannelUpdate,
726 /// Used to indicate that a channel_update should be sent to a single peer.
727 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
728 /// private channel and we shouldn't be informing all of our peers of channel parameters.
730 /// The node_id of the node which should receive this message
732 /// The channel_update which should be sent.
733 msg: msgs::ChannelUpdate,
735 /// Broadcast an error downstream to be handled
737 /// The node_id of the node which should receive this message
739 /// The action which should be taken.
740 action: msgs::ErrorAction
742 /// Query a peer for channels with funding transaction UTXOs in a block range.
743 SendChannelRangeQuery {
744 /// The node_id of this message recipient
746 /// The query_channel_range which should be sent.
747 msg: msgs::QueryChannelRange,
749 /// Request routing gossip messages from a peer for a list of channels identified by
750 /// their short_channel_ids.
752 /// The node_id of this message recipient
754 /// The query_short_channel_ids which should be sent.
755 msg: msgs::QueryShortChannelIds,
757 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
758 /// emitted during processing of the query.
759 SendReplyChannelRange {
760 /// The node_id of this message recipient
762 /// The reply_channel_range which should be sent.
763 msg: msgs::ReplyChannelRange,
767 /// A trait indicating an object may generate message send events
768 pub trait MessageSendEventsProvider {
769 /// Gets the list of pending events which were generated by previous actions, clearing the list
771 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
774 /// A trait indicating an object may generate events.
776 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
780 /// See [`process_pending_events`] for requirements around event processing.
782 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
783 /// event since the last invocation. The handler must either act upon the event immediately
784 /// or preserve it for later handling.
786 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
787 /// consult the provider's documentation on the implication of processing events and how a handler
788 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
789 /// [`ChainMonitor::process_pending_events`]).
791 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
794 /// [`process_pending_events`]: Self::process_pending_events
795 /// [`handle_event`]: EventHandler::handle_event
796 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
797 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
798 pub trait EventsProvider {
799 /// Processes any events generated since the last call using the given event handler.
801 /// Subsequent calls must only process new events. However, handlers must be capable of handling
802 /// duplicate events across process restarts. This may occur if the provider was recovered from
803 /// an old state (i.e., it hadn't been successfully persisted after processing pending events).
804 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
807 /// A trait implemented for objects handling events from [`EventsProvider`].
808 pub trait EventHandler {
809 /// Handles the given [`Event`].
811 /// See [`EventsProvider`] for details that must be considered when implementing this method.
812 fn handle_event(&self, event: &Event);
815 impl<F> EventHandler for F where F: Fn(&Event) {
816 fn handle_event(&self, event: &Event) {
821 impl<T: EventHandler> EventHandler for Arc<T> {
822 fn handle_event(&self, event: &Event) {
823 self.deref().handle_event(event)