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::blinded_path::payment::{Bolt12OfferContext, Bolt12RefundContext, PaymentContext, PaymentContextRef};
22 use crate::sign::SpendableOutputDescriptor;
23 use crate::ln::channelmanager::{InterceptId, PaymentId, RecipientOnionFields};
24 use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
25 use crate::ln::features::ChannelTypeFeatures;
27 use crate::ln::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
28 use crate::chain::transaction;
29 use crate::routing::gossip::NetworkUpdate;
30 use crate::util::errors::APIError;
31 use crate::util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, RequiredWrapper, UpgradableRequired, WithoutLength};
32 use crate::util::string::UntrustedString;
33 use crate::routing::router::{BlindedTail, Path, RouteHop, RouteParameters};
35 use bitcoin::{Transaction, OutPoint};
36 use bitcoin::blockdata::locktime::absolute::LockTime;
37 use bitcoin::blockdata::script::ScriptBuf;
38 use bitcoin::hashes::Hash;
39 use bitcoin::hashes::sha256::Hash as Sha256;
40 use bitcoin::secp256k1::PublicKey;
42 use core::time::Duration;
46 #[allow(unused_imports)]
47 use crate::prelude::*;
49 /// Some information provided on receipt of payment depends on whether the payment received is a
50 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
51 #[derive(Clone, Debug, PartialEq, Eq)]
52 pub enum PaymentPurpose {
53 /// A payment for a BOLT 11 invoice.
54 Bolt11InvoicePayment {
55 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
56 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
57 /// [`ChannelManager::claim_funds`].
59 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
60 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
61 payment_preimage: Option<PaymentPreimage>,
62 /// The "payment secret". This authenticates the sender to the recipient, preventing a
63 /// number of deanonymization attacks during the routing process.
64 /// It is provided here for your reference, however its accuracy is enforced directly by
65 /// [`ChannelManager`] using the values you previously provided to
66 /// [`ChannelManager::create_inbound_payment`] or
67 /// [`ChannelManager::create_inbound_payment_for_hash`].
69 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
70 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
71 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
72 payment_secret: PaymentSecret,
74 /// A payment for a BOLT 12 [`Offer`].
76 /// [`Offer`]: crate::offers::offer::Offer
78 /// The preimage to the payment hash. If provided, this can be handed directly to
79 /// [`ChannelManager::claim_funds`].
81 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
82 payment_preimage: Option<PaymentPreimage>,
83 /// The secret used to authenticate the sender to the recipient, preventing a number of
84 /// de-anonymization attacks while routing a payment.
86 /// See [`PaymentPurpose::Bolt11InvoicePayment::payment_secret`] for further details.
87 payment_secret: PaymentSecret,
88 /// The context of the payment such as information about the corresponding [`Offer`] and
89 /// [`InvoiceRequest`].
91 /// [`Offer`]: crate::offers::offer::Offer
92 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
93 payment_context: Bolt12OfferContext,
95 /// A payment for a BOLT 12 [`Refund`].
97 /// [`Refund`]: crate::offers::refund::Refund
99 /// The preimage to the payment hash. If provided, this can be handed directly to
100 /// [`ChannelManager::claim_funds`].
102 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
103 payment_preimage: Option<PaymentPreimage>,
104 /// The secret used to authenticate the sender to the recipient, preventing a number of
105 /// de-anonymization attacks while routing a payment.
107 /// See [`PaymentPurpose::Bolt11InvoicePayment::payment_secret`] for further details.
108 payment_secret: PaymentSecret,
109 /// The context of the payment such as information about the corresponding [`Refund`].
111 /// [`Refund`]: crate::offers::refund::Refund
112 payment_context: Bolt12RefundContext,
114 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
115 /// (the payee) providing a preimage.
116 SpontaneousPayment(PaymentPreimage),
119 impl PaymentPurpose {
120 /// Returns the preimage for this payment, if it is known.
121 pub fn preimage(&self) -> Option<PaymentPreimage> {
123 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, .. } => *payment_preimage,
124 PaymentPurpose::Bolt12OfferPayment { payment_preimage, .. } => *payment_preimage,
125 PaymentPurpose::Bolt12RefundPayment { payment_preimage, .. } => *payment_preimage,
126 PaymentPurpose::SpontaneousPayment(preimage) => Some(*preimage),
130 pub(crate) fn is_keysend(&self) -> bool {
132 PaymentPurpose::Bolt11InvoicePayment { .. } => false,
133 PaymentPurpose::Bolt12OfferPayment { .. } => false,
134 PaymentPurpose::Bolt12RefundPayment { .. } => false,
135 PaymentPurpose::SpontaneousPayment(..) => true,
140 impl_writeable_tlv_based_enum!(PaymentPurpose,
141 (0, Bolt11InvoicePayment) => {
142 (0, payment_preimage, option),
143 (2, payment_secret, required),
145 (4, Bolt12OfferPayment) => {
146 (0, payment_preimage, option),
147 (2, payment_secret, required),
148 (4, payment_context, required),
150 (6, Bolt12RefundPayment) => {
151 (0, payment_preimage, option),
152 (2, payment_secret, required),
153 (4, payment_context, required),
156 (2, SpontaneousPayment)
159 /// Information about an HTLC that is part of a payment that can be claimed.
160 #[derive(Clone, Debug, PartialEq, Eq)]
161 pub struct ClaimedHTLC {
162 /// The `channel_id` of the channel over which the HTLC was received.
163 pub channel_id: ChannelId,
164 /// The `user_channel_id` of the channel over which the HTLC was received. This is the value
165 /// passed in to [`ChannelManager::create_channel`] for outbound channels, or to
166 /// [`ChannelManager::accept_inbound_channel`] for inbound channels if
167 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
168 /// `user_channel_id` will be randomized for an inbound channel.
170 /// This field will be zero for a payment that was serialized prior to LDK version 0.0.117. (This
171 /// should only happen in the case that a payment was claimable prior to LDK version 0.0.117, but
172 /// was not actually claimed until after upgrading.)
174 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
175 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
176 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
177 pub user_channel_id: u128,
178 /// The block height at which this HTLC expires.
179 pub cltv_expiry: u32,
180 /// The amount (in msats) of this part of an MPP.
182 /// The extra fee our counterparty skimmed off the top of this HTLC, if any.
184 /// This value will always be 0 for [`ClaimedHTLC`]s serialized with LDK versions prior to
186 pub counterparty_skimmed_fee_msat: u64,
188 impl_writeable_tlv_based!(ClaimedHTLC, {
189 (0, channel_id, required),
190 (1, counterparty_skimmed_fee_msat, (default_value, 0u64)),
191 (2, user_channel_id, required),
192 (4, cltv_expiry, required),
193 (6, value_msat, required),
196 /// When the payment path failure took place and extra details about it. [`PathFailure::OnPath`] may
197 /// contain a [`NetworkUpdate`] that needs to be applied to the [`NetworkGraph`].
199 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
200 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
201 #[derive(Clone, Debug, Eq, PartialEq)]
202 pub enum PathFailure {
203 /// We failed to initially send the payment and no HTLC was committed to. Contains the relevant
206 /// The error surfaced from initial send.
209 /// A hop on the path failed to forward our payment.
211 /// If present, this [`NetworkUpdate`] should be applied to the [`NetworkGraph`] so that routing
212 /// decisions can take into account the update.
214 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
215 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
216 network_update: Option<NetworkUpdate>,
220 impl_writeable_tlv_based_enum_upgradable!(PathFailure,
222 (0, network_update, upgradable_option),
224 (2, InitialSend) => {
225 (0, err, upgradable_required),
229 #[derive(Clone, Debug, PartialEq, Eq)]
230 /// The reason the channel was closed. See individual variants for more details.
231 pub enum ClosureReason {
232 /// Closure generated from receiving a peer error message.
234 /// Our counterparty may have broadcasted their latest commitment state, and we have
236 CounterpartyForceClosed {
237 /// The error which the peer sent us.
239 /// Be careful about printing the peer_msg, a well-crafted message could exploit
240 /// a security vulnerability in the terminal emulator or the logging subsystem.
241 /// To be safe, use `Display` on `UntrustedString`
243 /// [`UntrustedString`]: crate::util::string::UntrustedString
244 peer_msg: UntrustedString,
246 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
248 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
250 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
251 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
253 /// This was only set in versions of LDK prior to 0.0.122.
254 // Can be removed once we disallow downgrading to 0.0.121
255 LegacyCooperativeClosure,
256 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
257 /// the cooperative close transaction. This indicates that the shutdown was initiated by our
260 /// In rare cases where we initiated closure immediately prior to shutting down without
261 /// persisting, this value may be provided for channels we initiated closure for.
262 CounterpartyInitiatedCooperativeClosure,
263 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
264 /// the cooperative close transaction. This indicates that the shutdown was initiated by us.
265 LocallyInitiatedCooperativeClosure,
266 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
267 /// commitment transaction came from our counterparty, but it may also have come from
268 /// a copy of our own `ChannelMonitor`.
269 CommitmentTxConfirmed,
270 /// The funding transaction failed to confirm in a timely manner on an inbound channel.
272 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
274 /// A developer-readable error message which we generated.
277 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
278 /// forget the channel entirely - we can attempt again if the peer reconnects.
280 /// This includes cases where we restarted prior to funding completion, including prior to the
281 /// initial [`ChannelMonitor`] persistence completing.
283 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
284 /// peer because of mutual incompatibility between us and our channel counterparty.
286 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
288 /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
289 /// the [`ChannelManager`] deserialized.
291 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
292 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
293 OutdatedChannelManager,
294 /// The counterparty requested a cooperative close of a channel that had not been funded yet.
295 /// The channel has been immediately closed.
296 CounterpartyCoopClosedUnfundedChannel,
297 /// Another channel in the same funding batch closed before the funding transaction
298 /// was ready to be broadcast.
300 /// One of our HTLCs timed out in a channel, causing us to force close the channel.
304 impl core::fmt::Display for ClosureReason {
305 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
306 f.write_str("Channel closed because ")?;
308 ClosureReason::CounterpartyForceClosed { peer_msg } => {
309 f.write_fmt(format_args!("counterparty force-closed with message: {}", peer_msg))
311 ClosureReason::HolderForceClosed => f.write_str("user force-closed the channel"),
312 ClosureReason::LegacyCooperativeClosure => f.write_str("the channel was cooperatively closed"),
313 ClosureReason::CounterpartyInitiatedCooperativeClosure => f.write_str("the channel was cooperatively closed by our peer"),
314 ClosureReason::LocallyInitiatedCooperativeClosure => f.write_str("the channel was cooperatively closed by us"),
315 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
316 ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
317 ClosureReason::ProcessingError { err } => {
318 f.write_str("of an exception: ")?;
321 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
322 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
323 ClosureReason::CounterpartyCoopClosedUnfundedChannel => f.write_str("the peer requested the unfunded channel be closed"),
324 ClosureReason::FundingBatchClosure => f.write_str("another channel in the same funding batch closed"),
325 ClosureReason::HTLCsTimedOut => f.write_str("htlcs on the channel timed out"),
330 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
331 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
332 (1, FundingTimedOut) => {},
333 (2, HolderForceClosed) => {},
334 (6, CommitmentTxConfirmed) => {},
335 (4, LegacyCooperativeClosure) => {},
336 (8, ProcessingError) => { (1, err, required) },
337 (10, DisconnectedPeer) => {},
338 (12, OutdatedChannelManager) => {},
339 (13, CounterpartyCoopClosedUnfundedChannel) => {},
340 (15, FundingBatchClosure) => {},
341 (17, CounterpartyInitiatedCooperativeClosure) => {},
342 (19, LocallyInitiatedCooperativeClosure) => {},
343 (21, HTLCsTimedOut) => {},
346 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
347 #[derive(Clone, Debug, PartialEq, Eq)]
348 pub enum HTLCDestination {
349 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
350 /// there is insufficient capacity in our outbound channel.
352 /// The `node_id` of the next node. For backwards compatibility, this field is
353 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
354 /// counterparty node information.
355 node_id: Option<PublicKey>,
356 /// The outgoing `channel_id` between us and the next node.
357 channel_id: ChannelId,
359 /// Scenario where we are unsure of the next node to forward the HTLC to.
361 /// Short channel id we are requesting to forward an HTLC to.
362 requested_forward_scid: u64,
364 /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
367 /// Short channel id we are requesting to forward an HTLC to.
368 requested_forward_scid: u64
370 /// We couldn't decode the incoming onion to obtain the forwarding details.
372 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
373 /// but is invalid for some reason, so we reject it.
375 /// Some of the reasons may include:
377 /// * Excess HTLCs for a payment that we have already fully received, over-paying for the
379 /// * The counterparty node modified the HTLC in transit,
380 /// * A probing attack where an intermediary node is trying to detect if we are the ultimate
381 /// recipient for a payment.
383 /// The payment hash of the payment we attempted to process.
384 payment_hash: PaymentHash
388 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
389 (0, NextHopChannel) => {
390 (0, node_id, required),
391 (2, channel_id, required),
393 (1, InvalidForward) => {
394 (0, requested_forward_scid, required),
396 (2, UnknownNextHop) => {
397 (0, requested_forward_scid, required),
399 (3, InvalidOnion) => {},
400 (4, FailedPayment) => {
401 (0, payment_hash, required),
405 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
406 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
407 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
408 /// intercepts in upcoming work.
409 enum InterceptNextHop {
411 requested_next_hop_scid: u64,
415 impl_writeable_tlv_based_enum!(InterceptNextHop,
417 (0, requested_next_hop_scid, required),
421 /// The reason the payment failed. Used in [`Event::PaymentFailed`].
422 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
423 pub enum PaymentFailureReason {
424 /// The intended recipient rejected our payment.
426 /// The user chose to abandon this payment by calling [`ChannelManager::abandon_payment`].
428 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
430 /// We exhausted all of our retry attempts while trying to send the payment, or we
431 /// exhausted the [`Retry::Timeout`] if the user set one. If at any point a retry
432 /// attempt failed while being forwarded along the path, an [`Event::PaymentPathFailed`] will
433 /// have come before this.
435 /// [`Retry::Timeout`]: crate::ln::channelmanager::Retry::Timeout
437 /// The payment expired while retrying, based on the provided
438 /// [`PaymentParameters::expiry_time`].
440 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
442 /// We failed to find a route while retrying the payment.
444 /// Note that this generally indicates that we've exhausted the available set of possible
445 /// routes - we tried the payment over a few routes but were not able to find any further
446 /// candidate routes beyond those.
448 /// This error should generally never happen. This likely means that there is a problem with
453 impl_writeable_tlv_based_enum!(PaymentFailureReason,
454 (0, RecipientRejected) => {},
455 (2, UserAbandoned) => {},
456 (4, RetriesExhausted) => {},
457 (6, PaymentExpired) => {},
458 (8, RouteNotFound) => {},
459 (10, UnexpectedError) => {}, ;
462 /// An Event which you should probably take some action in response to.
464 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
465 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
466 /// written as it makes no sense to respond to it after reconnecting to peers).
467 #[derive(Clone, Debug, PartialEq, Eq)]
469 /// Used to indicate that the client should generate a funding transaction with the given
470 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
471 /// Generated in [`ChannelManager`] message handling.
472 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
473 /// counterparty can steal your funds!
475 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
476 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
477 FundingGenerationReady {
478 /// The random channel_id we picked which you'll need to pass into
479 /// [`ChannelManager::funding_transaction_generated`].
481 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
482 temporary_channel_id: ChannelId,
483 /// The counterparty's node_id, which you'll need to pass back into
484 /// [`ChannelManager::funding_transaction_generated`].
486 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
487 counterparty_node_id: PublicKey,
488 /// The value, in satoshis, that the output should have.
489 channel_value_satoshis: u64,
490 /// The script which should be used in the transaction output.
491 output_script: ScriptBuf,
492 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
493 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
494 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
495 /// `user_channel_id` will be randomized for an inbound channel. This may be zero for objects
496 /// serialized with LDK versions prior to 0.0.113.
498 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
499 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
500 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
501 user_channel_id: u128,
503 /// Indicates that we've been offered a payment and it needs to be claimed via calling
504 /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
506 /// Note that if the preimage is not known, you should call
507 /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
508 /// to free up resources for this HTLC and avoid network congestion.
510 /// If [`Event::PaymentClaimable::onion_fields`] is `Some`, and includes custom TLVs with even type
511 /// numbers, you should use [`ChannelManager::fail_htlc_backwards_with_reason`] with
512 /// [`FailureCode::InvalidOnionPayload`] if you fail to understand and handle the contents, or
513 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`] upon successful handling.
514 /// If you don't intend to check for custom TLVs, you can simply use
515 /// [`ChannelManager::claim_funds`], which will automatically fail back even custom TLVs.
517 /// If you fail to call [`ChannelManager::claim_funds`],
518 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`],
519 /// [`ChannelManager::fail_htlc_backwards`], or
520 /// [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will
521 /// be automatically failed.
524 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
525 /// `PaymentClaimable` events may be generated for the same payment. In such a case it is
526 /// polite (and required in the lightning specification) to fail the payment the second time
527 /// and give the sender their money back rather than accepting double payment.
530 /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
532 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
533 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`]: crate::ln::channelmanager::ChannelManager::claim_funds_with_known_custom_tlvs
534 /// [`FailureCode::InvalidOnionPayload`]: crate::ln::channelmanager::FailureCode::InvalidOnionPayload
535 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
536 /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
538 /// The node that will receive the payment after it has been claimed.
539 /// This is useful to identify payments received via [phantom nodes].
540 /// This field will always be filled in when the event was generated by LDK versions
541 /// 0.0.113 and above.
543 /// [phantom nodes]: crate::sign::PhantomKeysManager
544 receiver_node_id: Option<PublicKey>,
545 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
546 /// not stop you from registering duplicate payment hashes for inbound payments.
547 payment_hash: PaymentHash,
548 /// The fields in the onion which were received with each HTLC. Only fields which were
549 /// identical in each HTLC involved in the payment will be included here.
551 /// Payments received on LDK versions prior to 0.0.115 will have this field unset.
552 onion_fields: Option<RecipientOnionFields>,
553 /// The value, in thousandths of a satoshi, that this payment is claimable for. May be greater
554 /// than the invoice amount.
556 /// May be less than the invoice amount if [`ChannelConfig::accept_underpaying_htlcs`] is set
557 /// and the previous hop took an extra fee.
560 /// If [`ChannelConfig::accept_underpaying_htlcs`] is set and you claim without verifying this
561 /// field, you may lose money!
563 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
565 /// The value, in thousands of a satoshi, that was skimmed off of this payment as an extra fee
566 /// taken by our channel counterparty.
568 /// Will always be 0 unless [`ChannelConfig::accept_underpaying_htlcs`] is set.
570 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
571 counterparty_skimmed_fee_msat: u64,
572 /// Information for claiming this received payment, based on whether the purpose of the
573 /// payment is to pay an invoice or to send a spontaneous payment.
574 purpose: PaymentPurpose,
575 /// The `channel_id` indicating over which channel we received the payment.
576 via_channel_id: Option<ChannelId>,
577 /// The `user_channel_id` indicating over which channel we received the payment.
578 via_user_channel_id: Option<u128>,
579 /// The block height at which this payment will be failed back and will no longer be
580 /// eligible for claiming.
582 /// Prior to this height, a call to [`ChannelManager::claim_funds`] is guaranteed to
583 /// succeed, however you should wait for [`Event::PaymentClaimed`] to be sure.
585 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
586 claim_deadline: Option<u32>,
588 /// Indicates a payment has been claimed and we've received money!
590 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
591 /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
592 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
593 /// [`Event::PaymentClaimable`] event.
596 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
597 /// `PaymentClaimable` events may be generated for the same payment. If you then call
598 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
599 /// multiple `PaymentClaimed` events.
601 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
603 /// The node that received the payment.
604 /// This is useful to identify payments which were received via [phantom nodes].
605 /// This field will always be filled in when the event was generated by LDK versions
606 /// 0.0.113 and above.
608 /// [phantom nodes]: crate::sign::PhantomKeysManager
609 receiver_node_id: Option<PublicKey>,
610 /// The payment hash of the claimed payment. Note that LDK will not stop you from
611 /// registering duplicate payment hashes for inbound payments.
612 payment_hash: PaymentHash,
613 /// The value, in thousandths of a satoshi, that this payment is for. May be greater than the
616 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
617 /// spontaneous payment.
618 purpose: PaymentPurpose,
619 /// The HTLCs that comprise the claimed payment. This will be empty for events serialized prior
620 /// to LDK version 0.0.117.
621 htlcs: Vec<ClaimedHTLC>,
622 /// The sender-intended sum total of all the MPP parts. This will be `None` for events
623 /// serialized prior to LDK version 0.0.117.
624 sender_intended_total_msat: Option<u64>,
626 /// Indicates that a peer connection with a node is needed in order to send an [`OnionMessage`].
628 /// Typically, this happens when a [`MessageRouter`] is unable to find a complete path to a
629 /// [`Destination`]. Once a connection is established, any messages buffered by an
630 /// [`OnionMessageHandler`] may be sent.
632 /// This event will not be generated for onion message forwards; only for sends including
633 /// replies. Handlers should connect to the node otherwise any buffered messages may be lost.
635 /// [`OnionMessage`]: msgs::OnionMessage
636 /// [`MessageRouter`]: crate::onion_message::messenger::MessageRouter
637 /// [`Destination`]: crate::onion_message::messenger::Destination
638 /// [`OnionMessageHandler`]: crate::ln::msgs::OnionMessageHandler
640 /// The node id for the node needing a connection.
642 /// Sockets for connecting to the node.
643 addresses: Vec<msgs::SocketAddress>,
645 /// Indicates a request for an invoice failed to yield a response in a reasonable amount of time
646 /// or was explicitly abandoned by [`ChannelManager::abandon_payment`]. This may be for an
647 /// [`InvoiceRequest`] sent for an [`Offer`] or for a [`Refund`] that hasn't been redeemed.
649 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
650 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
651 /// [`Offer`]: crate::offers::offer::Offer
652 /// [`Refund`]: crate::offers::refund::Refund
653 InvoiceRequestFailed {
654 /// The `payment_id` to have been associated with payment for the requested invoice.
655 payment_id: PaymentId,
657 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
658 /// and we got back the payment preimage for it).
660 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
661 /// event. In this situation, you SHOULD treat this payment as having succeeded.
663 /// The `payment_id` passed to [`ChannelManager::send_payment`].
665 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
666 payment_id: Option<PaymentId>,
667 /// The preimage to the hash given to ChannelManager::send_payment.
668 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
669 /// store it somehow!
670 payment_preimage: PaymentPreimage,
671 /// The hash that was given to [`ChannelManager::send_payment`].
673 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
674 payment_hash: PaymentHash,
675 /// The total fee which was spent at intermediate hops in this payment, across all paths.
677 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
678 /// overpayment to the recipient node.
680 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
681 /// overstate the amount paid, though this is unlikely.
683 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
684 fee_paid_msat: Option<u64>,
686 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
687 /// provide failure information for each path attempt in the payment, including retries.
689 /// This event is provided once there are no further pending HTLCs for the payment and the
690 /// payment is no longer retryable, due either to the [`Retry`] provided or
691 /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
693 /// In exceedingly rare cases, it is possible that an [`Event::PaymentFailed`] is generated for
694 /// a payment after an [`Event::PaymentSent`] event for this same payment has already been
695 /// received and processed. In this case, the [`Event::PaymentFailed`] event MUST be ignored,
696 /// and the payment MUST be treated as having succeeded.
698 /// [`Retry`]: crate::ln::channelmanager::Retry
699 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
701 /// The `payment_id` passed to [`ChannelManager::send_payment`].
703 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
704 payment_id: PaymentId,
705 /// The hash that was given to [`ChannelManager::send_payment`].
707 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
708 payment_hash: PaymentHash,
709 /// The reason the payment failed. This is only `None` for events generated or serialized
710 /// by versions prior to 0.0.115.
711 reason: Option<PaymentFailureReason>,
713 /// Indicates that a path for an outbound payment was successful.
715 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
716 /// [`Event::PaymentSent`] for obtaining the payment preimage.
717 PaymentPathSuccessful {
718 /// The `payment_id` passed to [`ChannelManager::send_payment`].
720 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
721 payment_id: PaymentId,
722 /// The hash that was given to [`ChannelManager::send_payment`].
724 /// This will be `Some` for all payments which completed on LDK 0.0.104 or later.
726 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
727 payment_hash: Option<PaymentHash>,
728 /// The payment path that was successful.
730 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
733 /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
736 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
737 /// [`Event::PaymentFailed`].
739 /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
742 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
744 /// The `payment_id` passed to [`ChannelManager::send_payment`].
746 /// This will be `Some` for all payment paths which failed on LDK 0.0.103 or later.
748 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
749 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
750 payment_id: Option<PaymentId>,
751 /// The hash that was given to [`ChannelManager::send_payment`].
753 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
754 payment_hash: PaymentHash,
755 /// Indicates the payment was rejected for some reason by the recipient. This implies that
756 /// the payment has failed, not just the route in question. If this is not set, the payment may
757 /// be retried via a different route.
758 payment_failed_permanently: bool,
759 /// Extra error details based on the failure type. May contain an update that needs to be
760 /// applied to the [`NetworkGraph`].
762 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
763 failure: PathFailure,
764 /// The payment path that failed.
766 /// The channel responsible for the failed payment path.
768 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
769 /// may not refer to a channel in the public network graph. These aliases may also collide
770 /// with channels in the public network graph.
772 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
773 /// retried. May be `None` for older [`Event`] serializations.
774 short_channel_id: Option<u64>,
776 error_code: Option<u16>,
778 error_data: Option<Vec<u8>>,
780 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
782 /// The id returned by [`ChannelManager::send_probe`].
784 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
785 payment_id: PaymentId,
786 /// The hash generated by [`ChannelManager::send_probe`].
788 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
789 payment_hash: PaymentHash,
790 /// The payment path that was successful.
793 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
795 /// The id returned by [`ChannelManager::send_probe`].
797 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
798 payment_id: PaymentId,
799 /// The hash generated by [`ChannelManager::send_probe`].
801 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
802 payment_hash: PaymentHash,
803 /// The payment path that failed.
805 /// The channel responsible for the failed probe.
807 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
808 /// may not refer to a channel in the public network graph. These aliases may also collide
809 /// with channels in the public network graph.
810 short_channel_id: Option<u64>,
812 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
813 /// a time in the future.
815 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
816 PendingHTLCsForwardable {
817 /// The minimum amount of time that should be waited prior to calling
818 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
819 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
820 /// now + 5*time_forwardable).
821 time_forwardable: Duration,
823 /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
824 /// you've encoded an intercept scid in the receiver's invoice route hints using
825 /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
827 /// [`ChannelManager::forward_intercepted_htlc`] or
828 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
829 /// their docs for more information.
831 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
832 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
833 /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
834 /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
836 /// An id to help LDK identify which HTLC is being forwarded or failed.
837 intercept_id: InterceptId,
838 /// The fake scid that was programmed as the next hop's scid, generated using
839 /// [`ChannelManager::get_intercept_scid`].
841 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
842 requested_next_hop_scid: u64,
843 /// The payment hash used for this HTLC.
844 payment_hash: PaymentHash,
845 /// How many msats were received on the inbound edge of this HTLC.
846 inbound_amount_msat: u64,
847 /// How many msats the payer intended to route to the next node. Depending on the reason you are
848 /// intercepting this payment, you might take a fee by forwarding less than this amount.
849 /// Forwarding less than this amount may break compatibility with LDK versions prior to 0.0.116.
851 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
852 /// check that whatever fee you want has been included here or subtract it as required. Further,
853 /// LDK will not stop you from forwarding more than you received.
854 expected_outbound_amount_msat: u64,
856 /// Used to indicate that an output which you should know how to spend was confirmed on chain
857 /// and is now spendable.
858 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
859 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
860 /// somewhere and spend them when you create on-chain transactions.
862 /// The outputs which you should store as spendable by you.
863 outputs: Vec<SpendableOutputDescriptor>,
864 /// The `channel_id` indicating which channel the spendable outputs belong to.
866 /// This will always be `Some` for events generated by LDK versions 0.0.117 and above.
867 channel_id: Option<ChannelId>,
869 /// This event is generated when a payment has been successfully forwarded through us and a
870 /// forwarding fee earned.
872 /// The channel id of the incoming channel between the previous node and us.
874 /// This is only `None` for events generated or serialized by versions prior to 0.0.107.
875 prev_channel_id: Option<ChannelId>,
876 /// The channel id of the outgoing channel between the next node and us.
878 /// This is only `None` for events generated or serialized by versions prior to 0.0.107.
879 next_channel_id: Option<ChannelId>,
880 /// The `user_channel_id` of the incoming channel between the previous node and us.
882 /// This is only `None` for events generated or serialized by versions prior to 0.0.122.
883 prev_user_channel_id: Option<u128>,
884 /// The `user_channel_id` of the outgoing channel between the next node and us.
886 /// This will be `None` if the payment was settled via an on-chain transaction. See the
887 /// caveat described for the `total_fee_earned_msat` field. Moreover it will be `None` for
888 /// events generated or serialized by versions prior to 0.0.122.
889 next_user_channel_id: Option<u128>,
890 /// The total fee, in milli-satoshis, which was earned as a result of the payment.
892 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
893 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
894 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
895 /// claimed the full value in millisatoshis from the source. In this case,
896 /// `claim_from_onchain_tx` will be set.
898 /// If the channel which sent us the payment has been force-closed, we will claim the funds
899 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
900 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
901 /// `PaymentForwarded` events are generated for the same payment iff `total_fee_earned_msat` is
903 total_fee_earned_msat: Option<u64>,
904 /// The share of the total fee, in milli-satoshis, which was withheld in addition to the
907 /// This will only be `Some` if we forwarded an intercepted HTLC with less than the
908 /// expected amount. This means our counterparty accepted to receive less than the invoice
909 /// amount, e.g., by claiming the payment featuring a corresponding
910 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`].
912 /// Will also always be `None` for events serialized with LDK prior to version 0.0.122.
914 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
916 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`]: Self::PaymentClaimable::counterparty_skimmed_fee_msat
917 skimmed_fee_msat: Option<u64>,
918 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
920 claim_from_onchain_tx: bool,
921 /// The final amount forwarded, in milli-satoshis, after the fee is deducted.
923 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
924 outbound_amount_forwarded_msat: Option<u64>,
926 /// Used to indicate that a channel with the given `channel_id` is being opened and pending
927 /// confirmation on-chain.
929 /// This event is emitted when the funding transaction has been signed and is broadcast to the
930 /// network. For 0conf channels it will be immediately followed by the corresponding
931 /// [`Event::ChannelReady`] event.
933 /// The `channel_id` of the channel that is pending confirmation.
934 channel_id: ChannelId,
935 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
936 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
937 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
938 /// `user_channel_id` will be randomized for an inbound channel.
940 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
941 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
942 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
943 user_channel_id: u128,
944 /// The `temporary_channel_id` this channel used to be known by during channel establishment.
946 /// Will be `None` for channels created prior to LDK version 0.0.115.
947 former_temporary_channel_id: Option<ChannelId>,
948 /// The `node_id` of the channel counterparty.
949 counterparty_node_id: PublicKey,
950 /// The outpoint of the channel's funding transaction.
951 funding_txo: OutPoint,
952 /// The features that this channel will operate with.
954 /// Will be `None` for channels created prior to LDK version 0.0.122.
955 channel_type: Option<ChannelTypeFeatures>,
957 /// Used to indicate that a channel with the given `channel_id` is ready to
958 /// be used. This event is emitted either when the funding transaction has been confirmed
959 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
962 /// The `channel_id` of the channel that is ready.
963 channel_id: ChannelId,
964 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
965 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
966 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
967 /// `user_channel_id` will be randomized for an inbound channel.
969 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
970 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
971 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
972 user_channel_id: u128,
973 /// The `node_id` of the channel counterparty.
974 counterparty_node_id: PublicKey,
975 /// The features that this channel will operate with.
976 channel_type: ChannelTypeFeatures,
978 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
979 /// process of closure.
981 /// Note that this event is only triggered for accepted channels: if the
982 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true and the channel is
983 /// rejected, no `ChannelClosed` event will be sent.
985 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
986 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
988 /// The `channel_id` of the channel which has been closed. Note that on-chain transactions
989 /// resolving the channel are likely still awaiting confirmation.
990 channel_id: ChannelId,
991 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
992 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
993 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
994 /// `user_channel_id` will be randomized for inbound channels.
995 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
996 /// zero for objects serialized with LDK versions prior to 0.0.102.
998 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
999 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1000 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1001 user_channel_id: u128,
1002 /// The reason the channel was closed.
1003 reason: ClosureReason,
1004 /// Counterparty in the closed channel.
1006 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
1007 counterparty_node_id: Option<PublicKey>,
1008 /// Channel capacity of the closing channel (sats).
1010 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
1011 channel_capacity_sats: Option<u64>,
1012 /// The original channel funding TXO; this helps checking for the existence and confirmation
1013 /// status of the closing tx.
1014 /// Note that for instances serialized in v0.0.119 or prior this will be missing (None).
1015 channel_funding_txo: Option<transaction::OutPoint>,
1017 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
1018 /// inputs for another purpose.
1020 /// This event is not guaranteed to be generated for channels that are closed due to a restart.
1022 /// The channel_id of the channel which has been closed.
1023 channel_id: ChannelId,
1024 /// The full transaction received from the user
1025 transaction: Transaction
1027 /// Indicates a request to open a new channel by a peer.
1029 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the request,
1030 /// call [`ChannelManager::force_close_without_broadcasting_txn`]. Note that a ['ChannelClosed`]
1031 /// event will _not_ be triggered if the channel is rejected.
1033 /// The event is only triggered when a new open channel request is received and the
1034 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
1036 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1037 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1038 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1039 OpenChannelRequest {
1040 /// The temporary channel ID of the channel requested to be opened.
1042 /// When responding to the request, the `temporary_channel_id` should be passed
1043 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
1044 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
1046 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1047 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1048 temporary_channel_id: ChannelId,
1049 /// The node_id of the counterparty requesting to open the channel.
1051 /// When responding to the request, the `counterparty_node_id` should be passed
1052 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
1053 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
1056 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1057 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1058 counterparty_node_id: PublicKey,
1059 /// The channel value of the requested channel.
1060 funding_satoshis: u64,
1061 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
1063 /// The features that this channel will operate with. If you reject the channel, a
1064 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
1067 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
1068 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1071 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
1072 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1073 /// 0.0.107. Channels setting this type also need to get manually accepted via
1074 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
1075 /// or will be rejected otherwise.
1077 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1078 channel_type: ChannelTypeFeatures,
1080 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
1083 /// Some scenarios where this event may be sent include:
1084 /// * Insufficient capacity in the outbound channel
1085 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
1086 /// * When an unknown SCID is requested for forwarding a payment.
1087 /// * Expected MPP amount has already been reached
1088 /// * The HTLC has timed out
1090 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
1091 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
1092 HTLCHandlingFailed {
1093 /// The channel over which the HTLC was received.
1094 prev_channel_id: ChannelId,
1095 /// Destination of the HTLC that failed to be processed.
1096 failed_next_destination: HTLCDestination,
1098 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
1099 /// requires confirmed external funds to be readily available to spend.
1101 /// LDK does not currently generate this event unless the
1102 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`] config flag is set to true.
1103 /// It is limited to the scope of channels with anchor outputs.
1105 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`]: crate::util::config::ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx
1106 BumpTransaction(BumpTransactionEvent),
1109 impl Writeable for Event {
1110 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1112 &Event::FundingGenerationReady { .. } => {
1114 // We never write out FundingGenerationReady events as, upon disconnection, peers
1115 // drop any channels which have not yet exchanged funding_signed.
1117 &Event::PaymentClaimable { ref payment_hash, ref amount_msat, counterparty_skimmed_fee_msat,
1118 ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id,
1119 ref claim_deadline, ref onion_fields
1122 let mut payment_secret = None;
1123 let payment_preimage;
1124 let mut payment_context = None;
1126 PaymentPurpose::Bolt11InvoicePayment {
1127 payment_preimage: preimage, payment_secret: secret
1129 payment_secret = Some(secret);
1130 payment_preimage = *preimage;
1132 PaymentPurpose::Bolt12OfferPayment {
1133 payment_preimage: preimage, payment_secret: secret, payment_context: context
1135 payment_secret = Some(secret);
1136 payment_preimage = *preimage;
1137 payment_context = Some(PaymentContextRef::Bolt12Offer(context));
1139 PaymentPurpose::Bolt12RefundPayment {
1140 payment_preimage: preimage, payment_secret: secret, payment_context: context
1142 payment_secret = Some(secret);
1143 payment_preimage = *preimage;
1144 payment_context = Some(PaymentContextRef::Bolt12Refund(context));
1146 PaymentPurpose::SpontaneousPayment(preimage) => {
1147 payment_preimage = Some(*preimage);
1150 let skimmed_fee_opt = if counterparty_skimmed_fee_msat == 0 { None }
1151 else { Some(counterparty_skimmed_fee_msat) };
1152 write_tlv_fields!(writer, {
1153 (0, payment_hash, required),
1154 (1, receiver_node_id, option),
1155 (2, payment_secret, option),
1156 (3, via_channel_id, option),
1157 (4, amount_msat, required),
1158 (5, via_user_channel_id, option),
1159 // Type 6 was `user_payment_id` on 0.0.103 and earlier
1160 (7, claim_deadline, option),
1161 (8, payment_preimage, option),
1162 (9, onion_fields, option),
1163 (10, skimmed_fee_opt, option),
1164 (11, payment_context, option),
1167 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
1169 write_tlv_fields!(writer, {
1170 (0, payment_preimage, required),
1171 (1, payment_hash, required),
1172 (3, payment_id, option),
1173 (5, fee_paid_msat, option),
1176 &Event::PaymentPathFailed {
1177 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
1178 ref path, ref short_channel_id,
1186 error_code.write(writer)?;
1188 error_data.write(writer)?;
1189 write_tlv_fields!(writer, {
1190 (0, payment_hash, required),
1191 (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
1192 (2, payment_failed_permanently, required),
1193 (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
1194 (4, path.blinded_tail, option),
1195 (5, path.hops, required_vec),
1196 (7, short_channel_id, option),
1197 (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
1198 (11, payment_id, option),
1199 (13, failure, required),
1202 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
1204 // Note that we now ignore these on the read end as we'll re-generate them in
1205 // ChannelManager, we write them here only for backwards compatibility.
1207 &Event::SpendableOutputs { ref outputs, channel_id } => {
1209 write_tlv_fields!(writer, {
1210 (0, WithoutLength(outputs), required),
1211 (1, channel_id, option),
1214 &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1216 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1217 write_tlv_fields!(writer, {
1218 (0, intercept_id, required),
1219 (2, intercept_scid, required),
1220 (4, payment_hash, required),
1221 (6, inbound_amount_msat, required),
1222 (8, expected_outbound_amount_msat, required),
1225 &Event::PaymentForwarded {
1226 prev_channel_id, next_channel_id, prev_user_channel_id, next_user_channel_id,
1227 total_fee_earned_msat, skimmed_fee_msat, claim_from_onchain_tx,
1228 outbound_amount_forwarded_msat,
1231 write_tlv_fields!(writer, {
1232 (0, total_fee_earned_msat, option),
1233 (1, prev_channel_id, option),
1234 (2, claim_from_onchain_tx, required),
1235 (3, next_channel_id, option),
1236 (5, outbound_amount_forwarded_msat, option),
1237 (7, skimmed_fee_msat, option),
1238 (9, prev_user_channel_id, option),
1239 (11, next_user_channel_id, option),
1242 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason,
1243 ref counterparty_node_id, ref channel_capacity_sats, ref channel_funding_txo
1246 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1247 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1248 // separate u64 values.
1249 let user_channel_id_low = *user_channel_id as u64;
1250 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1251 write_tlv_fields!(writer, {
1252 (0, channel_id, required),
1253 (1, user_channel_id_low, required),
1254 (2, reason, required),
1255 (3, user_channel_id_high, required),
1256 (5, counterparty_node_id, option),
1257 (7, channel_capacity_sats, option),
1258 (9, channel_funding_txo, option),
1261 &Event::DiscardFunding { ref channel_id, ref transaction } => {
1262 11u8.write(writer)?;
1263 write_tlv_fields!(writer, {
1264 (0, channel_id, required),
1265 (2, transaction, required)
1268 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1269 13u8.write(writer)?;
1270 write_tlv_fields!(writer, {
1271 (0, payment_id, required),
1272 (2, payment_hash, option),
1273 (4, path.hops, required_vec),
1274 (6, path.blinded_tail, option),
1277 &Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
1278 15u8.write(writer)?;
1279 write_tlv_fields!(writer, {
1280 (0, payment_id, required),
1281 (1, reason, option),
1282 (2, payment_hash, required),
1285 &Event::OpenChannelRequest { .. } => {
1286 17u8.write(writer)?;
1287 // We never write the OpenChannelRequest events as, upon disconnection, peers
1288 // drop any channels which have not yet exchanged funding_signed.
1290 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref htlcs, ref sender_intended_total_msat } => {
1291 19u8.write(writer)?;
1292 write_tlv_fields!(writer, {
1293 (0, payment_hash, required),
1294 (1, receiver_node_id, option),
1295 (2, purpose, required),
1296 (4, amount_msat, required),
1297 (5, *htlcs, optional_vec),
1298 (7, sender_intended_total_msat, option),
1301 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1302 21u8.write(writer)?;
1303 write_tlv_fields!(writer, {
1304 (0, payment_id, required),
1305 (2, payment_hash, required),
1306 (4, path.hops, required_vec),
1307 (6, path.blinded_tail, option),
1310 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1311 23u8.write(writer)?;
1312 write_tlv_fields!(writer, {
1313 (0, payment_id, required),
1314 (2, payment_hash, required),
1315 (4, path.hops, required_vec),
1316 (6, short_channel_id, option),
1317 (8, path.blinded_tail, option),
1320 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1321 25u8.write(writer)?;
1322 write_tlv_fields!(writer, {
1323 (0, prev_channel_id, required),
1324 (2, failed_next_destination, required),
1327 &Event::BumpTransaction(ref event)=> {
1328 27u8.write(writer)?;
1330 // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1331 // upon restarting anyway if they remain unresolved.
1332 BumpTransactionEvent::ChannelClose { .. } => {}
1333 BumpTransactionEvent::HTLCResolution { .. } => {}
1335 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1337 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1338 29u8.write(writer)?;
1339 write_tlv_fields!(writer, {
1340 (0, channel_id, required),
1341 (2, user_channel_id, required),
1342 (4, counterparty_node_id, required),
1343 (6, channel_type, required),
1346 &Event::ChannelPending { ref channel_id, ref user_channel_id,
1347 ref former_temporary_channel_id, ref counterparty_node_id, ref funding_txo,
1350 31u8.write(writer)?;
1351 write_tlv_fields!(writer, {
1352 (0, channel_id, required),
1353 (1, channel_type, option),
1354 (2, user_channel_id, required),
1355 (4, former_temporary_channel_id, required),
1356 (6, counterparty_node_id, required),
1357 (8, funding_txo, required),
1360 &Event::InvoiceRequestFailed { ref payment_id } => {
1361 33u8.write(writer)?;
1362 write_tlv_fields!(writer, {
1363 (0, payment_id, required),
1366 &Event::ConnectionNeeded { .. } => {
1367 35u8.write(writer)?;
1368 // Never write ConnectionNeeded events as buffered onion messages aren't serialized.
1370 // Note that, going forward, all new events must only write data inside of
1371 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1372 // data via `write_tlv_fields`.
1377 impl MaybeReadable for Event {
1378 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1379 match Readable::read(reader)? {
1380 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events.
1384 let mut payment_hash = PaymentHash([0; 32]);
1385 let mut payment_preimage = None;
1386 let mut payment_secret = None;
1387 let mut amount_msat = 0;
1388 let mut counterparty_skimmed_fee_msat_opt = None;
1389 let mut receiver_node_id = None;
1390 let mut _user_payment_id = None::<u64>; // Used in 0.0.103 and earlier, no longer written in 0.0.116+.
1391 let mut via_channel_id = None;
1392 let mut claim_deadline = None;
1393 let mut via_user_channel_id = None;
1394 let mut onion_fields = None;
1395 let mut payment_context = None;
1396 read_tlv_fields!(reader, {
1397 (0, payment_hash, required),
1398 (1, receiver_node_id, option),
1399 (2, payment_secret, option),
1400 (3, via_channel_id, option),
1401 (4, amount_msat, required),
1402 (5, via_user_channel_id, option),
1403 (6, _user_payment_id, option),
1404 (7, claim_deadline, option),
1405 (8, payment_preimage, option),
1406 (9, onion_fields, option),
1407 (10, counterparty_skimmed_fee_msat_opt, option),
1408 (11, payment_context, option),
1410 let purpose = match payment_secret {
1411 Some(secret) => match payment_context {
1412 Some(PaymentContext::Unknown(_)) | None => {
1413 PaymentPurpose::Bolt11InvoicePayment {
1415 payment_secret: secret,
1418 Some(PaymentContext::Bolt12Offer(context)) => {
1419 PaymentPurpose::Bolt12OfferPayment {
1421 payment_secret: secret,
1422 payment_context: context,
1425 Some(PaymentContext::Bolt12Refund(context)) => {
1426 PaymentPurpose::Bolt12RefundPayment {
1428 payment_secret: secret,
1429 payment_context: context,
1433 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1434 None => return Err(msgs::DecodeError::InvalidValue),
1436 Ok(Some(Event::PaymentClaimable {
1440 counterparty_skimmed_fee_msat: counterparty_skimmed_fee_msat_opt.unwrap_or(0),
1443 via_user_channel_id,
1452 let mut payment_preimage = PaymentPreimage([0; 32]);
1453 let mut payment_hash = None;
1454 let mut payment_id = None;
1455 let mut fee_paid_msat = None;
1456 read_tlv_fields!(reader, {
1457 (0, payment_preimage, required),
1458 (1, payment_hash, option),
1459 (3, payment_id, option),
1460 (5, fee_paid_msat, option),
1462 if payment_hash.is_none() {
1463 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()));
1465 Ok(Some(Event::PaymentSent {
1468 payment_hash: payment_hash.unwrap(),
1477 let error_code = Readable::read(reader)?;
1479 let error_data = Readable::read(reader)?;
1480 let mut payment_hash = PaymentHash([0; 32]);
1481 let mut payment_failed_permanently = false;
1482 let mut network_update = None;
1483 let mut blinded_tail: Option<BlindedTail> = None;
1484 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1485 let mut short_channel_id = None;
1486 let mut payment_id = None;
1487 let mut failure_opt = None;
1488 read_tlv_fields!(reader, {
1489 (0, payment_hash, required),
1490 (1, network_update, upgradable_option),
1491 (2, payment_failed_permanently, required),
1492 (4, blinded_tail, option),
1493 // Added as a part of LDK 0.0.101 and always filled in since.
1494 // Defaults to an empty Vec, though likely should have been `Option`al.
1495 (5, path, optional_vec),
1496 (7, short_channel_id, option),
1497 (11, payment_id, option),
1498 (13, failure_opt, upgradable_option),
1500 let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1501 Ok(Some(Event::PaymentPathFailed {
1504 payment_failed_permanently,
1506 path: Path { hops: path.unwrap(), blinded_tail },
1519 let mut outputs = WithoutLength(Vec::new());
1520 let mut channel_id: Option<ChannelId> = None;
1521 read_tlv_fields!(reader, {
1522 (0, outputs, required),
1523 (1, channel_id, option),
1525 Ok(Some(Event::SpendableOutputs { outputs: outputs.0, channel_id }))
1530 let mut payment_hash = PaymentHash([0; 32]);
1531 let mut intercept_id = InterceptId([0; 32]);
1532 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1533 let mut inbound_amount_msat = 0;
1534 let mut expected_outbound_amount_msat = 0;
1535 read_tlv_fields!(reader, {
1536 (0, intercept_id, required),
1537 (2, requested_next_hop_scid, required),
1538 (4, payment_hash, required),
1539 (6, inbound_amount_msat, required),
1540 (8, expected_outbound_amount_msat, required),
1542 let next_scid = match requested_next_hop_scid {
1543 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1545 Ok(Some(Event::HTLCIntercepted {
1547 requested_next_hop_scid: next_scid,
1548 inbound_amount_msat,
1549 expected_outbound_amount_msat,
1555 let mut prev_channel_id = None;
1556 let mut next_channel_id = None;
1557 let mut prev_user_channel_id = None;
1558 let mut next_user_channel_id = None;
1559 let mut total_fee_earned_msat = None;
1560 let mut skimmed_fee_msat = None;
1561 let mut claim_from_onchain_tx = false;
1562 let mut outbound_amount_forwarded_msat = None;
1563 read_tlv_fields!(reader, {
1564 (0, total_fee_earned_msat, option),
1565 (1, prev_channel_id, option),
1566 (2, claim_from_onchain_tx, required),
1567 (3, next_channel_id, option),
1568 (5, outbound_amount_forwarded_msat, option),
1569 (7, skimmed_fee_msat, option),
1570 (9, prev_user_channel_id, option),
1571 (11, next_user_channel_id, option),
1573 Ok(Some(Event::PaymentForwarded {
1574 prev_channel_id, next_channel_id, prev_user_channel_id,
1575 next_user_channel_id, total_fee_earned_msat, skimmed_fee_msat,
1576 claim_from_onchain_tx, outbound_amount_forwarded_msat,
1583 let mut channel_id = ChannelId::new_zero();
1584 let mut reason = UpgradableRequired(None);
1585 let mut user_channel_id_low_opt: Option<u64> = None;
1586 let mut user_channel_id_high_opt: Option<u64> = None;
1587 let mut counterparty_node_id = None;
1588 let mut channel_capacity_sats = None;
1589 let mut channel_funding_txo = None;
1590 read_tlv_fields!(reader, {
1591 (0, channel_id, required),
1592 (1, user_channel_id_low_opt, option),
1593 (2, reason, upgradable_required),
1594 (3, user_channel_id_high_opt, option),
1595 (5, counterparty_node_id, option),
1596 (7, channel_capacity_sats, option),
1597 (9, channel_funding_txo, option),
1600 // `user_channel_id` used to be a single u64 value. In order to remain
1601 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1602 // as two separate u64 values.
1603 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1604 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1606 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required),
1607 counterparty_node_id, channel_capacity_sats, channel_funding_txo }))
1613 let mut channel_id = ChannelId::new_zero();
1614 let mut transaction = Transaction{ version: 2, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
1615 read_tlv_fields!(reader, {
1616 (0, channel_id, required),
1617 (2, transaction, required),
1619 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1625 _init_and_read_len_prefixed_tlv_fields!(reader, {
1626 (0, payment_id, required),
1627 (2, payment_hash, option),
1628 (4, path, required_vec),
1629 (6, blinded_tail, option),
1631 Ok(Some(Event::PaymentPathSuccessful {
1632 payment_id: payment_id.0.unwrap(),
1634 path: Path { hops: path, blinded_tail },
1641 let mut payment_hash = PaymentHash([0; 32]);
1642 let mut payment_id = PaymentId([0; 32]);
1643 let mut reason = None;
1644 read_tlv_fields!(reader, {
1645 (0, payment_id, required),
1646 (1, reason, upgradable_option),
1647 (2, payment_hash, required),
1649 Ok(Some(Event::PaymentFailed {
1658 // Value 17 is used for `Event::OpenChannelRequest`.
1663 let mut payment_hash = PaymentHash([0; 32]);
1664 let mut purpose = UpgradableRequired(None);
1665 let mut amount_msat = 0;
1666 let mut receiver_node_id = None;
1667 let mut htlcs: Option<Vec<ClaimedHTLC>> = Some(vec![]);
1668 let mut sender_intended_total_msat: Option<u64> = None;
1669 read_tlv_fields!(reader, {
1670 (0, payment_hash, required),
1671 (1, receiver_node_id, option),
1672 (2, purpose, upgradable_required),
1673 (4, amount_msat, required),
1674 (5, htlcs, optional_vec),
1675 (7, sender_intended_total_msat, option),
1677 Ok(Some(Event::PaymentClaimed {
1680 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1682 htlcs: htlcs.unwrap_or(vec![]),
1683 sender_intended_total_msat,
1690 _init_and_read_len_prefixed_tlv_fields!(reader, {
1691 (0, payment_id, required),
1692 (2, payment_hash, required),
1693 (4, path, required_vec),
1694 (6, blinded_tail, option),
1696 Ok(Some(Event::ProbeSuccessful {
1697 payment_id: payment_id.0.unwrap(),
1698 payment_hash: payment_hash.0.unwrap(),
1699 path: Path { hops: path, blinded_tail },
1706 _init_and_read_len_prefixed_tlv_fields!(reader, {
1707 (0, payment_id, required),
1708 (2, payment_hash, required),
1709 (4, path, required_vec),
1710 (6, short_channel_id, option),
1711 (8, blinded_tail, option),
1713 Ok(Some(Event::ProbeFailed {
1714 payment_id: payment_id.0.unwrap(),
1715 payment_hash: payment_hash.0.unwrap(),
1716 path: Path { hops: path, blinded_tail },
1724 let mut prev_channel_id = ChannelId::new_zero();
1725 let mut failed_next_destination_opt = UpgradableRequired(None);
1726 read_tlv_fields!(reader, {
1727 (0, prev_channel_id, required),
1728 (2, failed_next_destination_opt, upgradable_required),
1730 Ok(Some(Event::HTLCHandlingFailed {
1732 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1740 let mut channel_id = ChannelId::new_zero();
1741 let mut user_channel_id: u128 = 0;
1742 let mut counterparty_node_id = RequiredWrapper(None);
1743 let mut channel_type = RequiredWrapper(None);
1744 read_tlv_fields!(reader, {
1745 (0, channel_id, required),
1746 (2, user_channel_id, required),
1747 (4, counterparty_node_id, required),
1748 (6, channel_type, required),
1751 Ok(Some(Event::ChannelReady {
1754 counterparty_node_id: counterparty_node_id.0.unwrap(),
1755 channel_type: channel_type.0.unwrap()
1762 let mut channel_id = ChannelId::new_zero();
1763 let mut user_channel_id: u128 = 0;
1764 let mut former_temporary_channel_id = None;
1765 let mut counterparty_node_id = RequiredWrapper(None);
1766 let mut funding_txo = RequiredWrapper(None);
1767 let mut channel_type = None;
1768 read_tlv_fields!(reader, {
1769 (0, channel_id, required),
1770 (1, channel_type, option),
1771 (2, user_channel_id, required),
1772 (4, former_temporary_channel_id, required),
1773 (6, counterparty_node_id, required),
1774 (8, funding_txo, required),
1777 Ok(Some(Event::ChannelPending {
1780 former_temporary_channel_id,
1781 counterparty_node_id: counterparty_node_id.0.unwrap(),
1782 funding_txo: funding_txo.0.unwrap(),
1790 _init_and_read_len_prefixed_tlv_fields!(reader, {
1791 (0, payment_id, required),
1793 Ok(Some(Event::InvoiceRequestFailed {
1794 payment_id: payment_id.0.unwrap(),
1799 // Note that we do not write a length-prefixed TLV for ConnectionNeeded events.
1801 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1802 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1804 x if x % 2 == 1 => {
1805 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1806 // which prefixes the whole thing with a length BigSize. Because the event is
1807 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1808 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1809 // exactly the number of bytes specified, ignoring them entirely.
1810 let tlv_len: BigSize = Readable::read(reader)?;
1811 FixedLengthReader::new(reader, tlv_len.0)
1812 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1815 _ => Err(msgs::DecodeError::InvalidValue)
1820 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1821 /// broadcast to most peers).
1822 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1823 #[derive(Clone, Debug)]
1824 #[cfg_attr(test, derive(PartialEq))]
1825 pub enum MessageSendEvent {
1826 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1827 /// message provided to the given peer.
1829 /// The node_id of the node which should receive this message
1831 /// The message which should be sent.
1832 msg: msgs::AcceptChannel,
1834 /// Used to indicate that we've accepted a V2 channel open and should send the accept_channel2
1835 /// message provided to the given peer.
1836 SendAcceptChannelV2 {
1837 /// The node_id of the node which should receive this message
1839 /// The message which should be sent.
1840 msg: msgs::AcceptChannelV2,
1842 /// Used to indicate that we've initiated a channel open and should send the open_channel
1843 /// message provided to the given peer.
1845 /// The node_id of the node which should receive this message
1847 /// The message which should be sent.
1848 msg: msgs::OpenChannel,
1850 /// Used to indicate that we've initiated a V2 channel open and should send the open_channel2
1851 /// message provided to the given peer.
1853 /// The node_id of the node which should receive this message
1855 /// The message which should be sent.
1856 msg: msgs::OpenChannelV2,
1858 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1859 SendFundingCreated {
1860 /// The node_id of the node which should receive this message
1862 /// The message which should be sent.
1863 msg: msgs::FundingCreated,
1865 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1867 /// The node_id of the node which should receive this message
1869 /// The message which should be sent.
1870 msg: msgs::FundingSigned,
1872 /// Used to indicate that a stfu message should be sent to the peer with the given node id.
1874 /// The node_id of the node which should receive this message
1876 /// The message which should be sent.
1879 /// Used to indicate that a splice message should be sent to the peer with the given node id.
1881 /// The node_id of the node which should receive this message
1883 /// The message which should be sent.
1886 /// Used to indicate that a splice_ack message should be sent to the peer with the given node id.
1888 /// The node_id of the node which should receive this message
1890 /// The message which should be sent.
1891 msg: msgs::SpliceAck,
1893 /// Used to indicate that a splice_locked message should be sent to the peer with the given node id.
1895 /// The node_id of the node which should receive this message
1897 /// The message which should be sent.
1898 msg: msgs::SpliceLocked,
1900 /// Used to indicate that a tx_add_input message should be sent to the peer with the given node_id.
1902 /// The node_id of the node which should receive this message
1904 /// The message which should be sent.
1905 msg: msgs::TxAddInput,
1907 /// Used to indicate that a tx_add_output message should be sent to the peer with the given node_id.
1909 /// The node_id of the node which should receive this message
1911 /// The message which should be sent.
1912 msg: msgs::TxAddOutput,
1914 /// Used to indicate that a tx_remove_input message should be sent to the peer with the given node_id.
1916 /// The node_id of the node which should receive this message
1918 /// The message which should be sent.
1919 msg: msgs::TxRemoveInput,
1921 /// Used to indicate that a tx_remove_output message should be sent to the peer with the given node_id.
1922 SendTxRemoveOutput {
1923 /// The node_id of the node which should receive this message
1925 /// The message which should be sent.
1926 msg: msgs::TxRemoveOutput,
1928 /// Used to indicate that a tx_complete message should be sent to the peer with the given node_id.
1930 /// The node_id of the node which should receive this message
1932 /// The message which should be sent.
1933 msg: msgs::TxComplete,
1935 /// Used to indicate that a tx_signatures message should be sent to the peer with the given node_id.
1937 /// The node_id of the node which should receive this message
1939 /// The message which should be sent.
1940 msg: msgs::TxSignatures,
1942 /// Used to indicate that a tx_init_rbf message should be sent to the peer with the given node_id.
1944 /// The node_id of the node which should receive this message
1946 /// The message which should be sent.
1947 msg: msgs::TxInitRbf,
1949 /// Used to indicate that a tx_ack_rbf message should be sent to the peer with the given node_id.
1951 /// The node_id of the node which should receive this message
1953 /// The message which should be sent.
1954 msg: msgs::TxAckRbf,
1956 /// Used to indicate that a tx_abort message should be sent to the peer with the given node_id.
1958 /// The node_id of the node which should receive this message
1960 /// The message which should be sent.
1963 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1965 /// The node_id of the node which should receive these message(s)
1967 /// The channel_ready message which should be sent.
1968 msg: msgs::ChannelReady,
1970 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1971 SendAnnouncementSignatures {
1972 /// The node_id of the node which should receive these message(s)
1974 /// The announcement_signatures message which should be sent.
1975 msg: msgs::AnnouncementSignatures,
1977 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1978 /// message should be sent to the peer with the given node_id.
1980 /// The node_id of the node which should receive these message(s)
1982 /// The update messages which should be sent. ALL messages in the struct should be sent!
1983 updates: msgs::CommitmentUpdate,
1985 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1987 /// The node_id of the node which should receive this message
1989 /// The message which should be sent.
1990 msg: msgs::RevokeAndACK,
1992 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1994 /// The node_id of the node which should receive this message
1996 /// The message which should be sent.
1997 msg: msgs::ClosingSigned,
1999 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
2001 /// The node_id of the node which should receive this message
2003 /// The message which should be sent.
2004 msg: msgs::Shutdown,
2006 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
2007 SendChannelReestablish {
2008 /// The node_id of the node which should receive this message
2010 /// The message which should be sent.
2011 msg: msgs::ChannelReestablish,
2013 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
2014 /// initial connection to ensure our peers know about our channels.
2015 SendChannelAnnouncement {
2016 /// The node_id of the node which should receive this message
2018 /// The channel_announcement which should be sent.
2019 msg: msgs::ChannelAnnouncement,
2020 /// The followup channel_update which should be sent.
2021 update_msg: msgs::ChannelUpdate,
2023 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
2024 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
2026 /// Note that after doing so, you very likely (unless you did so very recently) want to
2027 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
2028 /// ensures that any nodes which see our channel_announcement also have a relevant
2029 /// node_announcement, including relevant feature flags which may be important for routing
2030 /// through or to us.
2032 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
2033 BroadcastChannelAnnouncement {
2034 /// The channel_announcement which should be sent.
2035 msg: msgs::ChannelAnnouncement,
2036 /// The followup channel_update which should be sent.
2037 update_msg: Option<msgs::ChannelUpdate>,
2039 /// Used to indicate that a channel_update should be broadcast to all peers.
2040 BroadcastChannelUpdate {
2041 /// The channel_update which should be sent.
2042 msg: msgs::ChannelUpdate,
2044 /// Used to indicate that a node_announcement should be broadcast to all peers.
2045 BroadcastNodeAnnouncement {
2046 /// The node_announcement which should be sent.
2047 msg: msgs::NodeAnnouncement,
2049 /// Used to indicate that a channel_update should be sent to a single peer.
2050 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
2051 /// private channel and we shouldn't be informing all of our peers of channel parameters.
2053 /// The node_id of the node which should receive this message
2055 /// The channel_update which should be sent.
2056 msg: msgs::ChannelUpdate,
2058 /// Broadcast an error downstream to be handled
2060 /// The node_id of the node which should receive this message
2062 /// The action which should be taken.
2063 action: msgs::ErrorAction
2065 /// Query a peer for channels with funding transaction UTXOs in a block range.
2066 SendChannelRangeQuery {
2067 /// The node_id of this message recipient
2069 /// The query_channel_range which should be sent.
2070 msg: msgs::QueryChannelRange,
2072 /// Request routing gossip messages from a peer for a list of channels identified by
2073 /// their short_channel_ids.
2075 /// The node_id of this message recipient
2077 /// The query_short_channel_ids which should be sent.
2078 msg: msgs::QueryShortChannelIds,
2080 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
2081 /// emitted during processing of the query.
2082 SendReplyChannelRange {
2083 /// The node_id of this message recipient
2085 /// The reply_channel_range which should be sent.
2086 msg: msgs::ReplyChannelRange,
2088 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
2089 /// enable receiving gossip messages from the peer.
2090 SendGossipTimestampFilter {
2091 /// The node_id of this message recipient
2093 /// The gossip_timestamp_filter which should be sent.
2094 msg: msgs::GossipTimestampFilter,
2098 /// A trait indicating an object may generate message send events
2099 pub trait MessageSendEventsProvider {
2100 /// Gets the list of pending events which were generated by previous actions, clearing the list
2102 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
2105 /// A trait indicating an object may generate events.
2107 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
2109 /// Implementations of this trait may also feature an async version of event handling, as shown with
2110 /// [`ChannelManager::process_pending_events_async`] and
2111 /// [`ChainMonitor::process_pending_events_async`].
2115 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
2116 /// event since the last invocation.
2118 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
2119 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
2120 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
2121 /// relevant changes to disk *before* returning.
2123 /// Further, because an application may crash between an [`Event`] being handled and the
2124 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
2125 /// effect, [`Event`]s may be replayed.
2127 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
2128 /// consult the provider's documentation on the implication of processing events and how a handler
2129 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
2130 /// [`ChainMonitor::process_pending_events`]).
2132 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
2135 /// [`process_pending_events`]: Self::process_pending_events
2136 /// [`handle_event`]: EventHandler::handle_event
2137 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
2138 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
2139 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
2140 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
2141 pub trait EventsProvider {
2142 /// Processes any events generated since the last call using the given event handler.
2144 /// See the trait-level documentation for requirements.
2145 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
2148 /// A trait implemented for objects handling events from [`EventsProvider`].
2150 /// An async variation also exists for implementations of [`EventsProvider`] that support async
2151 /// event handling. The async event handler should satisfy the generic bounds: `F:
2152 /// core::future::Future, H: Fn(Event) -> F`.
2153 pub trait EventHandler {
2154 /// Handles the given [`Event`].
2156 /// See [`EventsProvider`] for details that must be considered when implementing this method.
2157 fn handle_event(&self, event: Event);
2160 impl<F> EventHandler for F where F: Fn(Event) {
2161 fn handle_event(&self, event: Event) {
2166 impl<T: EventHandler> EventHandler for Arc<T> {
2167 fn handle_event(&self, event: Event) {
2168 self.deref().handle_event(event)