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::types::{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;
41 use bitcoin::transaction::Version;
43 use core::time::Duration;
47 #[allow(unused_imports)]
48 use crate::prelude::*;
50 /// Some information provided on receipt of payment depends on whether the payment received is a
51 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
52 #[derive(Clone, Debug, PartialEq, Eq)]
53 pub enum PaymentPurpose {
54 /// A payment for a BOLT 11 invoice.
55 Bolt11InvoicePayment {
56 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
57 /// [`ChannelManager::create_inbound_payment`]. When handling [`Event::PaymentClaimable`],
58 /// this can be passed directly to [`ChannelManager::claim_funds`] to claim the payment. No
59 /// action is needed when seen in [`Event::PaymentClaimed`].
61 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
62 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
63 payment_preimage: Option<PaymentPreimage>,
64 /// The "payment secret". This authenticates the sender to the recipient, preventing a
65 /// number of deanonymization attacks during the routing process.
66 /// It is provided here for your reference, however its accuracy is enforced directly by
67 /// [`ChannelManager`] using the values you previously provided to
68 /// [`ChannelManager::create_inbound_payment`] or
69 /// [`ChannelManager::create_inbound_payment_for_hash`].
71 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
72 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
73 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
74 payment_secret: PaymentSecret,
76 /// A payment for a BOLT 12 [`Offer`].
78 /// [`Offer`]: crate::offers::offer::Offer
80 /// The preimage to the payment hash. When handling [`Event::PaymentClaimable`], this can be
81 /// passed directly to [`ChannelManager::claim_funds`], if provided. No action is needed
82 /// when seen in [`Event::PaymentClaimed`].
84 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
85 payment_preimage: Option<PaymentPreimage>,
86 /// The secret used to authenticate the sender to the recipient, preventing a number of
87 /// de-anonymization attacks while routing a payment.
89 /// See [`PaymentPurpose::Bolt11InvoicePayment::payment_secret`] for further details.
90 payment_secret: PaymentSecret,
91 /// The context of the payment such as information about the corresponding [`Offer`] and
92 /// [`InvoiceRequest`].
94 /// [`Offer`]: crate::offers::offer::Offer
95 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
96 payment_context: Bolt12OfferContext,
98 /// A payment for a BOLT 12 [`Refund`].
100 /// [`Refund`]: crate::offers::refund::Refund
101 Bolt12RefundPayment {
102 /// The preimage to the payment hash. When handling [`Event::PaymentClaimable`], this can be
103 /// passed directly to [`ChannelManager::claim_funds`], if provided. No action is needed
104 /// when seen in [`Event::PaymentClaimed`].
106 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
107 payment_preimage: Option<PaymentPreimage>,
108 /// The secret used to authenticate the sender to the recipient, preventing a number of
109 /// de-anonymization attacks while routing a payment.
111 /// See [`PaymentPurpose::Bolt11InvoicePayment::payment_secret`] for further details.
112 payment_secret: PaymentSecret,
113 /// The context of the payment such as information about the corresponding [`Refund`].
115 /// [`Refund`]: crate::offers::refund::Refund
116 payment_context: Bolt12RefundContext,
118 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
119 /// (the payee) providing a preimage.
120 SpontaneousPayment(PaymentPreimage),
123 impl PaymentPurpose {
124 /// Returns the preimage for this payment, if it is known.
125 pub fn preimage(&self) -> Option<PaymentPreimage> {
127 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, .. } => *payment_preimage,
128 PaymentPurpose::Bolt12OfferPayment { payment_preimage, .. } => *payment_preimage,
129 PaymentPurpose::Bolt12RefundPayment { payment_preimage, .. } => *payment_preimage,
130 PaymentPurpose::SpontaneousPayment(preimage) => Some(*preimage),
134 pub(crate) fn is_keysend(&self) -> bool {
136 PaymentPurpose::Bolt11InvoicePayment { .. } => false,
137 PaymentPurpose::Bolt12OfferPayment { .. } => false,
138 PaymentPurpose::Bolt12RefundPayment { .. } => false,
139 PaymentPurpose::SpontaneousPayment(..) => true,
143 pub(crate) fn from_parts(
144 payment_preimage: Option<PaymentPreimage>, payment_secret: PaymentSecret,
145 payment_context: Option<PaymentContext>,
147 match payment_context {
148 Some(PaymentContext::Unknown(_)) | None => {
149 PaymentPurpose::Bolt11InvoicePayment {
154 Some(PaymentContext::Bolt12Offer(context)) => {
155 PaymentPurpose::Bolt12OfferPayment {
158 payment_context: context,
161 Some(PaymentContext::Bolt12Refund(context)) => {
162 PaymentPurpose::Bolt12RefundPayment {
165 payment_context: context,
172 impl_writeable_tlv_based_enum!(PaymentPurpose,
173 (0, Bolt11InvoicePayment) => {
174 (0, payment_preimage, option),
175 (2, payment_secret, required),
177 (4, Bolt12OfferPayment) => {
178 (0, payment_preimage, option),
179 (2, payment_secret, required),
180 (4, payment_context, required),
182 (6, Bolt12RefundPayment) => {
183 (0, payment_preimage, option),
184 (2, payment_secret, required),
185 (4, payment_context, required),
188 (2, SpontaneousPayment)
191 /// Information about an HTLC that is part of a payment that can be claimed.
192 #[derive(Clone, Debug, PartialEq, Eq)]
193 pub struct ClaimedHTLC {
194 /// The `channel_id` of the channel over which the HTLC was received.
195 pub channel_id: ChannelId,
196 /// The `user_channel_id` of the channel over which the HTLC was received. This is the value
197 /// passed in to [`ChannelManager::create_channel`] for outbound channels, or to
198 /// [`ChannelManager::accept_inbound_channel`] for inbound channels if
199 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
200 /// `user_channel_id` will be randomized for an inbound channel.
202 /// This field will be zero for a payment that was serialized prior to LDK version 0.0.117. (This
203 /// should only happen in the case that a payment was claimable prior to LDK version 0.0.117, but
204 /// was not actually claimed until after upgrading.)
206 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
207 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
208 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
209 pub user_channel_id: u128,
210 /// The block height at which this HTLC expires.
211 pub cltv_expiry: u32,
212 /// The amount (in msats) of this part of an MPP.
214 /// The extra fee our counterparty skimmed off the top of this HTLC, if any.
216 /// This value will always be 0 for [`ClaimedHTLC`]s serialized with LDK versions prior to
218 pub counterparty_skimmed_fee_msat: u64,
220 impl_writeable_tlv_based!(ClaimedHTLC, {
221 (0, channel_id, required),
222 (1, counterparty_skimmed_fee_msat, (default_value, 0u64)),
223 (2, user_channel_id, required),
224 (4, cltv_expiry, required),
225 (6, value_msat, required),
228 /// When the payment path failure took place and extra details about it. [`PathFailure::OnPath`] may
229 /// contain a [`NetworkUpdate`] that needs to be applied to the [`NetworkGraph`].
231 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
232 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
233 #[derive(Clone, Debug, Eq, PartialEq)]
234 pub enum PathFailure {
235 /// We failed to initially send the payment and no HTLC was committed to. Contains the relevant
238 /// The error surfaced from initial send.
241 /// A hop on the path failed to forward our payment.
243 /// If present, this [`NetworkUpdate`] should be applied to the [`NetworkGraph`] so that routing
244 /// decisions can take into account the update.
246 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
247 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
248 network_update: Option<NetworkUpdate>,
252 impl_writeable_tlv_based_enum_upgradable!(PathFailure,
254 (0, network_update, upgradable_option),
256 (2, InitialSend) => {
257 (0, err, upgradable_required),
261 #[derive(Clone, Debug, PartialEq, Eq)]
262 /// The reason the channel was closed. See individual variants for more details.
263 pub enum ClosureReason {
264 /// Closure generated from receiving a peer error message.
266 /// Our counterparty may have broadcasted their latest commitment state, and we have
268 CounterpartyForceClosed {
269 /// The error which the peer sent us.
271 /// Be careful about printing the peer_msg, a well-crafted message could exploit
272 /// a security vulnerability in the terminal emulator or the logging subsystem.
273 /// To be safe, use `Display` on `UntrustedString`
275 /// [`UntrustedString`]: crate::util::string::UntrustedString
276 peer_msg: UntrustedString,
278 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
280 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
282 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
283 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
285 /// This was only set in versions of LDK prior to 0.0.122.
286 // Can be removed once we disallow downgrading to 0.0.121
287 LegacyCooperativeClosure,
288 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
289 /// the cooperative close transaction. This indicates that the shutdown was initiated by our
292 /// In rare cases where we initiated closure immediately prior to shutting down without
293 /// persisting, this value may be provided for channels we initiated closure for.
294 CounterpartyInitiatedCooperativeClosure,
295 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
296 /// the cooperative close transaction. This indicates that the shutdown was initiated by us.
297 LocallyInitiatedCooperativeClosure,
298 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
299 /// commitment transaction came from our counterparty, but it may also have come from
300 /// a copy of our own `ChannelMonitor`.
301 CommitmentTxConfirmed,
302 /// The funding transaction failed to confirm in a timely manner on an inbound channel.
304 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
306 /// A developer-readable error message which we generated.
309 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
310 /// forget the channel entirely - we can attempt again if the peer reconnects.
312 /// This includes cases where we restarted prior to funding completion, including prior to the
313 /// initial [`ChannelMonitor`] persistence completing.
315 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
316 /// peer because of mutual incompatibility between us and our channel counterparty.
318 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
320 /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
321 /// the [`ChannelManager`] deserialized.
323 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
324 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
325 OutdatedChannelManager,
326 /// The counterparty requested a cooperative close of a channel that had not been funded yet.
327 /// The channel has been immediately closed.
328 CounterpartyCoopClosedUnfundedChannel,
329 /// Another channel in the same funding batch closed before the funding transaction
330 /// was ready to be broadcast.
332 /// One of our HTLCs timed out in a channel, causing us to force close the channel.
336 impl core::fmt::Display for ClosureReason {
337 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
338 f.write_str("Channel closed because ")?;
340 ClosureReason::CounterpartyForceClosed { peer_msg } => {
341 f.write_fmt(format_args!("counterparty force-closed with message: {}", peer_msg))
343 ClosureReason::HolderForceClosed => f.write_str("user force-closed the channel"),
344 ClosureReason::LegacyCooperativeClosure => f.write_str("the channel was cooperatively closed"),
345 ClosureReason::CounterpartyInitiatedCooperativeClosure => f.write_str("the channel was cooperatively closed by our peer"),
346 ClosureReason::LocallyInitiatedCooperativeClosure => f.write_str("the channel was cooperatively closed by us"),
347 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
348 ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
349 ClosureReason::ProcessingError { err } => {
350 f.write_str("of an exception: ")?;
353 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
354 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
355 ClosureReason::CounterpartyCoopClosedUnfundedChannel => f.write_str("the peer requested the unfunded channel be closed"),
356 ClosureReason::FundingBatchClosure => f.write_str("another channel in the same funding batch closed"),
357 ClosureReason::HTLCsTimedOut => f.write_str("htlcs on the channel timed out"),
362 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
363 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
364 (1, FundingTimedOut) => {},
365 (2, HolderForceClosed) => {},
366 (6, CommitmentTxConfirmed) => {},
367 (4, LegacyCooperativeClosure) => {},
368 (8, ProcessingError) => { (1, err, required) },
369 (10, DisconnectedPeer) => {},
370 (12, OutdatedChannelManager) => {},
371 (13, CounterpartyCoopClosedUnfundedChannel) => {},
372 (15, FundingBatchClosure) => {},
373 (17, CounterpartyInitiatedCooperativeClosure) => {},
374 (19, LocallyInitiatedCooperativeClosure) => {},
375 (21, HTLCsTimedOut) => {},
378 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
379 #[derive(Clone, Debug, PartialEq, Eq)]
380 pub enum HTLCDestination {
381 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
382 /// there is insufficient capacity in our outbound channel.
384 /// The `node_id` of the next node. For backwards compatibility, this field is
385 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
386 /// counterparty node information.
387 node_id: Option<PublicKey>,
388 /// The outgoing `channel_id` between us and the next node.
389 channel_id: ChannelId,
391 /// Scenario where we are unsure of the next node to forward the HTLC to.
393 /// Short channel id we are requesting to forward an HTLC to.
394 requested_forward_scid: u64,
396 /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
399 /// Short channel id we are requesting to forward an HTLC to.
400 requested_forward_scid: u64
402 /// We couldn't decode the incoming onion to obtain the forwarding details.
404 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
405 /// but is invalid for some reason, so we reject it.
407 /// Some of the reasons may include:
409 /// * Excess HTLCs for a payment that we have already fully received, over-paying for the
411 /// * The counterparty node modified the HTLC in transit,
412 /// * A probing attack where an intermediary node is trying to detect if we are the ultimate
413 /// recipient for a payment.
415 /// The payment hash of the payment we attempted to process.
416 payment_hash: PaymentHash
420 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
421 (0, NextHopChannel) => {
422 (0, node_id, required),
423 (2, channel_id, required),
425 (1, InvalidForward) => {
426 (0, requested_forward_scid, required),
428 (2, UnknownNextHop) => {
429 (0, requested_forward_scid, required),
431 (3, InvalidOnion) => {},
432 (4, FailedPayment) => {
433 (0, payment_hash, required),
437 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
438 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
439 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
440 /// intercepts in upcoming work.
441 enum InterceptNextHop {
443 requested_next_hop_scid: u64,
447 impl_writeable_tlv_based_enum!(InterceptNextHop,
449 (0, requested_next_hop_scid, required),
453 /// The reason the payment failed. Used in [`Event::PaymentFailed`].
454 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
455 pub enum PaymentFailureReason {
456 /// The intended recipient rejected our payment.
458 /// The user chose to abandon this payment by calling [`ChannelManager::abandon_payment`].
460 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
462 /// We exhausted all of our retry attempts while trying to send the payment, or we
463 /// exhausted the [`Retry::Timeout`] if the user set one. If at any point a retry
464 /// attempt failed while being forwarded along the path, an [`Event::PaymentPathFailed`] will
465 /// have come before this.
467 /// [`Retry::Timeout`]: crate::ln::channelmanager::Retry::Timeout
469 /// The payment expired while retrying, based on the provided
470 /// [`PaymentParameters::expiry_time`].
472 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
474 /// We failed to find a route while retrying the payment.
476 /// Note that this generally indicates that we've exhausted the available set of possible
477 /// routes - we tried the payment over a few routes but were not able to find any further
478 /// candidate routes beyond those.
480 /// This error should generally never happen. This likely means that there is a problem with
485 impl_writeable_tlv_based_enum!(PaymentFailureReason,
486 (0, RecipientRejected) => {},
487 (2, UserAbandoned) => {},
488 (4, RetriesExhausted) => {},
489 (6, PaymentExpired) => {},
490 (8, RouteNotFound) => {},
491 (10, UnexpectedError) => {}, ;
494 /// An Event which you should probably take some action in response to.
496 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
497 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
498 /// written as it makes no sense to respond to it after reconnecting to peers).
499 #[derive(Clone, Debug, PartialEq, Eq)]
501 /// Used to indicate that the client should generate a funding transaction with the given
502 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
503 /// Generated in [`ChannelManager`] message handling.
504 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
505 /// counterparty can steal your funds!
507 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
508 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
509 FundingGenerationReady {
510 /// The random channel_id we picked which you'll need to pass into
511 /// [`ChannelManager::funding_transaction_generated`].
513 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
514 temporary_channel_id: ChannelId,
515 /// The counterparty's node_id, which you'll need to pass back into
516 /// [`ChannelManager::funding_transaction_generated`].
518 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
519 counterparty_node_id: PublicKey,
520 /// The value, in satoshis, that the output should have.
521 channel_value_satoshis: u64,
522 /// The script which should be used in the transaction output.
523 output_script: ScriptBuf,
524 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
525 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
526 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
527 /// `user_channel_id` will be randomized for an inbound channel. This may be zero for objects
528 /// serialized with LDK versions prior to 0.0.113.
530 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
531 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
532 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
533 user_channel_id: u128,
535 /// Indicates that we've been offered a payment and it needs to be claimed via calling
536 /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
538 /// Note that if the preimage is not known, you should call
539 /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
540 /// to free up resources for this HTLC and avoid network congestion.
542 /// If [`Event::PaymentClaimable::onion_fields`] is `Some`, and includes custom TLVs with even type
543 /// numbers, you should use [`ChannelManager::fail_htlc_backwards_with_reason`] with
544 /// [`FailureCode::InvalidOnionPayload`] if you fail to understand and handle the contents, or
545 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`] upon successful handling.
546 /// If you don't intend to check for custom TLVs, you can simply use
547 /// [`ChannelManager::claim_funds`], which will automatically fail back even custom TLVs.
549 /// If you fail to call [`ChannelManager::claim_funds`],
550 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`],
551 /// [`ChannelManager::fail_htlc_backwards`], or
552 /// [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will
553 /// be automatically failed.
556 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
557 /// `PaymentClaimable` events may be generated for the same payment. In such a case it is
558 /// polite (and required in the lightning specification) to fail the payment the second time
559 /// and give the sender their money back rather than accepting double payment.
562 /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
564 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
565 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`]: crate::ln::channelmanager::ChannelManager::claim_funds_with_known_custom_tlvs
566 /// [`FailureCode::InvalidOnionPayload`]: crate::ln::channelmanager::FailureCode::InvalidOnionPayload
567 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
568 /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
570 /// The node that will receive the payment after it has been claimed.
571 /// This is useful to identify payments received via [phantom nodes].
572 /// This field will always be filled in when the event was generated by LDK versions
573 /// 0.0.113 and above.
575 /// [phantom nodes]: crate::sign::PhantomKeysManager
576 receiver_node_id: Option<PublicKey>,
577 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
578 /// not stop you from registering duplicate payment hashes for inbound payments.
579 payment_hash: PaymentHash,
580 /// The fields in the onion which were received with each HTLC. Only fields which were
581 /// identical in each HTLC involved in the payment will be included here.
583 /// Payments received on LDK versions prior to 0.0.115 will have this field unset.
584 onion_fields: Option<RecipientOnionFields>,
585 /// The value, in thousandths of a satoshi, that this payment is claimable for. May be greater
586 /// than the invoice amount.
588 /// May be less than the invoice amount if [`ChannelConfig::accept_underpaying_htlcs`] is set
589 /// and the previous hop took an extra fee.
592 /// If [`ChannelConfig::accept_underpaying_htlcs`] is set and you claim without verifying this
593 /// field, you may lose money!
595 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
597 /// The value, in thousands of a satoshi, that was skimmed off of this payment as an extra fee
598 /// taken by our channel counterparty.
600 /// Will always be 0 unless [`ChannelConfig::accept_underpaying_htlcs`] is set.
602 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
603 counterparty_skimmed_fee_msat: u64,
604 /// Information for claiming this received payment, based on whether the purpose of the
605 /// payment is to pay an invoice or to send a spontaneous payment.
606 purpose: PaymentPurpose,
607 /// The `channel_id` indicating over which channel we received the payment.
608 via_channel_id: Option<ChannelId>,
609 /// The `user_channel_id` indicating over which channel we received the payment.
610 via_user_channel_id: Option<u128>,
611 /// The block height at which this payment will be failed back and will no longer be
612 /// eligible for claiming.
614 /// Prior to this height, a call to [`ChannelManager::claim_funds`] is guaranteed to
615 /// succeed, however you should wait for [`Event::PaymentClaimed`] to be sure.
617 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
618 claim_deadline: Option<u32>,
620 /// Indicates a payment has been claimed and we've received money!
622 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
623 /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
624 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
625 /// [`Event::PaymentClaimable`] event.
628 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
629 /// `PaymentClaimable` events may be generated for the same payment. If you then call
630 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
631 /// multiple `PaymentClaimed` events.
633 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
635 /// The node that received the payment.
636 /// This is useful to identify payments which were received via [phantom nodes].
637 /// This field will always be filled in when the event was generated by LDK versions
638 /// 0.0.113 and above.
640 /// [phantom nodes]: crate::sign::PhantomKeysManager
641 receiver_node_id: Option<PublicKey>,
642 /// The payment hash of the claimed payment. Note that LDK will not stop you from
643 /// registering duplicate payment hashes for inbound payments.
644 payment_hash: PaymentHash,
645 /// The value, in thousandths of a satoshi, that this payment is for. May be greater than the
648 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
649 /// spontaneous payment.
650 purpose: PaymentPurpose,
651 /// The HTLCs that comprise the claimed payment. This will be empty for events serialized prior
652 /// to LDK version 0.0.117.
653 htlcs: Vec<ClaimedHTLC>,
654 /// The sender-intended sum total of all the MPP parts. This will be `None` for events
655 /// serialized prior to LDK version 0.0.117.
656 sender_intended_total_msat: Option<u64>,
658 /// Indicates that a peer connection with a node is needed in order to send an [`OnionMessage`].
660 /// Typically, this happens when a [`MessageRouter`] is unable to find a complete path to a
661 /// [`Destination`]. Once a connection is established, any messages buffered by an
662 /// [`OnionMessageHandler`] may be sent.
664 /// This event will not be generated for onion message forwards; only for sends including
665 /// replies. Handlers should connect to the node otherwise any buffered messages may be lost.
667 /// [`OnionMessage`]: msgs::OnionMessage
668 /// [`MessageRouter`]: crate::onion_message::messenger::MessageRouter
669 /// [`Destination`]: crate::onion_message::messenger::Destination
670 /// [`OnionMessageHandler`]: crate::ln::msgs::OnionMessageHandler
672 /// The node id for the node needing a connection.
674 /// Sockets for connecting to the node.
675 addresses: Vec<msgs::SocketAddress>,
677 /// Indicates a request for an invoice failed to yield a response in a reasonable amount of time
678 /// or was explicitly abandoned by [`ChannelManager::abandon_payment`]. This may be for an
679 /// [`InvoiceRequest`] sent for an [`Offer`] or for a [`Refund`] that hasn't been redeemed.
681 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
682 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
683 /// [`Offer`]: crate::offers::offer::Offer
684 /// [`Refund`]: crate::offers::refund::Refund
685 InvoiceRequestFailed {
686 /// The `payment_id` to have been associated with payment for the requested invoice.
687 payment_id: PaymentId,
689 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
690 /// and we got back the payment preimage for it).
692 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
693 /// event. In this situation, you SHOULD treat this payment as having succeeded.
695 /// The `payment_id` passed to [`ChannelManager::send_payment`].
697 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
698 payment_id: Option<PaymentId>,
699 /// The preimage to the hash given to ChannelManager::send_payment.
700 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
701 /// store it somehow!
702 payment_preimage: PaymentPreimage,
703 /// The hash that was given to [`ChannelManager::send_payment`].
705 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
706 payment_hash: PaymentHash,
707 /// The total fee which was spent at intermediate hops in this payment, across all paths.
709 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
710 /// overpayment to the recipient node.
712 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
713 /// overstate the amount paid, though this is unlikely.
715 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
716 fee_paid_msat: Option<u64>,
718 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
719 /// provide failure information for each path attempt in the payment, including retries.
721 /// This event is provided once there are no further pending HTLCs for the payment and the
722 /// payment is no longer retryable, due either to the [`Retry`] provided or
723 /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
725 /// In exceedingly rare cases, it is possible that an [`Event::PaymentFailed`] is generated for
726 /// a payment after an [`Event::PaymentSent`] event for this same payment has already been
727 /// received and processed. In this case, the [`Event::PaymentFailed`] event MUST be ignored,
728 /// and the payment MUST be treated as having succeeded.
730 /// [`Retry`]: crate::ln::channelmanager::Retry
731 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
733 /// The `payment_id` passed to [`ChannelManager::send_payment`].
735 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
736 payment_id: PaymentId,
737 /// The hash that was given to [`ChannelManager::send_payment`].
739 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
740 payment_hash: PaymentHash,
741 /// The reason the payment failed. This is only `None` for events generated or serialized
742 /// by versions prior to 0.0.115.
743 reason: Option<PaymentFailureReason>,
745 /// Indicates that a path for an outbound payment was successful.
747 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
748 /// [`Event::PaymentSent`] for obtaining the payment preimage.
749 PaymentPathSuccessful {
750 /// The `payment_id` passed to [`ChannelManager::send_payment`].
752 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
753 payment_id: PaymentId,
754 /// The hash that was given to [`ChannelManager::send_payment`].
756 /// This will be `Some` for all payments which completed on LDK 0.0.104 or later.
758 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
759 payment_hash: Option<PaymentHash>,
760 /// The payment path that was successful.
762 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
765 /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
768 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
769 /// [`Event::PaymentFailed`].
771 /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
774 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
776 /// The `payment_id` passed to [`ChannelManager::send_payment`].
778 /// This will be `Some` for all payment paths which failed on LDK 0.0.103 or later.
780 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
781 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
782 payment_id: Option<PaymentId>,
783 /// The hash that was given to [`ChannelManager::send_payment`].
785 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
786 payment_hash: PaymentHash,
787 /// Indicates the payment was rejected for some reason by the recipient. This implies that
788 /// the payment has failed, not just the route in question. If this is not set, the payment may
789 /// be retried via a different route.
790 payment_failed_permanently: bool,
791 /// Extra error details based on the failure type. May contain an update that needs to be
792 /// applied to the [`NetworkGraph`].
794 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
795 failure: PathFailure,
796 /// The payment path that failed.
798 /// The channel responsible for the failed payment path.
800 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
801 /// may not refer to a channel in the public network graph. These aliases may also collide
802 /// with channels in the public network graph.
804 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
805 /// retried. May be `None` for older [`Event`] serializations.
806 short_channel_id: Option<u64>,
808 error_code: Option<u16>,
810 error_data: Option<Vec<u8>>,
812 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
814 /// The id returned by [`ChannelManager::send_probe`].
816 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
817 payment_id: PaymentId,
818 /// The hash generated by [`ChannelManager::send_probe`].
820 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
821 payment_hash: PaymentHash,
822 /// The payment path that was successful.
825 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
827 /// The id returned by [`ChannelManager::send_probe`].
829 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
830 payment_id: PaymentId,
831 /// The hash generated by [`ChannelManager::send_probe`].
833 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
834 payment_hash: PaymentHash,
835 /// The payment path that failed.
837 /// The channel responsible for the failed probe.
839 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
840 /// may not refer to a channel in the public network graph. These aliases may also collide
841 /// with channels in the public network graph.
842 short_channel_id: Option<u64>,
844 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
845 /// a time in the future.
847 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
848 PendingHTLCsForwardable {
849 /// The minimum amount of time that should be waited prior to calling
850 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
851 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
852 /// now + 5*time_forwardable).
853 time_forwardable: Duration,
855 /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
856 /// you've encoded an intercept scid in the receiver's invoice route hints using
857 /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
859 /// [`ChannelManager::forward_intercepted_htlc`] or
860 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
861 /// their docs for more information.
863 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
864 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
865 /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
866 /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
868 /// An id to help LDK identify which HTLC is being forwarded or failed.
869 intercept_id: InterceptId,
870 /// The fake scid that was programmed as the next hop's scid, generated using
871 /// [`ChannelManager::get_intercept_scid`].
873 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
874 requested_next_hop_scid: u64,
875 /// The payment hash used for this HTLC.
876 payment_hash: PaymentHash,
877 /// How many msats were received on the inbound edge of this HTLC.
878 inbound_amount_msat: u64,
879 /// How many msats the payer intended to route to the next node. Depending on the reason you are
880 /// intercepting this payment, you might take a fee by forwarding less than this amount.
881 /// Forwarding less than this amount may break compatibility with LDK versions prior to 0.0.116.
883 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
884 /// check that whatever fee you want has been included here or subtract it as required. Further,
885 /// LDK will not stop you from forwarding more than you received.
886 expected_outbound_amount_msat: u64,
888 /// Used to indicate that an output which you should know how to spend was confirmed on chain
889 /// and is now spendable.
891 /// Such an output will *never* be spent directly by LDK, and are not at risk of your
892 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
893 /// somewhere and spend them when you create on-chain transactions.
895 /// You may hand them to the [`OutputSweeper`] utility which will store and (re-)generate spending
896 /// transactions for you.
898 /// [`OutputSweeper`]: crate::util::sweep::OutputSweeper
900 /// The outputs which you should store as spendable by you.
901 outputs: Vec<SpendableOutputDescriptor>,
902 /// The `channel_id` indicating which channel the spendable outputs belong to.
904 /// This will always be `Some` for events generated by LDK versions 0.0.117 and above.
905 channel_id: Option<ChannelId>,
907 /// This event is generated when a payment has been successfully forwarded through us and a
908 /// forwarding fee earned.
910 /// The channel id of the incoming channel between the previous node and us.
912 /// This is only `None` for events generated or serialized by versions prior to 0.0.107.
913 prev_channel_id: Option<ChannelId>,
914 /// The channel id of the outgoing channel between the next node and us.
916 /// This is only `None` for events generated or serialized by versions prior to 0.0.107.
917 next_channel_id: Option<ChannelId>,
918 /// The `user_channel_id` of the incoming channel between the previous node and us.
920 /// This is only `None` for events generated or serialized by versions prior to 0.0.122.
921 prev_user_channel_id: Option<u128>,
922 /// The `user_channel_id` of the outgoing channel between the next node and us.
924 /// This will be `None` if the payment was settled via an on-chain transaction. See the
925 /// caveat described for the `total_fee_earned_msat` field. Moreover it will be `None` for
926 /// events generated or serialized by versions prior to 0.0.122.
927 next_user_channel_id: Option<u128>,
928 /// The total fee, in milli-satoshis, which was earned as a result of the payment.
930 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
931 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
932 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
933 /// claimed the full value in millisatoshis from the source. In this case,
934 /// `claim_from_onchain_tx` will be set.
936 /// If the channel which sent us the payment has been force-closed, we will claim the funds
937 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
938 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
939 /// `PaymentForwarded` events are generated for the same payment iff `total_fee_earned_msat` is
941 total_fee_earned_msat: Option<u64>,
942 /// The share of the total fee, in milli-satoshis, which was withheld in addition to the
945 /// This will only be `Some` if we forwarded an intercepted HTLC with less than the
946 /// expected amount. This means our counterparty accepted to receive less than the invoice
947 /// amount, e.g., by claiming the payment featuring a corresponding
948 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`].
950 /// Will also always be `None` for events serialized with LDK prior to version 0.0.122.
952 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
954 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`]: Self::PaymentClaimable::counterparty_skimmed_fee_msat
955 skimmed_fee_msat: Option<u64>,
956 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
958 claim_from_onchain_tx: bool,
959 /// The final amount forwarded, in milli-satoshis, after the fee is deducted.
961 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
962 outbound_amount_forwarded_msat: Option<u64>,
964 /// Used to indicate that a channel with the given `channel_id` is being opened and pending
965 /// confirmation on-chain.
967 /// This event is emitted when the funding transaction has been signed and is broadcast to the
968 /// network. For 0conf channels it will be immediately followed by the corresponding
969 /// [`Event::ChannelReady`] event.
971 /// The `channel_id` of the channel that is pending confirmation.
972 channel_id: ChannelId,
973 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
974 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
975 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
976 /// `user_channel_id` will be randomized for an inbound channel.
978 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
979 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
980 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
981 user_channel_id: u128,
982 /// The `temporary_channel_id` this channel used to be known by during channel establishment.
984 /// Will be `None` for channels created prior to LDK version 0.0.115.
985 former_temporary_channel_id: Option<ChannelId>,
986 /// The `node_id` of the channel counterparty.
987 counterparty_node_id: PublicKey,
988 /// The outpoint of the channel's funding transaction.
989 funding_txo: OutPoint,
990 /// The features that this channel will operate with.
992 /// Will be `None` for channels created prior to LDK version 0.0.122.
993 channel_type: Option<ChannelTypeFeatures>,
995 /// Used to indicate that a channel with the given `channel_id` is ready to
996 /// be used. This event is emitted either when the funding transaction has been confirmed
997 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
1000 /// The `channel_id` of the channel that is ready.
1001 channel_id: ChannelId,
1002 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1003 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1004 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1005 /// `user_channel_id` will be randomized for an inbound channel.
1007 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1008 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1009 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1010 user_channel_id: u128,
1011 /// The `node_id` of the channel counterparty.
1012 counterparty_node_id: PublicKey,
1013 /// The features that this channel will operate with.
1014 channel_type: ChannelTypeFeatures,
1016 /// Used to indicate that a channel that got past the initial handshake with the given `channel_id` is in the
1017 /// process of closure. This includes previously opened channels, and channels that time out from not being funded.
1019 /// Note that this event is only triggered for accepted channels: if the
1020 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true and the channel is
1021 /// rejected, no `ChannelClosed` event will be sent.
1023 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1024 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1026 /// The `channel_id` of the channel which has been closed. Note that on-chain transactions
1027 /// resolving the channel are likely still awaiting confirmation.
1028 channel_id: ChannelId,
1029 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1030 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1031 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1032 /// `user_channel_id` will be randomized for inbound channels.
1033 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
1034 /// zero for objects serialized with LDK versions prior to 0.0.102.
1036 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1037 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1038 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1039 user_channel_id: u128,
1040 /// The reason the channel was closed.
1041 reason: ClosureReason,
1042 /// Counterparty in the closed channel.
1044 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
1045 counterparty_node_id: Option<PublicKey>,
1046 /// Channel capacity of the closing channel (sats).
1048 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
1049 channel_capacity_sats: Option<u64>,
1050 /// The original channel funding TXO; this helps checking for the existence and confirmation
1051 /// status of the closing tx.
1052 /// Note that for instances serialized in v0.0.119 or prior this will be missing (None).
1053 channel_funding_txo: Option<transaction::OutPoint>,
1055 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
1056 /// inputs for another purpose.
1058 /// This event is not guaranteed to be generated for channels that are closed due to a restart.
1060 /// The channel_id of the channel which has been closed.
1061 channel_id: ChannelId,
1062 /// The full transaction received from the user
1063 transaction: Transaction
1065 /// Indicates a request to open a new channel by a peer.
1067 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the request,
1068 /// call [`ChannelManager::force_close_without_broadcasting_txn`]. Note that a ['ChannelClosed`]
1069 /// event will _not_ be triggered if the channel is rejected.
1071 /// The event is only triggered when a new open channel request is received and the
1072 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
1074 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1075 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1076 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1077 OpenChannelRequest {
1078 /// The temporary channel ID of the channel requested to be opened.
1080 /// When responding to the request, the `temporary_channel_id` should be passed
1081 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
1082 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
1084 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1085 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1086 temporary_channel_id: ChannelId,
1087 /// The node_id of the counterparty requesting to open the channel.
1089 /// When responding to the request, the `counterparty_node_id` should be passed
1090 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
1091 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
1094 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1095 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1096 counterparty_node_id: PublicKey,
1097 /// The channel value of the requested channel.
1098 funding_satoshis: u64,
1099 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
1101 /// The features that this channel will operate with. If you reject the channel, a
1102 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
1105 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
1106 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1109 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
1110 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1111 /// 0.0.107. Channels setting this type also need to get manually accepted via
1112 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
1113 /// or will be rejected otherwise.
1115 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1116 channel_type: ChannelTypeFeatures,
1118 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
1121 /// Some scenarios where this event may be sent include:
1122 /// * Insufficient capacity in the outbound channel
1123 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
1124 /// * When an unknown SCID is requested for forwarding a payment.
1125 /// * Expected MPP amount has already been reached
1126 /// * The HTLC has timed out
1128 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
1129 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
1130 HTLCHandlingFailed {
1131 /// The channel over which the HTLC was received.
1132 prev_channel_id: ChannelId,
1133 /// Destination of the HTLC that failed to be processed.
1134 failed_next_destination: HTLCDestination,
1136 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
1137 /// requires confirmed external funds to be readily available to spend.
1139 /// LDK does not currently generate this event unless the
1140 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`] config flag is set to true.
1141 /// It is limited to the scope of channels with anchor outputs.
1143 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`]: crate::util::config::ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx
1144 BumpTransaction(BumpTransactionEvent),
1145 /// We received an onion message that is intended to be forwarded to a peer
1146 /// that is currently offline. This event will only be generated if the
1147 /// `OnionMessenger` was initialized with
1148 /// [`OnionMessenger::new_with_offline_peer_interception`], see its docs.
1150 /// [`OnionMessenger::new_with_offline_peer_interception`]: crate::onion_message::messenger::OnionMessenger::new_with_offline_peer_interception
1151 OnionMessageIntercepted {
1152 /// The node id of the offline peer.
1153 peer_node_id: PublicKey,
1154 /// The onion message intended to be forwarded to `peer_node_id`.
1155 message: msgs::OnionMessage,
1157 /// Indicates that an onion message supporting peer has come online and it may
1158 /// be time to forward any onion messages that were previously intercepted for
1159 /// them. This event will only be generated if the `OnionMessenger` was
1160 /// initialized with
1161 /// [`OnionMessenger::new_with_offline_peer_interception`], see its docs.
1163 /// [`OnionMessenger::new_with_offline_peer_interception`]: crate::onion_message::messenger::OnionMessenger::new_with_offline_peer_interception
1164 OnionMessagePeerConnected {
1165 /// The node id of the peer we just connected to, who advertises support for
1167 peer_node_id: PublicKey,
1171 impl Writeable for Event {
1172 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1174 &Event::FundingGenerationReady { .. } => {
1176 // We never write out FundingGenerationReady events as, upon disconnection, peers
1177 // drop any channels which have not yet exchanged funding_signed.
1179 &Event::PaymentClaimable { ref payment_hash, ref amount_msat, counterparty_skimmed_fee_msat,
1180 ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id,
1181 ref claim_deadline, ref onion_fields
1184 let mut payment_secret = None;
1185 let payment_preimage;
1186 let mut payment_context = None;
1188 PaymentPurpose::Bolt11InvoicePayment {
1189 payment_preimage: preimage, payment_secret: secret
1191 payment_secret = Some(secret);
1192 payment_preimage = *preimage;
1194 PaymentPurpose::Bolt12OfferPayment {
1195 payment_preimage: preimage, payment_secret: secret, payment_context: context
1197 payment_secret = Some(secret);
1198 payment_preimage = *preimage;
1199 payment_context = Some(PaymentContextRef::Bolt12Offer(context));
1201 PaymentPurpose::Bolt12RefundPayment {
1202 payment_preimage: preimage, payment_secret: secret, payment_context: context
1204 payment_secret = Some(secret);
1205 payment_preimage = *preimage;
1206 payment_context = Some(PaymentContextRef::Bolt12Refund(context));
1208 PaymentPurpose::SpontaneousPayment(preimage) => {
1209 payment_preimage = Some(*preimage);
1212 let skimmed_fee_opt = if counterparty_skimmed_fee_msat == 0 { None }
1213 else { Some(counterparty_skimmed_fee_msat) };
1214 write_tlv_fields!(writer, {
1215 (0, payment_hash, required),
1216 (1, receiver_node_id, option),
1217 (2, payment_secret, option),
1218 (3, via_channel_id, option),
1219 (4, amount_msat, required),
1220 (5, via_user_channel_id, option),
1221 // Type 6 was `user_payment_id` on 0.0.103 and earlier
1222 (7, claim_deadline, option),
1223 (8, payment_preimage, option),
1224 (9, onion_fields, option),
1225 (10, skimmed_fee_opt, option),
1226 (11, payment_context, option),
1229 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
1231 write_tlv_fields!(writer, {
1232 (0, payment_preimage, required),
1233 (1, payment_hash, required),
1234 (3, payment_id, option),
1235 (5, fee_paid_msat, option),
1238 &Event::PaymentPathFailed {
1239 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
1240 ref path, ref short_channel_id,
1248 error_code.write(writer)?;
1250 error_data.write(writer)?;
1251 write_tlv_fields!(writer, {
1252 (0, payment_hash, required),
1253 (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
1254 (2, payment_failed_permanently, required),
1255 (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
1256 (4, path.blinded_tail, option),
1257 (5, path.hops, required_vec),
1258 (7, short_channel_id, option),
1259 (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
1260 (11, payment_id, option),
1261 (13, failure, required),
1264 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
1266 // Note that we now ignore these on the read end as we'll re-generate them in
1267 // ChannelManager, we write them here only for backwards compatibility.
1269 &Event::SpendableOutputs { ref outputs, channel_id } => {
1271 write_tlv_fields!(writer, {
1272 (0, WithoutLength(outputs), required),
1273 (1, channel_id, option),
1276 &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1278 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1279 write_tlv_fields!(writer, {
1280 (0, intercept_id, required),
1281 (2, intercept_scid, required),
1282 (4, payment_hash, required),
1283 (6, inbound_amount_msat, required),
1284 (8, expected_outbound_amount_msat, required),
1287 &Event::PaymentForwarded {
1288 prev_channel_id, next_channel_id, prev_user_channel_id, next_user_channel_id,
1289 total_fee_earned_msat, skimmed_fee_msat, claim_from_onchain_tx,
1290 outbound_amount_forwarded_msat,
1293 write_tlv_fields!(writer, {
1294 (0, total_fee_earned_msat, option),
1295 (1, prev_channel_id, option),
1296 (2, claim_from_onchain_tx, required),
1297 (3, next_channel_id, option),
1298 (5, outbound_amount_forwarded_msat, option),
1299 (7, skimmed_fee_msat, option),
1300 (9, prev_user_channel_id, option),
1301 (11, next_user_channel_id, option),
1304 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason,
1305 ref counterparty_node_id, ref channel_capacity_sats, ref channel_funding_txo
1308 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1309 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1310 // separate u64 values.
1311 let user_channel_id_low = *user_channel_id as u64;
1312 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1313 write_tlv_fields!(writer, {
1314 (0, channel_id, required),
1315 (1, user_channel_id_low, required),
1316 (2, reason, required),
1317 (3, user_channel_id_high, required),
1318 (5, counterparty_node_id, option),
1319 (7, channel_capacity_sats, option),
1320 (9, channel_funding_txo, option),
1323 &Event::DiscardFunding { ref channel_id, ref transaction } => {
1324 11u8.write(writer)?;
1325 write_tlv_fields!(writer, {
1326 (0, channel_id, required),
1327 (2, transaction, required)
1330 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1331 13u8.write(writer)?;
1332 write_tlv_fields!(writer, {
1333 (0, payment_id, required),
1334 (2, payment_hash, option),
1335 (4, path.hops, required_vec),
1336 (6, path.blinded_tail, option),
1339 &Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
1340 15u8.write(writer)?;
1341 write_tlv_fields!(writer, {
1342 (0, payment_id, required),
1343 (1, reason, option),
1344 (2, payment_hash, required),
1347 &Event::OpenChannelRequest { .. } => {
1348 17u8.write(writer)?;
1349 // We never write the OpenChannelRequest events as, upon disconnection, peers
1350 // drop any channels which have not yet exchanged funding_signed.
1352 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref htlcs, ref sender_intended_total_msat } => {
1353 19u8.write(writer)?;
1354 write_tlv_fields!(writer, {
1355 (0, payment_hash, required),
1356 (1, receiver_node_id, option),
1357 (2, purpose, required),
1358 (4, amount_msat, required),
1359 (5, *htlcs, optional_vec),
1360 (7, sender_intended_total_msat, option),
1363 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1364 21u8.write(writer)?;
1365 write_tlv_fields!(writer, {
1366 (0, payment_id, required),
1367 (2, payment_hash, required),
1368 (4, path.hops, required_vec),
1369 (6, path.blinded_tail, option),
1372 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1373 23u8.write(writer)?;
1374 write_tlv_fields!(writer, {
1375 (0, payment_id, required),
1376 (2, payment_hash, required),
1377 (4, path.hops, required_vec),
1378 (6, short_channel_id, option),
1379 (8, path.blinded_tail, option),
1382 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1383 25u8.write(writer)?;
1384 write_tlv_fields!(writer, {
1385 (0, prev_channel_id, required),
1386 (2, failed_next_destination, required),
1389 &Event::BumpTransaction(ref event)=> {
1390 27u8.write(writer)?;
1392 // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1393 // upon restarting anyway if they remain unresolved.
1394 BumpTransactionEvent::ChannelClose { .. } => {}
1395 BumpTransactionEvent::HTLCResolution { .. } => {}
1397 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1399 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1400 29u8.write(writer)?;
1401 write_tlv_fields!(writer, {
1402 (0, channel_id, required),
1403 (2, user_channel_id, required),
1404 (4, counterparty_node_id, required),
1405 (6, channel_type, required),
1408 &Event::ChannelPending { ref channel_id, ref user_channel_id,
1409 ref former_temporary_channel_id, ref counterparty_node_id, ref funding_txo,
1412 31u8.write(writer)?;
1413 write_tlv_fields!(writer, {
1414 (0, channel_id, required),
1415 (1, channel_type, option),
1416 (2, user_channel_id, required),
1417 (4, former_temporary_channel_id, required),
1418 (6, counterparty_node_id, required),
1419 (8, funding_txo, required),
1422 &Event::InvoiceRequestFailed { ref payment_id } => {
1423 33u8.write(writer)?;
1424 write_tlv_fields!(writer, {
1425 (0, payment_id, required),
1428 &Event::ConnectionNeeded { .. } => {
1429 35u8.write(writer)?;
1430 // Never write ConnectionNeeded events as buffered onion messages aren't serialized.
1432 &Event::OnionMessageIntercepted { ref peer_node_id, ref message } => {
1433 37u8.write(writer)?;
1434 write_tlv_fields!(writer, {
1435 (0, peer_node_id, required),
1436 (2, message, required),
1439 &Event::OnionMessagePeerConnected { ref peer_node_id } => {
1440 39u8.write(writer)?;
1441 write_tlv_fields!(writer, {
1442 (0, peer_node_id, required),
1445 // Note that, going forward, all new events must only write data inside of
1446 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1447 // data via `write_tlv_fields`.
1452 impl MaybeReadable for Event {
1453 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1454 match Readable::read(reader)? {
1455 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events.
1459 let mut payment_hash = PaymentHash([0; 32]);
1460 let mut payment_preimage = None;
1461 let mut payment_secret = None;
1462 let mut amount_msat = 0;
1463 let mut counterparty_skimmed_fee_msat_opt = None;
1464 let mut receiver_node_id = None;
1465 let mut _user_payment_id = None::<u64>; // Used in 0.0.103 and earlier, no longer written in 0.0.116+.
1466 let mut via_channel_id = None;
1467 let mut claim_deadline = None;
1468 let mut via_user_channel_id = None;
1469 let mut onion_fields = None;
1470 let mut payment_context = None;
1471 read_tlv_fields!(reader, {
1472 (0, payment_hash, required),
1473 (1, receiver_node_id, option),
1474 (2, payment_secret, option),
1475 (3, via_channel_id, option),
1476 (4, amount_msat, required),
1477 (5, via_user_channel_id, option),
1478 (6, _user_payment_id, option),
1479 (7, claim_deadline, option),
1480 (8, payment_preimage, option),
1481 (9, onion_fields, option),
1482 (10, counterparty_skimmed_fee_msat_opt, option),
1483 (11, payment_context, option),
1485 let purpose = match payment_secret {
1486 Some(secret) => PaymentPurpose::from_parts(payment_preimage, secret, payment_context),
1487 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1488 None => return Err(msgs::DecodeError::InvalidValue),
1490 Ok(Some(Event::PaymentClaimable {
1494 counterparty_skimmed_fee_msat: counterparty_skimmed_fee_msat_opt.unwrap_or(0),
1497 via_user_channel_id,
1506 let mut payment_preimage = PaymentPreimage([0; 32]);
1507 let mut payment_hash = None;
1508 let mut payment_id = None;
1509 let mut fee_paid_msat = None;
1510 read_tlv_fields!(reader, {
1511 (0, payment_preimage, required),
1512 (1, payment_hash, option),
1513 (3, payment_id, option),
1514 (5, fee_paid_msat, option),
1516 if payment_hash.is_none() {
1517 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()));
1519 Ok(Some(Event::PaymentSent {
1522 payment_hash: payment_hash.unwrap(),
1531 let error_code = Readable::read(reader)?;
1533 let error_data = Readable::read(reader)?;
1534 let mut payment_hash = PaymentHash([0; 32]);
1535 let mut payment_failed_permanently = false;
1536 let mut network_update = None;
1537 let mut blinded_tail: Option<BlindedTail> = None;
1538 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1539 let mut short_channel_id = None;
1540 let mut payment_id = None;
1541 let mut failure_opt = None;
1542 read_tlv_fields!(reader, {
1543 (0, payment_hash, required),
1544 (1, network_update, upgradable_option),
1545 (2, payment_failed_permanently, required),
1546 (4, blinded_tail, option),
1547 // Added as a part of LDK 0.0.101 and always filled in since.
1548 // Defaults to an empty Vec, though likely should have been `Option`al.
1549 (5, path, optional_vec),
1550 (7, short_channel_id, option),
1551 (11, payment_id, option),
1552 (13, failure_opt, upgradable_option),
1554 let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1555 Ok(Some(Event::PaymentPathFailed {
1558 payment_failed_permanently,
1560 path: Path { hops: path.unwrap(), blinded_tail },
1573 let mut outputs = WithoutLength(Vec::new());
1574 let mut channel_id: Option<ChannelId> = None;
1575 read_tlv_fields!(reader, {
1576 (0, outputs, required),
1577 (1, channel_id, option),
1579 Ok(Some(Event::SpendableOutputs { outputs: outputs.0, channel_id }))
1584 let mut payment_hash = PaymentHash([0; 32]);
1585 let mut intercept_id = InterceptId([0; 32]);
1586 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1587 let mut inbound_amount_msat = 0;
1588 let mut expected_outbound_amount_msat = 0;
1589 read_tlv_fields!(reader, {
1590 (0, intercept_id, required),
1591 (2, requested_next_hop_scid, required),
1592 (4, payment_hash, required),
1593 (6, inbound_amount_msat, required),
1594 (8, expected_outbound_amount_msat, required),
1596 let next_scid = match requested_next_hop_scid {
1597 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1599 Ok(Some(Event::HTLCIntercepted {
1601 requested_next_hop_scid: next_scid,
1602 inbound_amount_msat,
1603 expected_outbound_amount_msat,
1609 let mut prev_channel_id = None;
1610 let mut next_channel_id = None;
1611 let mut prev_user_channel_id = None;
1612 let mut next_user_channel_id = None;
1613 let mut total_fee_earned_msat = None;
1614 let mut skimmed_fee_msat = None;
1615 let mut claim_from_onchain_tx = false;
1616 let mut outbound_amount_forwarded_msat = None;
1617 read_tlv_fields!(reader, {
1618 (0, total_fee_earned_msat, option),
1619 (1, prev_channel_id, option),
1620 (2, claim_from_onchain_tx, required),
1621 (3, next_channel_id, option),
1622 (5, outbound_amount_forwarded_msat, option),
1623 (7, skimmed_fee_msat, option),
1624 (9, prev_user_channel_id, option),
1625 (11, next_user_channel_id, option),
1627 Ok(Some(Event::PaymentForwarded {
1628 prev_channel_id, next_channel_id, prev_user_channel_id,
1629 next_user_channel_id, total_fee_earned_msat, skimmed_fee_msat,
1630 claim_from_onchain_tx, outbound_amount_forwarded_msat,
1637 let mut channel_id = ChannelId::new_zero();
1638 let mut reason = UpgradableRequired(None);
1639 let mut user_channel_id_low_opt: Option<u64> = None;
1640 let mut user_channel_id_high_opt: Option<u64> = None;
1641 let mut counterparty_node_id = None;
1642 let mut channel_capacity_sats = None;
1643 let mut channel_funding_txo = None;
1644 read_tlv_fields!(reader, {
1645 (0, channel_id, required),
1646 (1, user_channel_id_low_opt, option),
1647 (2, reason, upgradable_required),
1648 (3, user_channel_id_high_opt, option),
1649 (5, counterparty_node_id, option),
1650 (7, channel_capacity_sats, option),
1651 (9, channel_funding_txo, option),
1654 // `user_channel_id` used to be a single u64 value. In order to remain
1655 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1656 // as two separate u64 values.
1657 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1658 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1660 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required),
1661 counterparty_node_id, channel_capacity_sats, channel_funding_txo }))
1667 let mut channel_id = ChannelId::new_zero();
1668 let mut transaction = Transaction{ version: Version::TWO, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
1669 read_tlv_fields!(reader, {
1670 (0, channel_id, required),
1671 (2, transaction, required),
1673 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1679 _init_and_read_len_prefixed_tlv_fields!(reader, {
1680 (0, payment_id, required),
1681 (2, payment_hash, option),
1682 (4, path, required_vec),
1683 (6, blinded_tail, option),
1685 Ok(Some(Event::PaymentPathSuccessful {
1686 payment_id: payment_id.0.unwrap(),
1688 path: Path { hops: path, blinded_tail },
1695 let mut payment_hash = PaymentHash([0; 32]);
1696 let mut payment_id = PaymentId([0; 32]);
1697 let mut reason = None;
1698 read_tlv_fields!(reader, {
1699 (0, payment_id, required),
1700 (1, reason, upgradable_option),
1701 (2, payment_hash, required),
1703 Ok(Some(Event::PaymentFailed {
1712 // Value 17 is used for `Event::OpenChannelRequest`.
1717 let mut payment_hash = PaymentHash([0; 32]);
1718 let mut purpose = UpgradableRequired(None);
1719 let mut amount_msat = 0;
1720 let mut receiver_node_id = None;
1721 let mut htlcs: Option<Vec<ClaimedHTLC>> = Some(vec![]);
1722 let mut sender_intended_total_msat: Option<u64> = None;
1723 read_tlv_fields!(reader, {
1724 (0, payment_hash, required),
1725 (1, receiver_node_id, option),
1726 (2, purpose, upgradable_required),
1727 (4, amount_msat, required),
1728 (5, htlcs, optional_vec),
1729 (7, sender_intended_total_msat, option),
1731 Ok(Some(Event::PaymentClaimed {
1734 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1736 htlcs: htlcs.unwrap_or(vec![]),
1737 sender_intended_total_msat,
1744 _init_and_read_len_prefixed_tlv_fields!(reader, {
1745 (0, payment_id, required),
1746 (2, payment_hash, required),
1747 (4, path, required_vec),
1748 (6, blinded_tail, option),
1750 Ok(Some(Event::ProbeSuccessful {
1751 payment_id: payment_id.0.unwrap(),
1752 payment_hash: payment_hash.0.unwrap(),
1753 path: Path { hops: path, blinded_tail },
1760 _init_and_read_len_prefixed_tlv_fields!(reader, {
1761 (0, payment_id, required),
1762 (2, payment_hash, required),
1763 (4, path, required_vec),
1764 (6, short_channel_id, option),
1765 (8, blinded_tail, option),
1767 Ok(Some(Event::ProbeFailed {
1768 payment_id: payment_id.0.unwrap(),
1769 payment_hash: payment_hash.0.unwrap(),
1770 path: Path { hops: path, blinded_tail },
1778 let mut prev_channel_id = ChannelId::new_zero();
1779 let mut failed_next_destination_opt = UpgradableRequired(None);
1780 read_tlv_fields!(reader, {
1781 (0, prev_channel_id, required),
1782 (2, failed_next_destination_opt, upgradable_required),
1784 Ok(Some(Event::HTLCHandlingFailed {
1786 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1794 let mut channel_id = ChannelId::new_zero();
1795 let mut user_channel_id: u128 = 0;
1796 let mut counterparty_node_id = RequiredWrapper(None);
1797 let mut channel_type = RequiredWrapper(None);
1798 read_tlv_fields!(reader, {
1799 (0, channel_id, required),
1800 (2, user_channel_id, required),
1801 (4, counterparty_node_id, required),
1802 (6, channel_type, required),
1805 Ok(Some(Event::ChannelReady {
1808 counterparty_node_id: counterparty_node_id.0.unwrap(),
1809 channel_type: channel_type.0.unwrap()
1816 let mut channel_id = ChannelId::new_zero();
1817 let mut user_channel_id: u128 = 0;
1818 let mut former_temporary_channel_id = None;
1819 let mut counterparty_node_id = RequiredWrapper(None);
1820 let mut funding_txo = RequiredWrapper(None);
1821 let mut channel_type = None;
1822 read_tlv_fields!(reader, {
1823 (0, channel_id, required),
1824 (1, channel_type, option),
1825 (2, user_channel_id, required),
1826 (4, former_temporary_channel_id, required),
1827 (6, counterparty_node_id, required),
1828 (8, funding_txo, required),
1831 Ok(Some(Event::ChannelPending {
1834 former_temporary_channel_id,
1835 counterparty_node_id: counterparty_node_id.0.unwrap(),
1836 funding_txo: funding_txo.0.unwrap(),
1844 _init_and_read_len_prefixed_tlv_fields!(reader, {
1845 (0, payment_id, required),
1847 Ok(Some(Event::InvoiceRequestFailed {
1848 payment_id: payment_id.0.unwrap(),
1853 // Note that we do not write a length-prefixed TLV for ConnectionNeeded events.
1857 _init_and_read_len_prefixed_tlv_fields!(reader, {
1858 (0, peer_node_id, required),
1859 (2, message, required),
1861 Ok(Some(Event::OnionMessageIntercepted {
1862 peer_node_id: peer_node_id.0.unwrap(), message: message.0.unwrap()
1869 _init_and_read_len_prefixed_tlv_fields!(reader, {
1870 (0, peer_node_id, required),
1872 Ok(Some(Event::OnionMessagePeerConnected {
1873 peer_node_id: peer_node_id.0.unwrap()
1878 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1879 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1881 x if x % 2 == 1 => {
1882 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1883 // which prefixes the whole thing with a length BigSize. Because the event is
1884 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1885 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1886 // exactly the number of bytes specified, ignoring them entirely.
1887 let tlv_len: BigSize = Readable::read(reader)?;
1888 FixedLengthReader::new(reader, tlv_len.0)
1889 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1892 _ => Err(msgs::DecodeError::InvalidValue)
1897 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1898 /// broadcast to most peers).
1899 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1900 #[derive(Clone, Debug)]
1901 #[cfg_attr(test, derive(PartialEq))]
1902 pub enum MessageSendEvent {
1903 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1904 /// message provided to the given peer.
1906 /// The node_id of the node which should receive this message
1908 /// The message which should be sent.
1909 msg: msgs::AcceptChannel,
1911 /// Used to indicate that we've accepted a V2 channel open and should send the accept_channel2
1912 /// message provided to the given peer.
1913 SendAcceptChannelV2 {
1914 /// The node_id of the node which should receive this message
1916 /// The message which should be sent.
1917 msg: msgs::AcceptChannelV2,
1919 /// Used to indicate that we've initiated a channel open and should send the open_channel
1920 /// message provided to the given peer.
1922 /// The node_id of the node which should receive this message
1924 /// The message which should be sent.
1925 msg: msgs::OpenChannel,
1927 /// Used to indicate that we've initiated a V2 channel open and should send the open_channel2
1928 /// message provided to the given peer.
1930 /// The node_id of the node which should receive this message
1932 /// The message which should be sent.
1933 msg: msgs::OpenChannelV2,
1935 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1936 SendFundingCreated {
1937 /// The node_id of the node which should receive this message
1939 /// The message which should be sent.
1940 msg: msgs::FundingCreated,
1942 /// Used to indicate that a funding_signed 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::FundingSigned,
1949 /// Used to indicate that a stfu 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.
1956 /// Used to indicate that a splice 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 splice_ack message should be sent to the peer with the given node id.
1965 /// The node_id of the node which should receive this message
1967 /// The message which should be sent.
1968 msg: msgs::SpliceAck,
1970 /// Used to indicate that a splice_locked message should be sent to the peer with the given node id.
1972 /// The node_id of the node which should receive this message
1974 /// The message which should be sent.
1975 msg: msgs::SpliceLocked,
1977 /// Used to indicate that a tx_add_input message should be sent to the peer with the given node_id.
1979 /// The node_id of the node which should receive this message
1981 /// The message which should be sent.
1982 msg: msgs::TxAddInput,
1984 /// Used to indicate that a tx_add_output message should be sent to the peer with the given node_id.
1986 /// The node_id of the node which should receive this message
1988 /// The message which should be sent.
1989 msg: msgs::TxAddOutput,
1991 /// Used to indicate that a tx_remove_input message should be sent to the peer with the given node_id.
1993 /// The node_id of the node which should receive this message
1995 /// The message which should be sent.
1996 msg: msgs::TxRemoveInput,
1998 /// Used to indicate that a tx_remove_output message should be sent to the peer with the given node_id.
1999 SendTxRemoveOutput {
2000 /// The node_id of the node which should receive this message
2002 /// The message which should be sent.
2003 msg: msgs::TxRemoveOutput,
2005 /// Used to indicate that a tx_complete message should be sent to the peer with the given node_id.
2007 /// The node_id of the node which should receive this message
2009 /// The message which should be sent.
2010 msg: msgs::TxComplete,
2012 /// Used to indicate that a tx_signatures message should be sent to the peer with the given node_id.
2014 /// The node_id of the node which should receive this message
2016 /// The message which should be sent.
2017 msg: msgs::TxSignatures,
2019 /// Used to indicate that a tx_init_rbf message should be sent to the peer with the given node_id.
2021 /// The node_id of the node which should receive this message
2023 /// The message which should be sent.
2024 msg: msgs::TxInitRbf,
2026 /// Used to indicate that a tx_ack_rbf message should be sent to the peer with the given node_id.
2028 /// The node_id of the node which should receive this message
2030 /// The message which should be sent.
2031 msg: msgs::TxAckRbf,
2033 /// Used to indicate that a tx_abort message should be sent to the peer with the given node_id.
2035 /// The node_id of the node which should receive this message
2037 /// The message which should be sent.
2040 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
2042 /// The node_id of the node which should receive these message(s)
2044 /// The channel_ready message which should be sent.
2045 msg: msgs::ChannelReady,
2047 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
2048 SendAnnouncementSignatures {
2049 /// The node_id of the node which should receive these message(s)
2051 /// The announcement_signatures message which should be sent.
2052 msg: msgs::AnnouncementSignatures,
2054 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
2055 /// message should be sent to the peer with the given node_id.
2057 /// The node_id of the node which should receive these message(s)
2059 /// The update messages which should be sent. ALL messages in the struct should be sent!
2060 updates: msgs::CommitmentUpdate,
2062 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
2064 /// The node_id of the node which should receive this message
2066 /// The message which should be sent.
2067 msg: msgs::RevokeAndACK,
2069 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
2071 /// The node_id of the node which should receive this message
2073 /// The message which should be sent.
2074 msg: msgs::ClosingSigned,
2076 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
2078 /// The node_id of the node which should receive this message
2080 /// The message which should be sent.
2081 msg: msgs::Shutdown,
2083 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
2084 SendChannelReestablish {
2085 /// The node_id of the node which should receive this message
2087 /// The message which should be sent.
2088 msg: msgs::ChannelReestablish,
2090 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
2091 /// initial connection to ensure our peers know about our channels.
2092 SendChannelAnnouncement {
2093 /// The node_id of the node which should receive this message
2095 /// The channel_announcement which should be sent.
2096 msg: msgs::ChannelAnnouncement,
2097 /// The followup channel_update which should be sent.
2098 update_msg: msgs::ChannelUpdate,
2100 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
2101 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
2103 /// Note that after doing so, you very likely (unless you did so very recently) want to
2104 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
2105 /// ensures that any nodes which see our channel_announcement also have a relevant
2106 /// node_announcement, including relevant feature flags which may be important for routing
2107 /// through or to us.
2109 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
2110 BroadcastChannelAnnouncement {
2111 /// The channel_announcement which should be sent.
2112 msg: msgs::ChannelAnnouncement,
2113 /// The followup channel_update which should be sent.
2114 update_msg: Option<msgs::ChannelUpdate>,
2116 /// Used to indicate that a channel_update should be broadcast to all peers.
2117 BroadcastChannelUpdate {
2118 /// The channel_update which should be sent.
2119 msg: msgs::ChannelUpdate,
2121 /// Used to indicate that a node_announcement should be broadcast to all peers.
2122 BroadcastNodeAnnouncement {
2123 /// The node_announcement which should be sent.
2124 msg: msgs::NodeAnnouncement,
2126 /// Used to indicate that a channel_update should be sent to a single peer.
2127 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
2128 /// private channel and we shouldn't be informing all of our peers of channel parameters.
2130 /// The node_id of the node which should receive this message
2132 /// The channel_update which should be sent.
2133 msg: msgs::ChannelUpdate,
2135 /// Broadcast an error downstream to be handled
2137 /// The node_id of the node which should receive this message
2139 /// The action which should be taken.
2140 action: msgs::ErrorAction
2142 /// Query a peer for channels with funding transaction UTXOs in a block range.
2143 SendChannelRangeQuery {
2144 /// The node_id of this message recipient
2146 /// The query_channel_range which should be sent.
2147 msg: msgs::QueryChannelRange,
2149 /// Request routing gossip messages from a peer for a list of channels identified by
2150 /// their short_channel_ids.
2152 /// The node_id of this message recipient
2154 /// The query_short_channel_ids which should be sent.
2155 msg: msgs::QueryShortChannelIds,
2157 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
2158 /// emitted during processing of the query.
2159 SendReplyChannelRange {
2160 /// The node_id of this message recipient
2162 /// The reply_channel_range which should be sent.
2163 msg: msgs::ReplyChannelRange,
2165 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
2166 /// enable receiving gossip messages from the peer.
2167 SendGossipTimestampFilter {
2168 /// The node_id of this message recipient
2170 /// The gossip_timestamp_filter which should be sent.
2171 msg: msgs::GossipTimestampFilter,
2175 /// A trait indicating an object may generate message send events
2176 pub trait MessageSendEventsProvider {
2177 /// Gets the list of pending events which were generated by previous actions, clearing the list
2179 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
2182 /// A trait indicating an object may generate events.
2184 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
2186 /// Implementations of this trait may also feature an async version of event handling, as shown with
2187 /// [`ChannelManager::process_pending_events_async`] and
2188 /// [`ChainMonitor::process_pending_events_async`].
2192 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
2193 /// event since the last invocation.
2195 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
2196 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
2197 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
2198 /// relevant changes to disk *before* returning.
2200 /// Further, because an application may crash between an [`Event`] being handled and the
2201 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
2202 /// effect, [`Event`]s may be replayed.
2204 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
2205 /// consult the provider's documentation on the implication of processing events and how a handler
2206 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
2207 /// [`ChainMonitor::process_pending_events`]).
2209 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
2212 /// [`process_pending_events`]: Self::process_pending_events
2213 /// [`handle_event`]: EventHandler::handle_event
2214 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
2215 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
2216 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
2217 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
2218 pub trait EventsProvider {
2219 /// Processes any events generated since the last call using the given event handler.
2221 /// See the trait-level documentation for requirements.
2222 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
2225 /// A trait implemented for objects handling events from [`EventsProvider`].
2227 /// An async variation also exists for implementations of [`EventsProvider`] that support async
2228 /// event handling. The async event handler should satisfy the generic bounds: `F:
2229 /// core::future::Future, H: Fn(Event) -> F`.
2230 pub trait EventHandler {
2231 /// Handles the given [`Event`].
2233 /// See [`EventsProvider`] for details that must be considered when implementing this method.
2234 fn handle_event(&self, event: Event);
2237 impl<F> EventHandler for F where F: Fn(Event) {
2238 fn handle_event(&self, event: Event) {
2243 impl<T: EventHandler> EventHandler for Arc<T> {
2244 fn handle_event(&self, event: Event) {
2245 self.deref().handle_event(event)