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 pub mod bump_transaction;
19 pub use bump_transaction::BumpTransactionEvent;
21 use crate::sign::SpendableOutputDescriptor;
22 use crate::ln::channelmanager::{InterceptId, PaymentId, RecipientOnionFields};
23 use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
24 use crate::ln::features::ChannelTypeFeatures;
26 use crate::ln::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
27 use crate::chain::transaction;
28 use crate::routing::gossip::NetworkUpdate;
29 use crate::util::errors::APIError;
30 use crate::util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, RequiredWrapper, UpgradableRequired, WithoutLength};
31 use crate::util::string::UntrustedString;
32 use crate::routing::router::{BlindedTail, Path, RouteHop, RouteParameters};
34 use bitcoin::{Transaction, OutPoint};
35 use bitcoin::blockdata::locktime::absolute::LockTime;
36 use bitcoin::blockdata::script::ScriptBuf;
37 use bitcoin::hashes::Hash;
38 use bitcoin::hashes::sha256::Hash as Sha256;
39 use bitcoin::secp256k1::PublicKey;
41 use crate::prelude::*;
42 use core::time::Duration;
46 /// Some information provided on receipt of payment depends on whether the payment received is a
47 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
48 #[derive(Clone, Debug, PartialEq, Eq)]
49 pub enum PaymentPurpose {
50 /// Information for receiving a payment that we generated an invoice for.
52 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
53 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
54 /// [`ChannelManager::claim_funds`].
56 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
57 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
58 payment_preimage: Option<PaymentPreimage>,
59 /// The "payment secret". This authenticates the sender to the recipient, preventing a
60 /// number of deanonymization attacks during the routing process.
61 /// It is provided here for your reference, however its accuracy is enforced directly by
62 /// [`ChannelManager`] using the values you previously provided to
63 /// [`ChannelManager::create_inbound_payment`] or
64 /// [`ChannelManager::create_inbound_payment_for_hash`].
66 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
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
69 payment_secret: PaymentSecret,
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),
77 /// Returns the preimage for this payment, if it is known.
78 pub fn preimage(&self) -> Option<PaymentPreimage> {
80 PaymentPurpose::InvoicePayment { payment_preimage, .. } => *payment_preimage,
81 PaymentPurpose::SpontaneousPayment(preimage) => Some(*preimage),
86 impl_writeable_tlv_based_enum!(PaymentPurpose,
87 (0, InvoicePayment) => {
88 (0, payment_preimage, option),
89 (2, payment_secret, required),
91 (2, SpontaneousPayment)
94 /// Information about an HTLC that is part of a payment that can be claimed.
95 #[derive(Clone, Debug, PartialEq, Eq)]
96 pub struct ClaimedHTLC {
97 /// The `channel_id` of the channel over which the HTLC was received.
98 pub channel_id: ChannelId,
99 /// The `user_channel_id` of the channel over which the HTLC was received. This is the value
100 /// passed in to [`ChannelManager::create_channel`] for outbound channels, or to
101 /// [`ChannelManager::accept_inbound_channel`] for inbound channels if
102 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
103 /// `user_channel_id` will be randomized for an inbound channel.
105 /// This field will be zero for a payment that was serialized prior to LDK version 0.0.117. (This
106 /// should only happen in the case that a payment was claimable prior to LDK version 0.0.117, but
107 /// was not actually claimed until after upgrading.)
109 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
110 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
111 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
112 pub user_channel_id: u128,
113 /// The block height at which this HTLC expires.
114 pub cltv_expiry: u32,
115 /// The amount (in msats) of this part of an MPP.
117 /// The extra fee our counterparty skimmed off the top of this HTLC, if any.
119 /// This value will always be 0 for [`ClaimedHTLC`]s serialized with LDK versions prior to
121 pub counterparty_skimmed_fee_msat: u64,
123 impl_writeable_tlv_based!(ClaimedHTLC, {
124 (0, channel_id, required),
125 (1, counterparty_skimmed_fee_msat, (default_value, 0u64)),
126 (2, user_channel_id, required),
127 (4, cltv_expiry, required),
128 (6, value_msat, required),
131 /// When the payment path failure took place and extra details about it. [`PathFailure::OnPath`] may
132 /// contain a [`NetworkUpdate`] that needs to be applied to the [`NetworkGraph`].
134 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
135 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
136 #[derive(Clone, Debug, Eq, PartialEq)]
137 pub enum PathFailure {
138 /// We failed to initially send the payment and no HTLC was committed to. Contains the relevant
141 /// The error surfaced from initial send.
144 /// A hop on the path failed to forward our payment.
146 /// If present, this [`NetworkUpdate`] should be applied to the [`NetworkGraph`] so that routing
147 /// decisions can take into account the update.
149 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
150 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
151 network_update: Option<NetworkUpdate>,
155 impl_writeable_tlv_based_enum_upgradable!(PathFailure,
157 (0, network_update, upgradable_option),
159 (2, InitialSend) => {
160 (0, err, upgradable_required),
164 #[derive(Clone, Debug, PartialEq, Eq)]
165 /// The reason the channel was closed. See individual variants for more details.
166 pub enum ClosureReason {
167 /// Closure generated from receiving a peer error message.
169 /// Our counterparty may have broadcasted their latest commitment state, and we have
171 CounterpartyForceClosed {
172 /// The error which the peer sent us.
174 /// Be careful about printing the peer_msg, a well-crafted message could exploit
175 /// a security vulnerability in the terminal emulator or the logging subsystem.
176 /// To be safe, use `Display` on `UntrustedString`
178 /// [`UntrustedString`]: crate::util::string::UntrustedString
179 peer_msg: UntrustedString,
181 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
183 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
185 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
186 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
187 // Can be removed once we disallow downgrading to 0.0.121
188 LegacyCooperativeClosure,
189 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
190 /// the cooperative close transaction. This indicates that the shutdown was initiated by our
192 CounterpartyInitiatedCooperativeClosure,
193 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
194 /// the cooperative close transaction. This indicates that the shutdown was initiated by us.
195 LocallyInitiatedCooperativeClosure,
196 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
197 /// commitment transaction came from our counterparty, but it may also have come from
198 /// a copy of our own `ChannelMonitor`.
199 CommitmentTxConfirmed,
200 /// The funding transaction failed to confirm in a timely manner on an inbound channel.
202 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
204 /// A developer-readable error message which we generated.
207 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
208 /// forget the channel entirely - we can attempt again if the peer reconnects.
210 /// This includes cases where we restarted prior to funding completion, including prior to the
211 /// initial [`ChannelMonitor`] persistence completing.
213 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
214 /// peer because of mutual incompatibility between us and our channel counterparty.
216 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
218 /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
219 /// the [`ChannelManager`] deserialized.
221 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
222 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
223 OutdatedChannelManager,
224 /// The counterparty requested a cooperative close of a channel that had not been funded yet.
225 /// The channel has been immediately closed.
226 CounterpartyCoopClosedUnfundedChannel,
227 /// Another channel in the same funding batch closed before the funding transaction
228 /// was ready to be broadcast.
232 impl core::fmt::Display for ClosureReason {
233 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
234 f.write_str("Channel closed because ")?;
236 ClosureReason::CounterpartyForceClosed { peer_msg } => {
237 f.write_fmt(format_args!("counterparty force-closed with message: {}", peer_msg))
239 ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
240 ClosureReason::LegacyCooperativeClosure => f.write_str("the channel was cooperatively closed"),
241 ClosureReason::CounterpartyInitiatedCooperativeClosure => f.write_str("the channel was cooperatively closed by our peer"),
242 ClosureReason::LocallyInitiatedCooperativeClosure => f.write_str("the channel was cooperatively closed by us"),
243 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
244 ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
245 ClosureReason::ProcessingError { err } => {
246 f.write_str("of an exception: ")?;
249 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
250 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
251 ClosureReason::CounterpartyCoopClosedUnfundedChannel => f.write_str("the peer requested the unfunded channel be closed"),
252 ClosureReason::FundingBatchClosure => f.write_str("another channel in the same funding batch closed"),
257 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
258 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
259 (1, FundingTimedOut) => {},
260 (2, HolderForceClosed) => {},
261 (6, CommitmentTxConfirmed) => {},
262 (4, LegacyCooperativeClosure) => {},
263 (8, ProcessingError) => { (1, err, required) },
264 (10, DisconnectedPeer) => {},
265 (12, OutdatedChannelManager) => {},
266 (13, CounterpartyCoopClosedUnfundedChannel) => {},
267 (15, FundingBatchClosure) => {},
268 (17, CounterpartyInitiatedCooperativeClosure) => {},
269 (19, LocallyInitiatedCooperativeClosure) => {},
272 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
273 #[derive(Clone, Debug, PartialEq, Eq)]
274 pub enum HTLCDestination {
275 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
276 /// there is insufficient capacity in our outbound channel.
278 /// The `node_id` of the next node. For backwards compatibility, this field is
279 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
280 /// counterparty node information.
281 node_id: Option<PublicKey>,
282 /// The outgoing `channel_id` between us and the next node.
283 channel_id: ChannelId,
285 /// Scenario where we are unsure of the next node to forward the HTLC to.
287 /// Short channel id we are requesting to forward an HTLC to.
288 requested_forward_scid: u64,
290 /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
293 /// Short channel id we are requesting to forward an HTLC to.
294 requested_forward_scid: u64
296 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
297 /// but is invalid for some reason, so we reject it.
299 /// Some of the reasons may include:
301 /// * Excess HTLCs for a payment that we have already fully received, over-paying for the
303 /// * The counterparty node modified the HTLC in transit,
304 /// * A probing attack where an intermediary node is trying to detect if we are the ultimate
305 /// recipient for a payment.
307 /// The payment hash of the payment we attempted to process.
308 payment_hash: PaymentHash
312 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
313 (0, NextHopChannel) => {
314 (0, node_id, required),
315 (2, channel_id, required),
317 (1, InvalidForward) => {
318 (0, requested_forward_scid, required),
320 (2, UnknownNextHop) => {
321 (0, requested_forward_scid, required),
323 (4, FailedPayment) => {
324 (0, payment_hash, required),
328 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
329 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
330 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
331 /// intercepts in upcoming work.
332 enum InterceptNextHop {
334 requested_next_hop_scid: u64,
338 impl_writeable_tlv_based_enum!(InterceptNextHop,
340 (0, requested_next_hop_scid, required),
344 /// The reason the payment failed. Used in [`Event::PaymentFailed`].
345 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
346 pub enum PaymentFailureReason {
347 /// The intended recipient rejected our payment.
349 /// The user chose to abandon this payment by calling [`ChannelManager::abandon_payment`].
351 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
353 /// We exhausted all of our retry attempts while trying to send the payment, or we
354 /// exhausted the [`Retry::Timeout`] if the user set one. If at any point a retry
355 /// attempt failed while being forwarded along the path, an [`Event::PaymentPathFailed`] will
356 /// have come before this.
358 /// [`Retry::Timeout`]: crate::ln::channelmanager::Retry::Timeout
360 /// The payment expired while retrying, based on the provided
361 /// [`PaymentParameters::expiry_time`].
363 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
365 /// We failed to find a route while retrying the payment.
367 /// This error should generally never happen. This likely means that there is a problem with
372 impl_writeable_tlv_based_enum!(PaymentFailureReason,
373 (0, RecipientRejected) => {},
374 (2, UserAbandoned) => {},
375 (4, RetriesExhausted) => {},
376 (6, PaymentExpired) => {},
377 (8, RouteNotFound) => {},
378 (10, UnexpectedError) => {}, ;
381 /// An Event which you should probably take some action in response to.
383 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
384 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
385 /// written as it makes no sense to respond to it after reconnecting to peers).
386 #[derive(Clone, Debug, PartialEq, Eq)]
388 /// Used to indicate that the client should generate a funding transaction with the given
389 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
390 /// Generated in [`ChannelManager`] message handling.
391 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
392 /// counterparty can steal your funds!
394 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
395 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
396 FundingGenerationReady {
397 /// The random channel_id we picked which you'll need to pass into
398 /// [`ChannelManager::funding_transaction_generated`].
400 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
401 temporary_channel_id: ChannelId,
402 /// The counterparty's node_id, which you'll need to pass back into
403 /// [`ChannelManager::funding_transaction_generated`].
405 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
406 counterparty_node_id: PublicKey,
407 /// The value, in satoshis, that the output should have.
408 channel_value_satoshis: u64,
409 /// The script which should be used in the transaction output.
410 output_script: ScriptBuf,
411 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
412 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
413 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
414 /// `user_channel_id` will be randomized for an inbound channel. This may be zero for objects
415 /// serialized with LDK versions prior to 0.0.113.
417 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
418 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
419 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
420 user_channel_id: u128,
422 /// Indicates that we've been offered a payment and it needs to be claimed via calling
423 /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
425 /// Note that if the preimage is not known, you should call
426 /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
427 /// to free up resources for this HTLC and avoid network congestion.
429 /// If [`Event::PaymentClaimable::onion_fields`] is `Some`, and includes custom TLVs with even type
430 /// numbers, you should use [`ChannelManager::fail_htlc_backwards_with_reason`] with
431 /// [`FailureCode::InvalidOnionPayload`] if you fail to understand and handle the contents, or
432 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`] upon successful handling.
433 /// If you don't intend to check for custom TLVs, you can simply use
434 /// [`ChannelManager::claim_funds`], which will automatically fail back even custom TLVs.
436 /// If you fail to call [`ChannelManager::claim_funds`],
437 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`],
438 /// [`ChannelManager::fail_htlc_backwards`], or
439 /// [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will
440 /// be automatically failed.
443 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
444 /// `PaymentClaimable` events may be generated for the same payment. In such a case it is
445 /// polite (and required in the lightning specification) to fail the payment the second time
446 /// and give the sender their money back rather than accepting double payment.
449 /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
451 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
452 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`]: crate::ln::channelmanager::ChannelManager::claim_funds_with_known_custom_tlvs
453 /// [`FailureCode::InvalidOnionPayload`]: crate::ln::channelmanager::FailureCode::InvalidOnionPayload
454 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
455 /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
457 /// The node that will receive the payment after it has been claimed.
458 /// This is useful to identify payments received via [phantom nodes].
459 /// This field will always be filled in when the event was generated by LDK versions
460 /// 0.0.113 and above.
462 /// [phantom nodes]: crate::sign::PhantomKeysManager
463 receiver_node_id: Option<PublicKey>,
464 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
465 /// not stop you from registering duplicate payment hashes for inbound payments.
466 payment_hash: PaymentHash,
467 /// The fields in the onion which were received with each HTLC. Only fields which were
468 /// identical in each HTLC involved in the payment will be included here.
470 /// Payments received on LDK versions prior to 0.0.115 will have this field unset.
471 onion_fields: Option<RecipientOnionFields>,
472 /// The value, in thousandths of a satoshi, that this payment is claimable for. May be greater
473 /// than the invoice amount.
475 /// May be less than the invoice amount if [`ChannelConfig::accept_underpaying_htlcs`] is set
476 /// and the previous hop took an extra fee.
479 /// If [`ChannelConfig::accept_underpaying_htlcs`] is set and you claim without verifying this
480 /// field, you may lose money!
482 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
484 /// The value, in thousands of a satoshi, that was skimmed off of this payment as an extra fee
485 /// taken by our channel counterparty.
487 /// Will always be 0 unless [`ChannelConfig::accept_underpaying_htlcs`] is set.
489 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
490 counterparty_skimmed_fee_msat: u64,
491 /// Information for claiming this received payment, based on whether the purpose of the
492 /// payment is to pay an invoice or to send a spontaneous payment.
493 purpose: PaymentPurpose,
494 /// The `channel_id` indicating over which channel we received the payment.
495 via_channel_id: Option<ChannelId>,
496 /// The `user_channel_id` indicating over which channel we received the payment.
497 via_user_channel_id: Option<u128>,
498 /// The block height at which this payment will be failed back and will no longer be
499 /// eligible for claiming.
501 /// Prior to this height, a call to [`ChannelManager::claim_funds`] is guaranteed to
502 /// succeed, however you should wait for [`Event::PaymentClaimed`] to be sure.
504 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
505 claim_deadline: Option<u32>,
507 /// Indicates a payment has been claimed and we've received money!
509 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
510 /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
511 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
512 /// [`Event::PaymentClaimable`] event.
515 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
516 /// `PaymentClaimable` events may be generated for the same payment. If you then call
517 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
518 /// multiple `PaymentClaimed` events.
520 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
522 /// The node that received the payment.
523 /// This is useful to identify payments which were received via [phantom nodes].
524 /// This field will always be filled in when the event was generated by LDK versions
525 /// 0.0.113 and above.
527 /// [phantom nodes]: crate::sign::PhantomKeysManager
528 receiver_node_id: Option<PublicKey>,
529 /// The payment hash of the claimed payment. Note that LDK will not stop you from
530 /// registering duplicate payment hashes for inbound payments.
531 payment_hash: PaymentHash,
532 /// The value, in thousandths of a satoshi, that this payment is for. May be greater than the
535 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
536 /// spontaneous payment.
537 purpose: PaymentPurpose,
538 /// The HTLCs that comprise the claimed payment. This will be empty for events serialized prior
539 /// to LDK version 0.0.117.
540 htlcs: Vec<ClaimedHTLC>,
541 /// The sender-intended sum total of all the MPP parts. This will be `None` for events
542 /// serialized prior to LDK version 0.0.117.
543 sender_intended_total_msat: Option<u64>,
545 /// Indicates that a peer connection with a node is needed in order to send an [`OnionMessage`].
547 /// Typically, this happens when a [`MessageRouter`] is unable to find a complete path to a
548 /// [`Destination`]. Once a connection is established, any messages buffered by an
549 /// [`OnionMessageHandler`] may be sent.
551 /// This event will not be generated for onion message forwards; only for sends including
552 /// replies. Handlers should connect to the node otherwise any buffered messages may be lost.
554 /// [`OnionMessage`]: msgs::OnionMessage
555 /// [`MessageRouter`]: crate::onion_message::messenger::MessageRouter
556 /// [`Destination`]: crate::onion_message::messenger::Destination
557 /// [`OnionMessageHandler`]: crate::ln::msgs::OnionMessageHandler
559 /// The node id for the node needing a connection.
561 /// Sockets for connecting to the node.
562 addresses: Vec<msgs::SocketAddress>,
564 /// Indicates a request for an invoice failed to yield a response in a reasonable amount of time
565 /// or was explicitly abandoned by [`ChannelManager::abandon_payment`]. This may be for an
566 /// [`InvoiceRequest`] sent for an [`Offer`] or for a [`Refund`] that hasn't been redeemed.
568 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
569 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
570 /// [`Offer`]: crate::offers::offer::Offer
571 /// [`Refund`]: crate::offers::refund::Refund
572 InvoiceRequestFailed {
573 /// The `payment_id` to have been associated with payment for the requested invoice.
574 payment_id: PaymentId,
576 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
577 /// and we got back the payment preimage for it).
579 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
580 /// event. In this situation, you SHOULD treat this payment as having succeeded.
582 /// The `payment_id` passed to [`ChannelManager::send_payment`].
584 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
585 payment_id: Option<PaymentId>,
586 /// The preimage to the hash given to ChannelManager::send_payment.
587 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
588 /// store it somehow!
589 payment_preimage: PaymentPreimage,
590 /// The hash that was given to [`ChannelManager::send_payment`].
592 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
593 payment_hash: PaymentHash,
594 /// The total fee which was spent at intermediate hops in this payment, across all paths.
596 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
597 /// overpayment to the recipient node.
599 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
600 /// overstate the amount paid, though this is unlikely.
602 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
603 fee_paid_msat: Option<u64>,
605 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
606 /// provide failure information for each path attempt in the payment, including retries.
608 /// This event is provided once there are no further pending HTLCs for the payment and the
609 /// payment is no longer retryable, due either to the [`Retry`] provided or
610 /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
612 /// In exceedingly rare cases, it is possible that an [`Event::PaymentFailed`] is generated for
613 /// a payment after an [`Event::PaymentSent`] event for this same payment has already been
614 /// received and processed. In this case, the [`Event::PaymentFailed`] event MUST be ignored,
615 /// and the payment MUST be treated as having succeeded.
617 /// [`Retry`]: crate::ln::channelmanager::Retry
618 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
620 /// The `payment_id` passed to [`ChannelManager::send_payment`].
622 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
623 payment_id: PaymentId,
624 /// The hash that was given to [`ChannelManager::send_payment`].
626 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
627 payment_hash: PaymentHash,
628 /// The reason the payment failed. This is only `None` for events generated or serialized
629 /// by versions prior to 0.0.115.
630 reason: Option<PaymentFailureReason>,
632 /// Indicates that a path for an outbound payment was successful.
634 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
635 /// [`Event::PaymentSent`] for obtaining the payment preimage.
636 PaymentPathSuccessful {
637 /// The `payment_id` passed to [`ChannelManager::send_payment`].
639 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
640 payment_id: PaymentId,
641 /// The hash that was given to [`ChannelManager::send_payment`].
643 /// This will be `Some` for all payments which completed on LDK 0.0.104 or later.
645 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
646 payment_hash: Option<PaymentHash>,
647 /// The payment path that was successful.
649 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
652 /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
655 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
656 /// [`Event::PaymentFailed`].
658 /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
661 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
663 /// The `payment_id` passed to [`ChannelManager::send_payment`].
665 /// This will be `Some` for all payment paths which failed on LDK 0.0.103 or later.
667 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
668 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
669 payment_id: Option<PaymentId>,
670 /// The hash that was given to [`ChannelManager::send_payment`].
672 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
673 payment_hash: PaymentHash,
674 /// Indicates the payment was rejected for some reason by the recipient. This implies that
675 /// the payment has failed, not just the route in question. If this is not set, the payment may
676 /// be retried via a different route.
677 payment_failed_permanently: bool,
678 /// Extra error details based on the failure type. May contain an update that needs to be
679 /// applied to the [`NetworkGraph`].
681 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
682 failure: PathFailure,
683 /// The payment path that failed.
685 /// The channel responsible for the failed payment path.
687 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
688 /// may not refer to a channel in the public network graph. These aliases may also collide
689 /// with channels in the public network graph.
691 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
692 /// retried. May be `None` for older [`Event`] serializations.
693 short_channel_id: Option<u64>,
695 error_code: Option<u16>,
697 error_data: Option<Vec<u8>>,
699 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
701 /// The id returned by [`ChannelManager::send_probe`].
703 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
704 payment_id: PaymentId,
705 /// The hash generated by [`ChannelManager::send_probe`].
707 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
708 payment_hash: PaymentHash,
709 /// The payment path that was successful.
712 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
714 /// The id returned by [`ChannelManager::send_probe`].
716 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
717 payment_id: PaymentId,
718 /// The hash generated by [`ChannelManager::send_probe`].
720 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
721 payment_hash: PaymentHash,
722 /// The payment path that failed.
724 /// The channel responsible for the failed probe.
726 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
727 /// may not refer to a channel in the public network graph. These aliases may also collide
728 /// with channels in the public network graph.
729 short_channel_id: Option<u64>,
731 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
732 /// a time in the future.
734 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
735 PendingHTLCsForwardable {
736 /// The minimum amount of time that should be waited prior to calling
737 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
738 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
739 /// now + 5*time_forwardable).
740 time_forwardable: Duration,
742 /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
743 /// you've encoded an intercept scid in the receiver's invoice route hints using
744 /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
746 /// [`ChannelManager::forward_intercepted_htlc`] or
747 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
748 /// their docs for more information.
750 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
751 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
752 /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
753 /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
755 /// An id to help LDK identify which HTLC is being forwarded or failed.
756 intercept_id: InterceptId,
757 /// The fake scid that was programmed as the next hop's scid, generated using
758 /// [`ChannelManager::get_intercept_scid`].
760 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
761 requested_next_hop_scid: u64,
762 /// The payment hash used for this HTLC.
763 payment_hash: PaymentHash,
764 /// How many msats were received on the inbound edge of this HTLC.
765 inbound_amount_msat: u64,
766 /// How many msats the payer intended to route to the next node. Depending on the reason you are
767 /// intercepting this payment, you might take a fee by forwarding less than this amount.
768 /// Forwarding less than this amount may break compatibility with LDK versions prior to 0.0.116.
770 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
771 /// check that whatever fee you want has been included here or subtract it as required. Further,
772 /// LDK will not stop you from forwarding more than you received.
773 expected_outbound_amount_msat: u64,
775 /// Used to indicate that an output which you should know how to spend was confirmed on chain
776 /// and is now spendable.
777 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
778 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
779 /// somewhere and spend them when you create on-chain transactions.
781 /// The outputs which you should store as spendable by you.
782 outputs: Vec<SpendableOutputDescriptor>,
783 /// The `channel_id` indicating which channel the spendable outputs belong to.
785 /// This will always be `Some` for events generated by LDK versions 0.0.117 and above.
786 channel_id: Option<ChannelId>,
788 /// This event is generated when a payment has been successfully forwarded through us and a
789 /// forwarding fee earned.
791 /// The incoming channel between the previous node and us. This is only `None` for events
792 /// generated or serialized by versions prior to 0.0.107.
793 prev_channel_id: Option<ChannelId>,
794 /// The outgoing channel between the next node and us. This is only `None` for events
795 /// generated or serialized by versions prior to 0.0.107.
796 next_channel_id: Option<ChannelId>,
797 /// The total fee, in milli-satoshis, which was earned as a result of the payment.
799 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
800 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
801 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
802 /// claimed the full value in millisatoshis from the source. In this case,
803 /// `claim_from_onchain_tx` will be set.
805 /// If the channel which sent us the payment has been force-closed, we will claim the funds
806 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
807 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
808 /// `PaymentForwarded` events are generated for the same payment iff `total_fee_earned_msat` is
810 total_fee_earned_msat: Option<u64>,
811 /// The share of the total fee, in milli-satoshis, which was withheld in addition to the
814 /// This will only be `Some` if we forwarded an intercepted HTLC with less than the
815 /// expected amount. This means our counterparty accepted to receive less than the invoice
816 /// amount, e.g., by claiming the payment featuring a corresponding
817 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`].
819 /// Will also always be `None` for events serialized with LDK prior to version 0.0.122.
821 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
823 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`]: Self::PaymentClaimable::counterparty_skimmed_fee_msat
824 skimmed_fee_msat: Option<u64>,
825 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
827 claim_from_onchain_tx: bool,
828 /// The final amount forwarded, in milli-satoshis, after the fee is deducted.
830 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
831 outbound_amount_forwarded_msat: Option<u64>,
833 /// Used to indicate that a channel with the given `channel_id` is being opened and pending
834 /// confirmation on-chain.
836 /// This event is emitted when the funding transaction has been signed and is broadcast to the
837 /// network. For 0conf channels it will be immediately followed by the corresponding
838 /// [`Event::ChannelReady`] event.
840 /// The `channel_id` of the channel that is pending confirmation.
841 channel_id: ChannelId,
842 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
843 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
844 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
845 /// `user_channel_id` will be randomized for an inbound channel.
847 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
848 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
849 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
850 user_channel_id: u128,
851 /// The `temporary_channel_id` this channel used to be known by during channel establishment.
853 /// Will be `None` for channels created prior to LDK version 0.0.115.
854 former_temporary_channel_id: Option<ChannelId>,
855 /// The `node_id` of the channel counterparty.
856 counterparty_node_id: PublicKey,
857 /// The outpoint of the channel's funding transaction.
858 funding_txo: OutPoint,
859 /// The features that this channel will operate with.
861 /// Will be `None` for channels created prior to LDK version 0.0.122.
862 channel_type: Option<ChannelTypeFeatures>,
864 /// Used to indicate that a channel with the given `channel_id` is ready to
865 /// be used. This event is emitted either when the funding transaction has been confirmed
866 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
869 /// The `channel_id` of the channel that is ready.
870 channel_id: ChannelId,
871 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
872 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
873 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
874 /// `user_channel_id` will be randomized for an inbound channel.
876 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
877 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
878 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
879 user_channel_id: u128,
880 /// The `node_id` of the channel counterparty.
881 counterparty_node_id: PublicKey,
882 /// The features that this channel will operate with.
883 channel_type: ChannelTypeFeatures,
885 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
886 /// process of closure.
888 /// Note that this event is only triggered for accepted channels: if the
889 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true and the channel is
890 /// rejected, no `ChannelClosed` event will be sent.
892 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
893 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
895 /// The `channel_id` of the channel which has been closed. Note that on-chain transactions
896 /// resolving the channel are likely still awaiting confirmation.
897 channel_id: ChannelId,
898 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
899 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
900 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
901 /// `user_channel_id` will be randomized for inbound channels.
902 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
903 /// zero for objects serialized with LDK versions prior to 0.0.102.
905 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
906 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
907 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
908 user_channel_id: u128,
909 /// The reason the channel was closed.
910 reason: ClosureReason,
911 /// Counterparty in the closed channel.
913 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
914 counterparty_node_id: Option<PublicKey>,
915 /// Channel capacity of the closing channel (sats).
917 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
918 channel_capacity_sats: Option<u64>,
919 /// The original channel funding TXO; this helps checking for the existence and confirmation
920 /// status of the closing tx.
921 /// Note that for instances serialized in v0.0.119 or prior this will be missing (None).
922 channel_funding_txo: Option<transaction::OutPoint>,
924 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
925 /// inputs for another purpose.
927 /// This event is not guaranteed to be generated for channels that are closed due to a restart.
929 /// The channel_id of the channel which has been closed.
930 channel_id: ChannelId,
931 /// The full transaction received from the user
932 transaction: Transaction
934 /// Indicates a request to open a new channel by a peer.
936 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the request,
937 /// call [`ChannelManager::force_close_without_broadcasting_txn`]. Note that a ['ChannelClosed`]
938 /// event will _not_ be triggered if the channel is rejected.
940 /// The event is only triggered when a new open channel request is received and the
941 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
943 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
944 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
945 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
947 /// The temporary channel ID of the channel requested to be opened.
949 /// When responding to the request, the `temporary_channel_id` should be passed
950 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
951 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
953 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
954 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
955 temporary_channel_id: ChannelId,
956 /// The node_id of the counterparty requesting to open the channel.
958 /// When responding to the request, the `counterparty_node_id` should be passed
959 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
960 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
963 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
964 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
965 counterparty_node_id: PublicKey,
966 /// The channel value of the requested channel.
967 funding_satoshis: u64,
968 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
970 /// The features that this channel will operate with. If you reject the channel, a
971 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
974 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
975 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
978 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
979 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
980 /// 0.0.107. Channels setting this type also need to get manually accepted via
981 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
982 /// or will be rejected otherwise.
984 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
985 channel_type: ChannelTypeFeatures,
987 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
990 /// Some scenarios where this event may be sent include:
991 /// * Insufficient capacity in the outbound channel
992 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
993 /// * When an unknown SCID is requested for forwarding a payment.
994 /// * Expected MPP amount has already been reached
995 /// * The HTLC has timed out
997 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
998 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
1000 /// The channel over which the HTLC was received.
1001 prev_channel_id: ChannelId,
1002 /// Destination of the HTLC that failed to be processed.
1003 failed_next_destination: HTLCDestination,
1005 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
1006 /// requires confirmed external funds to be readily available to spend.
1008 /// LDK does not currently generate this event unless the
1009 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`] config flag is set to true.
1010 /// It is limited to the scope of channels with anchor outputs.
1012 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`]: crate::util::config::ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx
1013 BumpTransaction(BumpTransactionEvent),
1016 impl Writeable for Event {
1017 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1019 &Event::FundingGenerationReady { .. } => {
1021 // We never write out FundingGenerationReady events as, upon disconnection, peers
1022 // drop any channels which have not yet exchanged funding_signed.
1024 &Event::PaymentClaimable { ref payment_hash, ref amount_msat, counterparty_skimmed_fee_msat,
1025 ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id,
1026 ref claim_deadline, ref onion_fields
1029 let mut payment_secret = None;
1030 let payment_preimage;
1032 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
1033 payment_secret = Some(secret);
1034 payment_preimage = *preimage;
1036 PaymentPurpose::SpontaneousPayment(preimage) => {
1037 payment_preimage = Some(*preimage);
1040 let skimmed_fee_opt = if counterparty_skimmed_fee_msat == 0 { None }
1041 else { Some(counterparty_skimmed_fee_msat) };
1042 write_tlv_fields!(writer, {
1043 (0, payment_hash, required),
1044 (1, receiver_node_id, option),
1045 (2, payment_secret, option),
1046 (3, via_channel_id, option),
1047 (4, amount_msat, required),
1048 (5, via_user_channel_id, option),
1049 // Type 6 was `user_payment_id` on 0.0.103 and earlier
1050 (7, claim_deadline, option),
1051 (8, payment_preimage, option),
1052 (9, onion_fields, option),
1053 (10, skimmed_fee_opt, option),
1056 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
1058 write_tlv_fields!(writer, {
1059 (0, payment_preimage, required),
1060 (1, payment_hash, required),
1061 (3, payment_id, option),
1062 (5, fee_paid_msat, option),
1065 &Event::PaymentPathFailed {
1066 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
1067 ref path, ref short_channel_id,
1075 error_code.write(writer)?;
1077 error_data.write(writer)?;
1078 write_tlv_fields!(writer, {
1079 (0, payment_hash, required),
1080 (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
1081 (2, payment_failed_permanently, required),
1082 (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
1083 (4, path.blinded_tail, option),
1084 (5, path.hops, required_vec),
1085 (7, short_channel_id, option),
1086 (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
1087 (11, payment_id, option),
1088 (13, failure, required),
1091 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
1093 // Note that we now ignore these on the read end as we'll re-generate them in
1094 // ChannelManager, we write them here only for backwards compatibility.
1096 &Event::SpendableOutputs { ref outputs, channel_id } => {
1098 write_tlv_fields!(writer, {
1099 (0, WithoutLength(outputs), required),
1100 (1, channel_id, option),
1103 &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1105 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1106 write_tlv_fields!(writer, {
1107 (0, intercept_id, required),
1108 (2, intercept_scid, required),
1109 (4, payment_hash, required),
1110 (6, inbound_amount_msat, required),
1111 (8, expected_outbound_amount_msat, required),
1114 &Event::PaymentForwarded {
1115 total_fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
1116 next_channel_id, outbound_amount_forwarded_msat, skimmed_fee_msat,
1119 write_tlv_fields!(writer, {
1120 (0, total_fee_earned_msat, option),
1121 (1, prev_channel_id, option),
1122 (2, claim_from_onchain_tx, required),
1123 (3, next_channel_id, option),
1124 (5, outbound_amount_forwarded_msat, option),
1125 (7, skimmed_fee_msat, option),
1128 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason,
1129 ref counterparty_node_id, ref channel_capacity_sats, ref channel_funding_txo
1132 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1133 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1134 // separate u64 values.
1135 let user_channel_id_low = *user_channel_id as u64;
1136 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1137 write_tlv_fields!(writer, {
1138 (0, channel_id, required),
1139 (1, user_channel_id_low, required),
1140 (2, reason, required),
1141 (3, user_channel_id_high, required),
1142 (5, counterparty_node_id, option),
1143 (7, channel_capacity_sats, option),
1144 (9, channel_funding_txo, option),
1147 &Event::DiscardFunding { ref channel_id, ref transaction } => {
1148 11u8.write(writer)?;
1149 write_tlv_fields!(writer, {
1150 (0, channel_id, required),
1151 (2, transaction, required)
1154 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1155 13u8.write(writer)?;
1156 write_tlv_fields!(writer, {
1157 (0, payment_id, required),
1158 (2, payment_hash, option),
1159 (4, path.hops, required_vec),
1160 (6, path.blinded_tail, option),
1163 &Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
1164 15u8.write(writer)?;
1165 write_tlv_fields!(writer, {
1166 (0, payment_id, required),
1167 (1, reason, option),
1168 (2, payment_hash, required),
1171 &Event::OpenChannelRequest { .. } => {
1172 17u8.write(writer)?;
1173 // We never write the OpenChannelRequest events as, upon disconnection, peers
1174 // drop any channels which have not yet exchanged funding_signed.
1176 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref htlcs, ref sender_intended_total_msat } => {
1177 19u8.write(writer)?;
1178 write_tlv_fields!(writer, {
1179 (0, payment_hash, required),
1180 (1, receiver_node_id, option),
1181 (2, purpose, required),
1182 (4, amount_msat, required),
1183 (5, *htlcs, optional_vec),
1184 (7, sender_intended_total_msat, option),
1187 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1188 21u8.write(writer)?;
1189 write_tlv_fields!(writer, {
1190 (0, payment_id, required),
1191 (2, payment_hash, required),
1192 (4, path.hops, required_vec),
1193 (6, path.blinded_tail, option),
1196 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1197 23u8.write(writer)?;
1198 write_tlv_fields!(writer, {
1199 (0, payment_id, required),
1200 (2, payment_hash, required),
1201 (4, path.hops, required_vec),
1202 (6, short_channel_id, option),
1203 (8, path.blinded_tail, option),
1206 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1207 25u8.write(writer)?;
1208 write_tlv_fields!(writer, {
1209 (0, prev_channel_id, required),
1210 (2, failed_next_destination, required),
1213 &Event::BumpTransaction(ref event)=> {
1214 27u8.write(writer)?;
1216 // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1217 // upon restarting anyway if they remain unresolved.
1218 BumpTransactionEvent::ChannelClose { .. } => {}
1219 BumpTransactionEvent::HTLCResolution { .. } => {}
1221 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1223 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1224 29u8.write(writer)?;
1225 write_tlv_fields!(writer, {
1226 (0, channel_id, required),
1227 (2, user_channel_id, required),
1228 (4, counterparty_node_id, required),
1229 (6, channel_type, required),
1232 &Event::ChannelPending { ref channel_id, ref user_channel_id,
1233 ref former_temporary_channel_id, ref counterparty_node_id, ref funding_txo,
1236 31u8.write(writer)?;
1237 write_tlv_fields!(writer, {
1238 (0, channel_id, required),
1239 (1, channel_type, option),
1240 (2, user_channel_id, required),
1241 (4, former_temporary_channel_id, required),
1242 (6, counterparty_node_id, required),
1243 (8, funding_txo, required),
1246 &Event::InvoiceRequestFailed { ref payment_id } => {
1247 33u8.write(writer)?;
1248 write_tlv_fields!(writer, {
1249 (0, payment_id, required),
1252 &Event::ConnectionNeeded { .. } => {
1253 35u8.write(writer)?;
1254 // Never write ConnectionNeeded events as buffered onion messages aren't serialized.
1256 // Note that, going forward, all new events must only write data inside of
1257 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1258 // data via `write_tlv_fields`.
1263 impl MaybeReadable for Event {
1264 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1265 match Readable::read(reader)? {
1266 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events.
1270 let mut payment_hash = PaymentHash([0; 32]);
1271 let mut payment_preimage = None;
1272 let mut payment_secret = None;
1273 let mut amount_msat = 0;
1274 let mut counterparty_skimmed_fee_msat_opt = None;
1275 let mut receiver_node_id = None;
1276 let mut _user_payment_id = None::<u64>; // Used in 0.0.103 and earlier, no longer written in 0.0.116+.
1277 let mut via_channel_id = None;
1278 let mut claim_deadline = None;
1279 let mut via_user_channel_id = None;
1280 let mut onion_fields = None;
1281 read_tlv_fields!(reader, {
1282 (0, payment_hash, required),
1283 (1, receiver_node_id, option),
1284 (2, payment_secret, option),
1285 (3, via_channel_id, option),
1286 (4, amount_msat, required),
1287 (5, via_user_channel_id, option),
1288 (6, _user_payment_id, option),
1289 (7, claim_deadline, option),
1290 (8, payment_preimage, option),
1291 (9, onion_fields, option),
1292 (10, counterparty_skimmed_fee_msat_opt, option),
1294 let purpose = match payment_secret {
1295 Some(secret) => PaymentPurpose::InvoicePayment {
1297 payment_secret: secret
1299 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1300 None => return Err(msgs::DecodeError::InvalidValue),
1302 Ok(Some(Event::PaymentClaimable {
1306 counterparty_skimmed_fee_msat: counterparty_skimmed_fee_msat_opt.unwrap_or(0),
1309 via_user_channel_id,
1318 let mut payment_preimage = PaymentPreimage([0; 32]);
1319 let mut payment_hash = None;
1320 let mut payment_id = None;
1321 let mut fee_paid_msat = None;
1322 read_tlv_fields!(reader, {
1323 (0, payment_preimage, required),
1324 (1, payment_hash, option),
1325 (3, payment_id, option),
1326 (5, fee_paid_msat, option),
1328 if payment_hash.is_none() {
1329 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()));
1331 Ok(Some(Event::PaymentSent {
1334 payment_hash: payment_hash.unwrap(),
1343 let error_code = Readable::read(reader)?;
1345 let error_data = Readable::read(reader)?;
1346 let mut payment_hash = PaymentHash([0; 32]);
1347 let mut payment_failed_permanently = false;
1348 let mut network_update = None;
1349 let mut blinded_tail: Option<BlindedTail> = None;
1350 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1351 let mut short_channel_id = None;
1352 let mut payment_id = None;
1353 let mut failure_opt = None;
1354 read_tlv_fields!(reader, {
1355 (0, payment_hash, required),
1356 (1, network_update, upgradable_option),
1357 (2, payment_failed_permanently, required),
1358 (4, blinded_tail, option),
1359 // Added as a part of LDK 0.0.101 and always filled in since.
1360 // Defaults to an empty Vec, though likely should have been `Option`al.
1361 (5, path, optional_vec),
1362 (7, short_channel_id, option),
1363 (11, payment_id, option),
1364 (13, failure_opt, upgradable_option),
1366 let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1367 Ok(Some(Event::PaymentPathFailed {
1370 payment_failed_permanently,
1372 path: Path { hops: path.unwrap(), blinded_tail },
1385 let mut outputs = WithoutLength(Vec::new());
1386 let mut channel_id: Option<ChannelId> = None;
1387 read_tlv_fields!(reader, {
1388 (0, outputs, required),
1389 (1, channel_id, option),
1391 Ok(Some(Event::SpendableOutputs { outputs: outputs.0, channel_id }))
1396 let mut payment_hash = PaymentHash([0; 32]);
1397 let mut intercept_id = InterceptId([0; 32]);
1398 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1399 let mut inbound_amount_msat = 0;
1400 let mut expected_outbound_amount_msat = 0;
1401 read_tlv_fields!(reader, {
1402 (0, intercept_id, required),
1403 (2, requested_next_hop_scid, required),
1404 (4, payment_hash, required),
1405 (6, inbound_amount_msat, required),
1406 (8, expected_outbound_amount_msat, required),
1408 let next_scid = match requested_next_hop_scid {
1409 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1411 Ok(Some(Event::HTLCIntercepted {
1413 requested_next_hop_scid: next_scid,
1414 inbound_amount_msat,
1415 expected_outbound_amount_msat,
1421 let mut total_fee_earned_msat = None;
1422 let mut prev_channel_id = None;
1423 let mut claim_from_onchain_tx = false;
1424 let mut next_channel_id = None;
1425 let mut outbound_amount_forwarded_msat = None;
1426 let mut skimmed_fee_msat = None;
1427 read_tlv_fields!(reader, {
1428 (0, total_fee_earned_msat, option),
1429 (1, prev_channel_id, option),
1430 (2, claim_from_onchain_tx, required),
1431 (3, next_channel_id, option),
1432 (5, outbound_amount_forwarded_msat, option),
1433 (7, skimmed_fee_msat, option),
1435 Ok(Some(Event::PaymentForwarded {
1436 total_fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id,
1437 outbound_amount_forwarded_msat, skimmed_fee_msat,
1444 let mut channel_id = ChannelId::new_zero();
1445 let mut reason = UpgradableRequired(None);
1446 let mut user_channel_id_low_opt: Option<u64> = None;
1447 let mut user_channel_id_high_opt: Option<u64> = None;
1448 let mut counterparty_node_id = None;
1449 let mut channel_capacity_sats = None;
1450 let mut channel_funding_txo = None;
1451 read_tlv_fields!(reader, {
1452 (0, channel_id, required),
1453 (1, user_channel_id_low_opt, option),
1454 (2, reason, upgradable_required),
1455 (3, user_channel_id_high_opt, option),
1456 (5, counterparty_node_id, option),
1457 (7, channel_capacity_sats, option),
1458 (9, channel_funding_txo, option),
1461 // `user_channel_id` used to be a single u64 value. In order to remain
1462 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1463 // as two separate u64 values.
1464 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1465 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1467 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required),
1468 counterparty_node_id, channel_capacity_sats, channel_funding_txo }))
1474 let mut channel_id = ChannelId::new_zero();
1475 let mut transaction = Transaction{ version: 2, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
1476 read_tlv_fields!(reader, {
1477 (0, channel_id, required),
1478 (2, transaction, required),
1480 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1486 _init_and_read_len_prefixed_tlv_fields!(reader, {
1487 (0, payment_id, required),
1488 (2, payment_hash, option),
1489 (4, path, required_vec),
1490 (6, blinded_tail, option),
1492 Ok(Some(Event::PaymentPathSuccessful {
1493 payment_id: payment_id.0.unwrap(),
1495 path: Path { hops: path, blinded_tail },
1502 let mut payment_hash = PaymentHash([0; 32]);
1503 let mut payment_id = PaymentId([0; 32]);
1504 let mut reason = None;
1505 read_tlv_fields!(reader, {
1506 (0, payment_id, required),
1507 (1, reason, upgradable_option),
1508 (2, payment_hash, required),
1510 Ok(Some(Event::PaymentFailed {
1519 // Value 17 is used for `Event::OpenChannelRequest`.
1524 let mut payment_hash = PaymentHash([0; 32]);
1525 let mut purpose = UpgradableRequired(None);
1526 let mut amount_msat = 0;
1527 let mut receiver_node_id = None;
1528 let mut htlcs: Option<Vec<ClaimedHTLC>> = Some(vec![]);
1529 let mut sender_intended_total_msat: Option<u64> = None;
1530 read_tlv_fields!(reader, {
1531 (0, payment_hash, required),
1532 (1, receiver_node_id, option),
1533 (2, purpose, upgradable_required),
1534 (4, amount_msat, required),
1535 (5, htlcs, optional_vec),
1536 (7, sender_intended_total_msat, option),
1538 Ok(Some(Event::PaymentClaimed {
1541 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1543 htlcs: htlcs.unwrap_or(vec![]),
1544 sender_intended_total_msat,
1551 _init_and_read_len_prefixed_tlv_fields!(reader, {
1552 (0, payment_id, required),
1553 (2, payment_hash, required),
1554 (4, path, required_vec),
1555 (6, blinded_tail, option),
1557 Ok(Some(Event::ProbeSuccessful {
1558 payment_id: payment_id.0.unwrap(),
1559 payment_hash: payment_hash.0.unwrap(),
1560 path: Path { hops: path, blinded_tail },
1567 _init_and_read_len_prefixed_tlv_fields!(reader, {
1568 (0, payment_id, required),
1569 (2, payment_hash, required),
1570 (4, path, required_vec),
1571 (6, short_channel_id, option),
1572 (8, blinded_tail, option),
1574 Ok(Some(Event::ProbeFailed {
1575 payment_id: payment_id.0.unwrap(),
1576 payment_hash: payment_hash.0.unwrap(),
1577 path: Path { hops: path, blinded_tail },
1585 let mut prev_channel_id = ChannelId::new_zero();
1586 let mut failed_next_destination_opt = UpgradableRequired(None);
1587 read_tlv_fields!(reader, {
1588 (0, prev_channel_id, required),
1589 (2, failed_next_destination_opt, upgradable_required),
1591 Ok(Some(Event::HTLCHandlingFailed {
1593 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1601 let mut channel_id = ChannelId::new_zero();
1602 let mut user_channel_id: u128 = 0;
1603 let mut counterparty_node_id = RequiredWrapper(None);
1604 let mut channel_type = RequiredWrapper(None);
1605 read_tlv_fields!(reader, {
1606 (0, channel_id, required),
1607 (2, user_channel_id, required),
1608 (4, counterparty_node_id, required),
1609 (6, channel_type, required),
1612 Ok(Some(Event::ChannelReady {
1615 counterparty_node_id: counterparty_node_id.0.unwrap(),
1616 channel_type: channel_type.0.unwrap()
1623 let mut channel_id = ChannelId::new_zero();
1624 let mut user_channel_id: u128 = 0;
1625 let mut former_temporary_channel_id = None;
1626 let mut counterparty_node_id = RequiredWrapper(None);
1627 let mut funding_txo = RequiredWrapper(None);
1628 let mut channel_type = None;
1629 read_tlv_fields!(reader, {
1630 (0, channel_id, required),
1631 (1, channel_type, option),
1632 (2, user_channel_id, required),
1633 (4, former_temporary_channel_id, required),
1634 (6, counterparty_node_id, required),
1635 (8, funding_txo, required),
1638 Ok(Some(Event::ChannelPending {
1641 former_temporary_channel_id,
1642 counterparty_node_id: counterparty_node_id.0.unwrap(),
1643 funding_txo: funding_txo.0.unwrap(),
1651 _init_and_read_len_prefixed_tlv_fields!(reader, {
1652 (0, payment_id, required),
1654 Ok(Some(Event::InvoiceRequestFailed {
1655 payment_id: payment_id.0.unwrap(),
1660 // Note that we do not write a length-prefixed TLV for ConnectionNeeded events.
1662 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1663 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1665 x if x % 2 == 1 => {
1666 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1667 // which prefixes the whole thing with a length BigSize. Because the event is
1668 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1669 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1670 // exactly the number of bytes specified, ignoring them entirely.
1671 let tlv_len: BigSize = Readable::read(reader)?;
1672 FixedLengthReader::new(reader, tlv_len.0)
1673 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1676 _ => Err(msgs::DecodeError::InvalidValue)
1681 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1682 /// broadcast to most peers).
1683 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1684 #[derive(Clone, Debug)]
1685 #[cfg_attr(test, derive(PartialEq))]
1686 pub enum MessageSendEvent {
1687 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1688 /// message provided to the given peer.
1690 /// The node_id of the node which should receive this message
1692 /// The message which should be sent.
1693 msg: msgs::AcceptChannel,
1695 /// Used to indicate that we've accepted a V2 channel open and should send the accept_channel2
1696 /// message provided to the given peer.
1697 SendAcceptChannelV2 {
1698 /// The node_id of the node which should receive this message
1700 /// The message which should be sent.
1701 msg: msgs::AcceptChannelV2,
1703 /// Used to indicate that we've initiated a channel open and should send the open_channel
1704 /// message provided to the given peer.
1706 /// The node_id of the node which should receive this message
1708 /// The message which should be sent.
1709 msg: msgs::OpenChannel,
1711 /// Used to indicate that we've initiated a V2 channel open and should send the open_channel2
1712 /// message provided to the given peer.
1714 /// The node_id of the node which should receive this message
1716 /// The message which should be sent.
1717 msg: msgs::OpenChannelV2,
1719 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1720 SendFundingCreated {
1721 /// The node_id of the node which should receive this message
1723 /// The message which should be sent.
1724 msg: msgs::FundingCreated,
1726 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1728 /// The node_id of the node which should receive this message
1730 /// The message which should be sent.
1731 msg: msgs::FundingSigned,
1733 /// Used to indicate that a stfu message should be sent to the peer with the given node id.
1735 /// The node_id of the node which should receive this message
1737 /// The message which should be sent.
1740 /// Used to indicate that a splice message should be sent to the peer with the given node id.
1742 /// The node_id of the node which should receive this message
1744 /// The message which should be sent.
1747 /// Used to indicate that a splice_ack message should be sent to the peer with the given node id.
1749 /// The node_id of the node which should receive this message
1751 /// The message which should be sent.
1752 msg: msgs::SpliceAck,
1754 /// Used to indicate that a splice_locked message should be sent to the peer with the given node id.
1756 /// The node_id of the node which should receive this message
1758 /// The message which should be sent.
1759 msg: msgs::SpliceLocked,
1761 /// Used to indicate that a tx_add_input message should be sent to the peer with the given node_id.
1763 /// The node_id of the node which should receive this message
1765 /// The message which should be sent.
1766 msg: msgs::TxAddInput,
1768 /// Used to indicate that a tx_add_output message should be sent to the peer with the given node_id.
1770 /// The node_id of the node which should receive this message
1772 /// The message which should be sent.
1773 msg: msgs::TxAddOutput,
1775 /// Used to indicate that a tx_remove_input message should be sent to the peer with the given node_id.
1777 /// The node_id of the node which should receive this message
1779 /// The message which should be sent.
1780 msg: msgs::TxRemoveInput,
1782 /// Used to indicate that a tx_remove_output message should be sent to the peer with the given node_id.
1783 SendTxRemoveOutput {
1784 /// The node_id of the node which should receive this message
1786 /// The message which should be sent.
1787 msg: msgs::TxRemoveOutput,
1789 /// Used to indicate that a tx_complete message should be sent to the peer with the given node_id.
1791 /// The node_id of the node which should receive this message
1793 /// The message which should be sent.
1794 msg: msgs::TxComplete,
1796 /// Used to indicate that a tx_signatures message should be sent to the peer with the given node_id.
1798 /// The node_id of the node which should receive this message
1800 /// The message which should be sent.
1801 msg: msgs::TxSignatures,
1803 /// Used to indicate that a tx_init_rbf message should be sent to the peer with the given node_id.
1805 /// The node_id of the node which should receive this message
1807 /// The message which should be sent.
1808 msg: msgs::TxInitRbf,
1810 /// Used to indicate that a tx_ack_rbf message should be sent to the peer with the given node_id.
1812 /// The node_id of the node which should receive this message
1814 /// The message which should be sent.
1815 msg: msgs::TxAckRbf,
1817 /// Used to indicate that a tx_abort message should be sent to the peer with the given node_id.
1819 /// The node_id of the node which should receive this message
1821 /// The message which should be sent.
1824 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1826 /// The node_id of the node which should receive these message(s)
1828 /// The channel_ready message which should be sent.
1829 msg: msgs::ChannelReady,
1831 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1832 SendAnnouncementSignatures {
1833 /// The node_id of the node which should receive these message(s)
1835 /// The announcement_signatures message which should be sent.
1836 msg: msgs::AnnouncementSignatures,
1838 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1839 /// message should be sent to the peer with the given node_id.
1841 /// The node_id of the node which should receive these message(s)
1843 /// The update messages which should be sent. ALL messages in the struct should be sent!
1844 updates: msgs::CommitmentUpdate,
1846 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1848 /// The node_id of the node which should receive this message
1850 /// The message which should be sent.
1851 msg: msgs::RevokeAndACK,
1853 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1855 /// The node_id of the node which should receive this message
1857 /// The message which should be sent.
1858 msg: msgs::ClosingSigned,
1860 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1862 /// The node_id of the node which should receive this message
1864 /// The message which should be sent.
1865 msg: msgs::Shutdown,
1867 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1868 SendChannelReestablish {
1869 /// The node_id of the node which should receive this message
1871 /// The message which should be sent.
1872 msg: msgs::ChannelReestablish,
1874 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1875 /// initial connection to ensure our peers know about our channels.
1876 SendChannelAnnouncement {
1877 /// The node_id of the node which should receive this message
1879 /// The channel_announcement which should be sent.
1880 msg: msgs::ChannelAnnouncement,
1881 /// The followup channel_update which should be sent.
1882 update_msg: msgs::ChannelUpdate,
1884 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1885 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1887 /// Note that after doing so, you very likely (unless you did so very recently) want to
1888 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1889 /// ensures that any nodes which see our channel_announcement also have a relevant
1890 /// node_announcement, including relevant feature flags which may be important for routing
1891 /// through or to us.
1893 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1894 BroadcastChannelAnnouncement {
1895 /// The channel_announcement which should be sent.
1896 msg: msgs::ChannelAnnouncement,
1897 /// The followup channel_update which should be sent.
1898 update_msg: Option<msgs::ChannelUpdate>,
1900 /// Used to indicate that a channel_update should be broadcast to all peers.
1901 BroadcastChannelUpdate {
1902 /// The channel_update which should be sent.
1903 msg: msgs::ChannelUpdate,
1905 /// Used to indicate that a node_announcement should be broadcast to all peers.
1906 BroadcastNodeAnnouncement {
1907 /// The node_announcement which should be sent.
1908 msg: msgs::NodeAnnouncement,
1910 /// Used to indicate that a channel_update should be sent to a single peer.
1911 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1912 /// private channel and we shouldn't be informing all of our peers of channel parameters.
1914 /// The node_id of the node which should receive this message
1916 /// The channel_update which should be sent.
1917 msg: msgs::ChannelUpdate,
1919 /// Broadcast an error downstream to be handled
1921 /// The node_id of the node which should receive this message
1923 /// The action which should be taken.
1924 action: msgs::ErrorAction
1926 /// Query a peer for channels with funding transaction UTXOs in a block range.
1927 SendChannelRangeQuery {
1928 /// The node_id of this message recipient
1930 /// The query_channel_range which should be sent.
1931 msg: msgs::QueryChannelRange,
1933 /// Request routing gossip messages from a peer for a list of channels identified by
1934 /// their short_channel_ids.
1936 /// The node_id of this message recipient
1938 /// The query_short_channel_ids which should be sent.
1939 msg: msgs::QueryShortChannelIds,
1941 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1942 /// emitted during processing of the query.
1943 SendReplyChannelRange {
1944 /// The node_id of this message recipient
1946 /// The reply_channel_range which should be sent.
1947 msg: msgs::ReplyChannelRange,
1949 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1950 /// enable receiving gossip messages from the peer.
1951 SendGossipTimestampFilter {
1952 /// The node_id of this message recipient
1954 /// The gossip_timestamp_filter which should be sent.
1955 msg: msgs::GossipTimestampFilter,
1959 /// A trait indicating an object may generate message send events
1960 pub trait MessageSendEventsProvider {
1961 /// Gets the list of pending events which were generated by previous actions, clearing the list
1963 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1966 /// A trait indicating an object may generate events.
1968 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1970 /// Implementations of this trait may also feature an async version of event handling, as shown with
1971 /// [`ChannelManager::process_pending_events_async`] and
1972 /// [`ChainMonitor::process_pending_events_async`].
1976 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1977 /// event since the last invocation.
1979 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1980 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1981 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1982 /// relevant changes to disk *before* returning.
1984 /// Further, because an application may crash between an [`Event`] being handled and the
1985 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1986 /// effect, [`Event`]s may be replayed.
1988 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1989 /// consult the provider's documentation on the implication of processing events and how a handler
1990 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1991 /// [`ChainMonitor::process_pending_events`]).
1993 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1996 /// [`process_pending_events`]: Self::process_pending_events
1997 /// [`handle_event`]: EventHandler::handle_event
1998 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1999 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
2000 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
2001 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
2002 pub trait EventsProvider {
2003 /// Processes any events generated since the last call using the given event handler.
2005 /// See the trait-level documentation for requirements.
2006 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
2009 /// A trait implemented for objects handling events from [`EventsProvider`].
2011 /// An async variation also exists for implementations of [`EventsProvider`] that support async
2012 /// event handling. The async event handler should satisfy the generic bounds: `F:
2013 /// core::future::Future, H: Fn(Event) -> F`.
2014 pub trait EventHandler {
2015 /// Handles the given [`Event`].
2017 /// See [`EventsProvider`] for details that must be considered when implementing this method.
2018 fn handle_event(&self, event: Event);
2021 impl<F> EventHandler for F where F: Fn(Event) {
2022 fn handle_event(&self, event: Event) {
2027 impl<T: EventHandler> EventHandler for Arc<T> {
2028 fn handle_event(&self, event: Event) {
2029 self.deref().handle_event(event)