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 /// Whether or not the latest transaction was broadcasted when the channel was force
285 /// Channels closed using [`ChannelManager::force_close_broadcasting_latest_txn`] will have
286 /// this field set to true, whereas channels closed using [`ChannelManager::force_close_without_broadcasting_txn`]
287 /// or force-closed prior to being funded will have this field set to false.
289 /// This will be `None` for objects generated or written by LDK 0.0.123 and
292 /// [`ChannelManager::force_close_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_broadcasting_latest_txn.
293 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn.
294 broadcasted_latest_txn: Option<bool>
296 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
297 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
299 /// This was only set in versions of LDK prior to 0.0.122.
300 // Can be removed once we disallow downgrading to 0.0.121
301 LegacyCooperativeClosure,
302 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
303 /// the cooperative close transaction. This indicates that the shutdown was initiated by our
306 /// In rare cases where we initiated closure immediately prior to shutting down without
307 /// persisting, this value may be provided for channels we initiated closure for.
308 CounterpartyInitiatedCooperativeClosure,
309 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
310 /// the cooperative close transaction. This indicates that the shutdown was initiated by us.
311 LocallyInitiatedCooperativeClosure,
312 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
313 /// commitment transaction came from our counterparty, but it may also have come from
314 /// a copy of our own `ChannelMonitor`.
315 CommitmentTxConfirmed,
316 /// The funding transaction failed to confirm in a timely manner on an inbound channel.
318 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
320 /// A developer-readable error message which we generated.
323 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
324 /// forget the channel entirely - we can attempt again if the peer reconnects.
326 /// This includes cases where we restarted prior to funding completion, including prior to the
327 /// initial [`ChannelMonitor`] persistence completing.
329 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
330 /// peer because of mutual incompatibility between us and our channel counterparty.
332 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
334 /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
335 /// the [`ChannelManager`] deserialized.
337 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
338 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
339 OutdatedChannelManager,
340 /// The counterparty requested a cooperative close of a channel that had not been funded yet.
341 /// The channel has been immediately closed.
342 CounterpartyCoopClosedUnfundedChannel,
343 /// Another channel in the same funding batch closed before the funding transaction
344 /// was ready to be broadcast.
346 /// One of our HTLCs timed out in a channel, causing us to force close the channel.
348 /// Our peer provided a feerate which violated our required minimum (fetched from our
349 /// [`FeeEstimator`] either as [`ConfirmationTarget::MinAllowedAnchorChannelRemoteFee`] or
350 /// [`ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee`]).
352 /// [`FeeEstimator`]: crate::chain::chaininterface::FeeEstimator
353 /// [`ConfirmationTarget::MinAllowedAnchorChannelRemoteFee`]: crate::chain::chaininterface::ConfirmationTarget::MinAllowedAnchorChannelRemoteFee
354 /// [`ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee`]: crate::chain::chaininterface::ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee
356 /// The feerate on our channel set by our peer.
357 peer_feerate_sat_per_kw: u32,
358 /// The required feerate we enforce, from our [`FeeEstimator`].
360 /// [`FeeEstimator`]: crate::chain::chaininterface::FeeEstimator
361 required_feerate_sat_per_kw: u32,
365 impl core::fmt::Display for ClosureReason {
366 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
367 f.write_str("Channel closed because ")?;
369 ClosureReason::CounterpartyForceClosed { peer_msg } => {
370 f.write_fmt(format_args!("counterparty force-closed with message: {}", peer_msg))
372 ClosureReason::HolderForceClosed { broadcasted_latest_txn } => {
373 f.write_str("user force-closed the channel")?;
374 if let Some(brodcasted) = broadcasted_latest_txn {
375 write!(f, " and {} the latest transaction", if *brodcasted { "broadcasted" } else { "did not broadcast" })
380 ClosureReason::LegacyCooperativeClosure => f.write_str("the channel was cooperatively closed"),
381 ClosureReason::CounterpartyInitiatedCooperativeClosure => f.write_str("the channel was cooperatively closed by our peer"),
382 ClosureReason::LocallyInitiatedCooperativeClosure => f.write_str("the channel was cooperatively closed by us"),
383 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
384 ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
385 ClosureReason::ProcessingError { err } => {
386 f.write_str("of an exception: ")?;
389 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
390 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
391 ClosureReason::CounterpartyCoopClosedUnfundedChannel => f.write_str("the peer requested the unfunded channel be closed"),
392 ClosureReason::FundingBatchClosure => f.write_str("another channel in the same funding batch closed"),
393 ClosureReason::HTLCsTimedOut => f.write_str("htlcs on the channel timed out"),
394 ClosureReason::PeerFeerateTooLow { peer_feerate_sat_per_kw, required_feerate_sat_per_kw } =>
395 f.write_fmt(format_args!(
396 "peer provided a feerate ({} sat/kw) which was below our lower bound ({} sat/kw)",
397 peer_feerate_sat_per_kw, required_feerate_sat_per_kw,
403 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
404 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
405 (1, FundingTimedOut) => {},
406 (2, HolderForceClosed) => { (1, broadcasted_latest_txn, option) },
407 (6, CommitmentTxConfirmed) => {},
408 (4, LegacyCooperativeClosure) => {},
409 (8, ProcessingError) => { (1, err, required) },
410 (10, DisconnectedPeer) => {},
411 (12, OutdatedChannelManager) => {},
412 (13, CounterpartyCoopClosedUnfundedChannel) => {},
413 (15, FundingBatchClosure) => {},
414 (17, CounterpartyInitiatedCooperativeClosure) => {},
415 (19, LocallyInitiatedCooperativeClosure) => {},
416 (21, HTLCsTimedOut) => {},
417 (23, PeerFeerateTooLow) => {
418 (0, peer_feerate_sat_per_kw, required),
419 (2, required_feerate_sat_per_kw, required),
423 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
424 #[derive(Clone, Debug, PartialEq, Eq)]
425 pub enum HTLCDestination {
426 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
427 /// there is insufficient capacity in our outbound channel.
429 /// The `node_id` of the next node. For backwards compatibility, this field is
430 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
431 /// counterparty node information.
432 node_id: Option<PublicKey>,
433 /// The outgoing `channel_id` between us and the next node.
434 channel_id: ChannelId,
436 /// Scenario where we are unsure of the next node to forward the HTLC to.
438 /// Short channel id we are requesting to forward an HTLC to.
439 requested_forward_scid: u64,
441 /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
444 /// Short channel id we are requesting to forward an HTLC to.
445 requested_forward_scid: u64
447 /// We couldn't decode the incoming onion to obtain the forwarding details.
449 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
450 /// but is invalid for some reason, so we reject it.
452 /// Some of the reasons may include:
454 /// * Excess HTLCs for a payment that we have already fully received, over-paying for the
456 /// * The counterparty node modified the HTLC in transit,
457 /// * A probing attack where an intermediary node is trying to detect if we are the ultimate
458 /// recipient for a payment.
460 /// The payment hash of the payment we attempted to process.
461 payment_hash: PaymentHash
465 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
466 (0, NextHopChannel) => {
467 (0, node_id, required),
468 (2, channel_id, required),
470 (1, InvalidForward) => {
471 (0, requested_forward_scid, required),
473 (2, UnknownNextHop) => {
474 (0, requested_forward_scid, required),
476 (3, InvalidOnion) => {},
477 (4, FailedPayment) => {
478 (0, payment_hash, required),
482 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
483 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
484 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
485 /// intercepts in upcoming work.
486 enum InterceptNextHop {
488 requested_next_hop_scid: u64,
492 impl_writeable_tlv_based_enum!(InterceptNextHop,
494 (0, requested_next_hop_scid, required),
498 /// The reason the payment failed. Used in [`Event::PaymentFailed`].
499 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
500 pub enum PaymentFailureReason {
501 /// The intended recipient rejected our payment.
503 /// The user chose to abandon this payment by calling [`ChannelManager::abandon_payment`].
505 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
507 /// We exhausted all of our retry attempts while trying to send the payment, or we
508 /// exhausted the [`Retry::Timeout`] if the user set one. If at any point a retry
509 /// attempt failed while being forwarded along the path, an [`Event::PaymentPathFailed`] will
510 /// have come before this.
512 /// [`Retry::Timeout`]: crate::ln::channelmanager::Retry::Timeout
514 /// The payment expired while retrying, based on the provided
515 /// [`PaymentParameters::expiry_time`].
517 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
519 /// We failed to find a route while retrying the payment.
521 /// Note that this generally indicates that we've exhausted the available set of possible
522 /// routes - we tried the payment over a few routes but were not able to find any further
523 /// candidate routes beyond those.
525 /// This error should generally never happen. This likely means that there is a problem with
530 impl_writeable_tlv_based_enum!(PaymentFailureReason,
531 (0, RecipientRejected) => {},
532 (2, UserAbandoned) => {},
533 (4, RetriesExhausted) => {},
534 (6, PaymentExpired) => {},
535 (8, RouteNotFound) => {},
536 (10, UnexpectedError) => {}, ;
539 /// An Event which you should probably take some action in response to.
541 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
542 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
543 /// written as it makes no sense to respond to it after reconnecting to peers).
544 #[derive(Clone, Debug, PartialEq, Eq)]
546 /// Used to indicate that the client should generate a funding transaction with the given
547 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
548 /// Generated in [`ChannelManager`] message handling.
549 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
550 /// counterparty can steal your funds!
552 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
553 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
554 FundingGenerationReady {
555 /// The random channel_id we picked which you'll need to pass into
556 /// [`ChannelManager::funding_transaction_generated`].
558 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
559 temporary_channel_id: ChannelId,
560 /// The counterparty's node_id, which you'll need to pass back into
561 /// [`ChannelManager::funding_transaction_generated`].
563 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
564 counterparty_node_id: PublicKey,
565 /// The value, in satoshis, that the output should have.
566 channel_value_satoshis: u64,
567 /// The script which should be used in the transaction output.
568 output_script: ScriptBuf,
569 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
570 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
571 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
572 /// `user_channel_id` will be randomized for an inbound channel. This may be zero for objects
573 /// serialized with LDK versions prior to 0.0.113.
575 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
576 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
577 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
578 user_channel_id: u128,
580 /// Indicates that we've been offered a payment and it needs to be claimed via calling
581 /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
583 /// Note that if the preimage is not known, you should call
584 /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
585 /// to free up resources for this HTLC and avoid network congestion.
587 /// If [`Event::PaymentClaimable::onion_fields`] is `Some`, and includes custom TLVs with even type
588 /// numbers, you should use [`ChannelManager::fail_htlc_backwards_with_reason`] with
589 /// [`FailureCode::InvalidOnionPayload`] if you fail to understand and handle the contents, or
590 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`] upon successful handling.
591 /// If you don't intend to check for custom TLVs, you can simply use
592 /// [`ChannelManager::claim_funds`], which will automatically fail back even custom TLVs.
594 /// If you fail to call [`ChannelManager::claim_funds`],
595 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`],
596 /// [`ChannelManager::fail_htlc_backwards`], or
597 /// [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will
598 /// be automatically failed.
601 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
602 /// `PaymentClaimable` events may be generated for the same payment. In such a case it is
603 /// polite (and required in the lightning specification) to fail the payment the second time
604 /// and give the sender their money back rather than accepting double payment.
607 /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
609 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
610 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`]: crate::ln::channelmanager::ChannelManager::claim_funds_with_known_custom_tlvs
611 /// [`FailureCode::InvalidOnionPayload`]: crate::ln::channelmanager::FailureCode::InvalidOnionPayload
612 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
613 /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
615 /// The node that will receive the payment after it has been claimed.
616 /// This is useful to identify payments received via [phantom nodes].
617 /// This field will always be filled in when the event was generated by LDK versions
618 /// 0.0.113 and above.
620 /// [phantom nodes]: crate::sign::PhantomKeysManager
621 receiver_node_id: Option<PublicKey>,
622 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
623 /// not stop you from registering duplicate payment hashes for inbound payments.
624 payment_hash: PaymentHash,
625 /// The fields in the onion which were received with each HTLC. Only fields which were
626 /// identical in each HTLC involved in the payment will be included here.
628 /// Payments received on LDK versions prior to 0.0.115 will have this field unset.
629 onion_fields: Option<RecipientOnionFields>,
630 /// The value, in thousandths of a satoshi, that this payment is claimable for. May be greater
631 /// than the invoice amount.
633 /// May be less than the invoice amount if [`ChannelConfig::accept_underpaying_htlcs`] is set
634 /// and the previous hop took an extra fee.
637 /// If [`ChannelConfig::accept_underpaying_htlcs`] is set and you claim without verifying this
638 /// field, you may lose money!
640 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
642 /// The value, in thousands of a satoshi, that was skimmed off of this payment as an extra fee
643 /// taken by our channel counterparty.
645 /// Will always be 0 unless [`ChannelConfig::accept_underpaying_htlcs`] is set.
647 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
648 counterparty_skimmed_fee_msat: u64,
649 /// Information for claiming this received payment, based on whether the purpose of the
650 /// payment is to pay an invoice or to send a spontaneous payment.
651 purpose: PaymentPurpose,
652 /// The `channel_id` indicating over which channel we received the payment.
653 via_channel_id: Option<ChannelId>,
654 /// The `user_channel_id` indicating over which channel we received the payment.
655 via_user_channel_id: Option<u128>,
656 /// The block height at which this payment will be failed back and will no longer be
657 /// eligible for claiming.
659 /// Prior to this height, a call to [`ChannelManager::claim_funds`] is guaranteed to
660 /// succeed, however you should wait for [`Event::PaymentClaimed`] to be sure.
662 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
663 claim_deadline: Option<u32>,
665 /// Indicates a payment has been claimed and we've received money!
667 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
668 /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
669 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
670 /// [`Event::PaymentClaimable`] event.
673 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
674 /// `PaymentClaimable` events may be generated for the same payment. If you then call
675 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
676 /// multiple `PaymentClaimed` events.
678 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
680 /// The node that received the payment.
681 /// This is useful to identify payments which were received via [phantom nodes].
682 /// This field will always be filled in when the event was generated by LDK versions
683 /// 0.0.113 and above.
685 /// [phantom nodes]: crate::sign::PhantomKeysManager
686 receiver_node_id: Option<PublicKey>,
687 /// The payment hash of the claimed payment. Note that LDK will not stop you from
688 /// registering duplicate payment hashes for inbound payments.
689 payment_hash: PaymentHash,
690 /// The value, in thousandths of a satoshi, that this payment is for. May be greater than the
693 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
694 /// spontaneous payment.
695 purpose: PaymentPurpose,
696 /// The HTLCs that comprise the claimed payment. This will be empty for events serialized prior
697 /// to LDK version 0.0.117.
698 htlcs: Vec<ClaimedHTLC>,
699 /// The sender-intended sum total of all the MPP parts. This will be `None` for events
700 /// serialized prior to LDK version 0.0.117.
701 sender_intended_total_msat: Option<u64>,
702 /// The fields in the onion which were received with each HTLC. Only fields which were
703 /// identical in each HTLC involved in the payment will be included here.
705 /// Payments received on LDK versions prior to 0.0.124 will have this field unset.
706 onion_fields: Option<RecipientOnionFields>,
708 /// Indicates that a peer connection with a node is needed in order to send an [`OnionMessage`].
710 /// Typically, this happens when a [`MessageRouter`] is unable to find a complete path to a
711 /// [`Destination`]. Once a connection is established, any messages buffered by an
712 /// [`OnionMessageHandler`] may be sent.
714 /// This event will not be generated for onion message forwards; only for sends including
715 /// replies. Handlers should connect to the node otherwise any buffered messages may be lost.
717 /// [`OnionMessage`]: msgs::OnionMessage
718 /// [`MessageRouter`]: crate::onion_message::messenger::MessageRouter
719 /// [`Destination`]: crate::onion_message::messenger::Destination
720 /// [`OnionMessageHandler`]: crate::ln::msgs::OnionMessageHandler
722 /// The node id for the node needing a connection.
724 /// Sockets for connecting to the node.
725 addresses: Vec<msgs::SocketAddress>,
727 /// Indicates a request for an invoice failed to yield a response in a reasonable amount of time
728 /// or was explicitly abandoned by [`ChannelManager::abandon_payment`]. This may be for an
729 /// [`InvoiceRequest`] sent for an [`Offer`] or for a [`Refund`] that hasn't been redeemed.
731 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
732 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
733 /// [`Offer`]: crate::offers::offer::Offer
734 /// [`Refund`]: crate::offers::refund::Refund
735 InvoiceRequestFailed {
736 /// The `payment_id` to have been associated with payment for the requested invoice.
737 payment_id: PaymentId,
739 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
740 /// and we got back the payment preimage for it).
742 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
743 /// event. In this situation, you SHOULD treat this payment as having succeeded.
745 /// The `payment_id` passed to [`ChannelManager::send_payment`].
747 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
748 payment_id: Option<PaymentId>,
749 /// The preimage to the hash given to ChannelManager::send_payment.
750 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
751 /// store it somehow!
752 payment_preimage: PaymentPreimage,
753 /// The hash that was given to [`ChannelManager::send_payment`].
755 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
756 payment_hash: PaymentHash,
757 /// The total fee which was spent at intermediate hops in this payment, across all paths.
759 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
760 /// overpayment to the recipient node.
762 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
763 /// overstate the amount paid, though this is unlikely.
765 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
766 fee_paid_msat: Option<u64>,
768 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
769 /// provide failure information for each path attempt in the payment, including retries.
771 /// This event is provided once there are no further pending HTLCs for the payment and the
772 /// payment is no longer retryable, due either to the [`Retry`] provided or
773 /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
775 /// In exceedingly rare cases, it is possible that an [`Event::PaymentFailed`] is generated for
776 /// a payment after an [`Event::PaymentSent`] event for this same payment has already been
777 /// received and processed. In this case, the [`Event::PaymentFailed`] event MUST be ignored,
778 /// and the payment MUST be treated as having succeeded.
780 /// [`Retry`]: crate::ln::channelmanager::Retry
781 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
783 /// The `payment_id` passed to [`ChannelManager::send_payment`].
785 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
786 payment_id: PaymentId,
787 /// The hash that was given to [`ChannelManager::send_payment`].
789 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
790 payment_hash: PaymentHash,
791 /// The reason the payment failed. This is only `None` for events generated or serialized
792 /// by versions prior to 0.0.115.
793 reason: Option<PaymentFailureReason>,
795 /// Indicates that a path for an outbound payment was successful.
797 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
798 /// [`Event::PaymentSent`] for obtaining the payment preimage.
799 PaymentPathSuccessful {
800 /// The `payment_id` passed to [`ChannelManager::send_payment`].
802 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
803 payment_id: PaymentId,
804 /// The hash that was given to [`ChannelManager::send_payment`].
806 /// This will be `Some` for all payments which completed on LDK 0.0.104 or later.
808 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
809 payment_hash: Option<PaymentHash>,
810 /// The payment path that was successful.
812 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
815 /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
818 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
819 /// [`Event::PaymentFailed`].
821 /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
824 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
826 /// The `payment_id` passed to [`ChannelManager::send_payment`].
828 /// This will be `Some` for all payment paths which failed on LDK 0.0.103 or later.
830 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
831 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
832 payment_id: Option<PaymentId>,
833 /// The hash that was given to [`ChannelManager::send_payment`].
835 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
836 payment_hash: PaymentHash,
837 /// Indicates the payment was rejected for some reason by the recipient. This implies that
838 /// the payment has failed, not just the route in question. If this is not set, the payment may
839 /// be retried via a different route.
840 payment_failed_permanently: bool,
841 /// Extra error details based on the failure type. May contain an update that needs to be
842 /// applied to the [`NetworkGraph`].
844 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
845 failure: PathFailure,
846 /// The payment path that failed.
848 /// The channel responsible for the failed payment path.
850 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
851 /// may not refer to a channel in the public network graph. These aliases may also collide
852 /// with channels in the public network graph.
854 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
855 /// retried. May be `None` for older [`Event`] serializations.
856 short_channel_id: Option<u64>,
858 error_code: Option<u16>,
860 error_data: Option<Vec<u8>>,
862 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
864 /// The id returned by [`ChannelManager::send_probe`].
866 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
867 payment_id: PaymentId,
868 /// The hash generated by [`ChannelManager::send_probe`].
870 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
871 payment_hash: PaymentHash,
872 /// The payment path that was successful.
875 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
877 /// The id returned by [`ChannelManager::send_probe`].
879 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
880 payment_id: PaymentId,
881 /// The hash generated by [`ChannelManager::send_probe`].
883 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
884 payment_hash: PaymentHash,
885 /// The payment path that failed.
887 /// The channel responsible for the failed probe.
889 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
890 /// may not refer to a channel in the public network graph. These aliases may also collide
891 /// with channels in the public network graph.
892 short_channel_id: Option<u64>,
894 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
895 /// a time in the future.
897 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
898 PendingHTLCsForwardable {
899 /// The minimum amount of time that should be waited prior to calling
900 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
901 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
902 /// now + 5*time_forwardable).
903 time_forwardable: Duration,
905 /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
906 /// you've encoded an intercept scid in the receiver's invoice route hints using
907 /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
909 /// [`ChannelManager::forward_intercepted_htlc`] or
910 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
911 /// their docs for more information.
913 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
914 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
915 /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
916 /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
918 /// An id to help LDK identify which HTLC is being forwarded or failed.
919 intercept_id: InterceptId,
920 /// The fake scid that was programmed as the next hop's scid, generated using
921 /// [`ChannelManager::get_intercept_scid`].
923 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
924 requested_next_hop_scid: u64,
925 /// The payment hash used for this HTLC.
926 payment_hash: PaymentHash,
927 /// How many msats were received on the inbound edge of this HTLC.
928 inbound_amount_msat: u64,
929 /// How many msats the payer intended to route to the next node. Depending on the reason you are
930 /// intercepting this payment, you might take a fee by forwarding less than this amount.
931 /// Forwarding less than this amount may break compatibility with LDK versions prior to 0.0.116.
933 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
934 /// check that whatever fee you want has been included here or subtract it as required. Further,
935 /// LDK will not stop you from forwarding more than you received.
936 expected_outbound_amount_msat: u64,
938 /// Used to indicate that an output which you should know how to spend was confirmed on chain
939 /// and is now spendable.
941 /// Such an output will *never* be spent directly by LDK, and are not at risk of your
942 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
943 /// somewhere and spend them when you create on-chain transactions.
945 /// You may hand them to the [`OutputSweeper`] utility which will store and (re-)generate spending
946 /// transactions for you.
948 /// [`OutputSweeper`]: crate::util::sweep::OutputSweeper
950 /// The outputs which you should store as spendable by you.
951 outputs: Vec<SpendableOutputDescriptor>,
952 /// The `channel_id` indicating which channel the spendable outputs belong to.
954 /// This will always be `Some` for events generated by LDK versions 0.0.117 and above.
955 channel_id: Option<ChannelId>,
957 /// This event is generated when a payment has been successfully forwarded through us and a
958 /// forwarding fee earned.
960 /// The channel id of the incoming channel between the previous node and us.
962 /// This is only `None` for events generated or serialized by versions prior to 0.0.107.
963 prev_channel_id: Option<ChannelId>,
964 /// The channel id of the outgoing channel between the next node and us.
966 /// This is only `None` for events generated or serialized by versions prior to 0.0.107.
967 next_channel_id: Option<ChannelId>,
968 /// The `user_channel_id` of the incoming channel between the previous node and us.
970 /// This is only `None` for events generated or serialized by versions prior to 0.0.122.
971 prev_user_channel_id: Option<u128>,
972 /// The `user_channel_id` of the outgoing channel between the next node and us.
974 /// This will be `None` if the payment was settled via an on-chain transaction. See the
975 /// caveat described for the `total_fee_earned_msat` field. Moreover it will be `None` for
976 /// events generated or serialized by versions prior to 0.0.122.
977 next_user_channel_id: Option<u128>,
978 /// The total fee, in milli-satoshis, which was earned as a result of the payment.
980 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
981 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
982 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
983 /// claimed the full value in millisatoshis from the source. In this case,
984 /// `claim_from_onchain_tx` will be set.
986 /// If the channel which sent us the payment has been force-closed, we will claim the funds
987 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
988 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
989 /// `PaymentForwarded` events are generated for the same payment iff `total_fee_earned_msat` is
991 total_fee_earned_msat: Option<u64>,
992 /// The share of the total fee, in milli-satoshis, which was withheld in addition to the
995 /// This will only be `Some` if we forwarded an intercepted HTLC with less than the
996 /// expected amount. This means our counterparty accepted to receive less than the invoice
997 /// amount, e.g., by claiming the payment featuring a corresponding
998 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`].
1000 /// Will also always be `None` for events serialized with LDK prior to version 0.0.122.
1002 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
1004 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`]: Self::PaymentClaimable::counterparty_skimmed_fee_msat
1005 skimmed_fee_msat: Option<u64>,
1006 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
1008 claim_from_onchain_tx: bool,
1009 /// The final amount forwarded, in milli-satoshis, after the fee is deducted.
1011 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
1012 outbound_amount_forwarded_msat: Option<u64>,
1014 /// Used to indicate that a channel with the given `channel_id` is being opened and pending
1015 /// confirmation on-chain.
1017 /// This event is emitted when the funding transaction has been signed and is broadcast to the
1018 /// network. For 0conf channels it will be immediately followed by the corresponding
1019 /// [`Event::ChannelReady`] event.
1021 /// The `channel_id` of the channel that is pending confirmation.
1022 channel_id: ChannelId,
1023 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1024 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1025 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1026 /// `user_channel_id` will be randomized for an inbound channel.
1028 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1029 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1030 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1031 user_channel_id: u128,
1032 /// The `temporary_channel_id` this channel used to be known by during channel establishment.
1034 /// Will be `None` for channels created prior to LDK version 0.0.115.
1035 former_temporary_channel_id: Option<ChannelId>,
1036 /// The `node_id` of the channel counterparty.
1037 counterparty_node_id: PublicKey,
1038 /// The outpoint of the channel's funding transaction.
1039 funding_txo: OutPoint,
1040 /// The features that this channel will operate with.
1042 /// Will be `None` for channels created prior to LDK version 0.0.122.
1043 channel_type: Option<ChannelTypeFeatures>,
1045 /// Used to indicate that a channel with the given `channel_id` is ready to
1046 /// be used. This event is emitted either when the funding transaction has been confirmed
1047 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
1050 /// The `channel_id` of the channel that is ready.
1051 channel_id: ChannelId,
1052 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1053 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1054 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1055 /// `user_channel_id` will be randomized for an inbound channel.
1057 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1058 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1059 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1060 user_channel_id: u128,
1061 /// The `node_id` of the channel counterparty.
1062 counterparty_node_id: PublicKey,
1063 /// The features that this channel will operate with.
1064 channel_type: ChannelTypeFeatures,
1066 /// Used to indicate that a channel that got past the initial handshake with the given `channel_id` is in the
1067 /// process of closure. This includes previously opened channels, and channels that time out from not being funded.
1069 /// Note that this event is only triggered for accepted channels: if the
1070 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true and the channel is
1071 /// rejected, no `ChannelClosed` event will be sent.
1073 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1074 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1076 /// The `channel_id` of the channel which has been closed. Note that on-chain transactions
1077 /// resolving the channel are likely still awaiting confirmation.
1078 channel_id: ChannelId,
1079 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1080 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1081 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1082 /// `user_channel_id` will be randomized for inbound channels.
1083 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
1084 /// zero for objects serialized with LDK versions prior to 0.0.102.
1086 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1087 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1088 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1089 user_channel_id: u128,
1090 /// The reason the channel was closed.
1091 reason: ClosureReason,
1092 /// Counterparty in the closed channel.
1094 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
1095 counterparty_node_id: Option<PublicKey>,
1096 /// Channel capacity of the closing channel (sats).
1098 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
1099 channel_capacity_sats: Option<u64>,
1100 /// The original channel funding TXO; this helps checking for the existence and confirmation
1101 /// status of the closing tx.
1102 /// Note that for instances serialized in v0.0.119 or prior this will be missing (None).
1103 channel_funding_txo: Option<transaction::OutPoint>,
1105 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
1106 /// inputs for another purpose.
1108 /// This event is not guaranteed to be generated for channels that are closed due to a restart.
1110 /// The channel_id of the channel which has been closed.
1111 channel_id: ChannelId,
1112 /// The full transaction received from the user
1113 transaction: Transaction
1115 /// Indicates a request to open a new channel by a peer.
1117 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the request,
1118 /// call [`ChannelManager::force_close_without_broadcasting_txn`]. Note that a ['ChannelClosed`]
1119 /// event will _not_ be triggered if the channel is rejected.
1121 /// The event is only triggered when a new open channel request is received and the
1122 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
1124 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1125 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1126 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1127 OpenChannelRequest {
1128 /// The temporary channel ID of the channel requested to be opened.
1130 /// When responding to the request, the `temporary_channel_id` should be passed
1131 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
1132 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
1134 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1135 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1136 temporary_channel_id: ChannelId,
1137 /// The node_id of the counterparty requesting to open the channel.
1139 /// When responding to the request, the `counterparty_node_id` should be passed
1140 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
1141 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
1144 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1145 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1146 counterparty_node_id: PublicKey,
1147 /// The channel value of the requested channel.
1148 funding_satoshis: u64,
1149 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
1151 /// The features that this channel will operate with. If you reject the channel, a
1152 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
1155 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
1156 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1159 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
1160 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1161 /// 0.0.107. Channels setting this type also need to get manually accepted via
1162 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
1163 /// or will be rejected otherwise.
1165 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1166 channel_type: ChannelTypeFeatures,
1168 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
1171 /// Some scenarios where this event may be sent include:
1172 /// * Insufficient capacity in the outbound channel
1173 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
1174 /// * When an unknown SCID is requested for forwarding a payment.
1175 /// * Expected MPP amount has already been reached
1176 /// * The HTLC has timed out
1178 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
1179 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
1180 HTLCHandlingFailed {
1181 /// The channel over which the HTLC was received.
1182 prev_channel_id: ChannelId,
1183 /// Destination of the HTLC that failed to be processed.
1184 failed_next_destination: HTLCDestination,
1186 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
1187 /// requires confirmed external funds to be readily available to spend.
1189 /// LDK does not currently generate this event unless the
1190 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`] config flag is set to true.
1191 /// It is limited to the scope of channels with anchor outputs.
1193 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`]: crate::util::config::ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx
1194 BumpTransaction(BumpTransactionEvent),
1195 /// We received an onion message that is intended to be forwarded to a peer
1196 /// that is currently offline. This event will only be generated if the
1197 /// `OnionMessenger` was initialized with
1198 /// [`OnionMessenger::new_with_offline_peer_interception`], see its docs.
1200 /// [`OnionMessenger::new_with_offline_peer_interception`]: crate::onion_message::messenger::OnionMessenger::new_with_offline_peer_interception
1201 OnionMessageIntercepted {
1202 /// The node id of the offline peer.
1203 peer_node_id: PublicKey,
1204 /// The onion message intended to be forwarded to `peer_node_id`.
1205 message: msgs::OnionMessage,
1207 /// Indicates that an onion message supporting peer has come online and it may
1208 /// be time to forward any onion messages that were previously intercepted for
1209 /// them. This event will only be generated if the `OnionMessenger` was
1210 /// initialized with
1211 /// [`OnionMessenger::new_with_offline_peer_interception`], see its docs.
1213 /// [`OnionMessenger::new_with_offline_peer_interception`]: crate::onion_message::messenger::OnionMessenger::new_with_offline_peer_interception
1214 OnionMessagePeerConnected {
1215 /// The node id of the peer we just connected to, who advertises support for
1217 peer_node_id: PublicKey,
1221 impl Writeable for Event {
1222 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1224 &Event::FundingGenerationReady { .. } => {
1226 // We never write out FundingGenerationReady events as, upon disconnection, peers
1227 // drop any channels which have not yet exchanged funding_signed.
1229 &Event::PaymentClaimable { ref payment_hash, ref amount_msat, counterparty_skimmed_fee_msat,
1230 ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id,
1231 ref claim_deadline, ref onion_fields
1234 let mut payment_secret = None;
1235 let payment_preimage;
1236 let mut payment_context = None;
1238 PaymentPurpose::Bolt11InvoicePayment {
1239 payment_preimage: preimage, payment_secret: secret
1241 payment_secret = Some(secret);
1242 payment_preimage = *preimage;
1244 PaymentPurpose::Bolt12OfferPayment {
1245 payment_preimage: preimage, payment_secret: secret, payment_context: context
1247 payment_secret = Some(secret);
1248 payment_preimage = *preimage;
1249 payment_context = Some(PaymentContextRef::Bolt12Offer(context));
1251 PaymentPurpose::Bolt12RefundPayment {
1252 payment_preimage: preimage, payment_secret: secret, payment_context: context
1254 payment_secret = Some(secret);
1255 payment_preimage = *preimage;
1256 payment_context = Some(PaymentContextRef::Bolt12Refund(context));
1258 PaymentPurpose::SpontaneousPayment(preimage) => {
1259 payment_preimage = Some(*preimage);
1262 let skimmed_fee_opt = if counterparty_skimmed_fee_msat == 0 { None }
1263 else { Some(counterparty_skimmed_fee_msat) };
1264 write_tlv_fields!(writer, {
1265 (0, payment_hash, required),
1266 (1, receiver_node_id, option),
1267 (2, payment_secret, option),
1268 (3, via_channel_id, option),
1269 (4, amount_msat, required),
1270 (5, via_user_channel_id, option),
1271 // Type 6 was `user_payment_id` on 0.0.103 and earlier
1272 (7, claim_deadline, option),
1273 (8, payment_preimage, option),
1274 (9, onion_fields, option),
1275 (10, skimmed_fee_opt, option),
1276 (11, payment_context, option),
1279 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
1281 write_tlv_fields!(writer, {
1282 (0, payment_preimage, required),
1283 (1, payment_hash, required),
1284 (3, payment_id, option),
1285 (5, fee_paid_msat, option),
1288 &Event::PaymentPathFailed {
1289 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
1290 ref path, ref short_channel_id,
1298 error_code.write(writer)?;
1300 error_data.write(writer)?;
1301 write_tlv_fields!(writer, {
1302 (0, payment_hash, required),
1303 (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
1304 (2, payment_failed_permanently, required),
1305 (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
1306 (4, path.blinded_tail, option),
1307 (5, path.hops, required_vec),
1308 (7, short_channel_id, option),
1309 (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
1310 (11, payment_id, option),
1311 (13, failure, required),
1314 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
1316 // Note that we now ignore these on the read end as we'll re-generate them in
1317 // ChannelManager, we write them here only for backwards compatibility.
1319 &Event::SpendableOutputs { ref outputs, channel_id } => {
1321 write_tlv_fields!(writer, {
1322 (0, WithoutLength(outputs), required),
1323 (1, channel_id, option),
1326 &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1328 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1329 write_tlv_fields!(writer, {
1330 (0, intercept_id, required),
1331 (2, intercept_scid, required),
1332 (4, payment_hash, required),
1333 (6, inbound_amount_msat, required),
1334 (8, expected_outbound_amount_msat, required),
1337 &Event::PaymentForwarded {
1338 prev_channel_id, next_channel_id, prev_user_channel_id, next_user_channel_id,
1339 total_fee_earned_msat, skimmed_fee_msat, claim_from_onchain_tx,
1340 outbound_amount_forwarded_msat,
1343 write_tlv_fields!(writer, {
1344 (0, total_fee_earned_msat, option),
1345 (1, prev_channel_id, option),
1346 (2, claim_from_onchain_tx, required),
1347 (3, next_channel_id, option),
1348 (5, outbound_amount_forwarded_msat, option),
1349 (7, skimmed_fee_msat, option),
1350 (9, prev_user_channel_id, option),
1351 (11, next_user_channel_id, option),
1354 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason,
1355 ref counterparty_node_id, ref channel_capacity_sats, ref channel_funding_txo
1358 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1359 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1360 // separate u64 values.
1361 let user_channel_id_low = *user_channel_id as u64;
1362 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1363 write_tlv_fields!(writer, {
1364 (0, channel_id, required),
1365 (1, user_channel_id_low, required),
1366 (2, reason, required),
1367 (3, user_channel_id_high, required),
1368 (5, counterparty_node_id, option),
1369 (7, channel_capacity_sats, option),
1370 (9, channel_funding_txo, option),
1373 &Event::DiscardFunding { ref channel_id, ref transaction } => {
1374 11u8.write(writer)?;
1375 write_tlv_fields!(writer, {
1376 (0, channel_id, required),
1377 (2, transaction, required)
1380 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1381 13u8.write(writer)?;
1382 write_tlv_fields!(writer, {
1383 (0, payment_id, required),
1384 (2, payment_hash, option),
1385 (4, path.hops, required_vec),
1386 (6, path.blinded_tail, option),
1389 &Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
1390 15u8.write(writer)?;
1391 write_tlv_fields!(writer, {
1392 (0, payment_id, required),
1393 (1, reason, option),
1394 (2, payment_hash, required),
1397 &Event::OpenChannelRequest { .. } => {
1398 17u8.write(writer)?;
1399 // We never write the OpenChannelRequest events as, upon disconnection, peers
1400 // drop any channels which have not yet exchanged funding_signed.
1402 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref htlcs, ref sender_intended_total_msat, ref onion_fields } => {
1403 19u8.write(writer)?;
1404 write_tlv_fields!(writer, {
1405 (0, payment_hash, required),
1406 (1, receiver_node_id, option),
1407 (2, purpose, required),
1408 (4, amount_msat, required),
1409 (5, *htlcs, optional_vec),
1410 (7, sender_intended_total_msat, option),
1411 (9, onion_fields, option),
1414 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1415 21u8.write(writer)?;
1416 write_tlv_fields!(writer, {
1417 (0, payment_id, required),
1418 (2, payment_hash, required),
1419 (4, path.hops, required_vec),
1420 (6, path.blinded_tail, option),
1423 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1424 23u8.write(writer)?;
1425 write_tlv_fields!(writer, {
1426 (0, payment_id, required),
1427 (2, payment_hash, required),
1428 (4, path.hops, required_vec),
1429 (6, short_channel_id, option),
1430 (8, path.blinded_tail, option),
1433 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1434 25u8.write(writer)?;
1435 write_tlv_fields!(writer, {
1436 (0, prev_channel_id, required),
1437 (2, failed_next_destination, required),
1440 &Event::BumpTransaction(ref event)=> {
1441 27u8.write(writer)?;
1443 // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1444 // upon restarting anyway if they remain unresolved.
1445 BumpTransactionEvent::ChannelClose { .. } => {}
1446 BumpTransactionEvent::HTLCResolution { .. } => {}
1448 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1450 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1451 29u8.write(writer)?;
1452 write_tlv_fields!(writer, {
1453 (0, channel_id, required),
1454 (2, user_channel_id, required),
1455 (4, counterparty_node_id, required),
1456 (6, channel_type, required),
1459 &Event::ChannelPending { ref channel_id, ref user_channel_id,
1460 ref former_temporary_channel_id, ref counterparty_node_id, ref funding_txo,
1463 31u8.write(writer)?;
1464 write_tlv_fields!(writer, {
1465 (0, channel_id, required),
1466 (1, channel_type, option),
1467 (2, user_channel_id, required),
1468 (4, former_temporary_channel_id, required),
1469 (6, counterparty_node_id, required),
1470 (8, funding_txo, required),
1473 &Event::InvoiceRequestFailed { ref payment_id } => {
1474 33u8.write(writer)?;
1475 write_tlv_fields!(writer, {
1476 (0, payment_id, required),
1479 &Event::ConnectionNeeded { .. } => {
1480 35u8.write(writer)?;
1481 // Never write ConnectionNeeded events as buffered onion messages aren't serialized.
1483 &Event::OnionMessageIntercepted { ref peer_node_id, ref message } => {
1484 37u8.write(writer)?;
1485 write_tlv_fields!(writer, {
1486 (0, peer_node_id, required),
1487 (2, message, required),
1490 &Event::OnionMessagePeerConnected { ref peer_node_id } => {
1491 39u8.write(writer)?;
1492 write_tlv_fields!(writer, {
1493 (0, peer_node_id, required),
1496 // Note that, going forward, all new events must only write data inside of
1497 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1498 // data via `write_tlv_fields`.
1503 impl MaybeReadable for Event {
1504 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1505 match Readable::read(reader)? {
1506 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events.
1510 let mut payment_hash = PaymentHash([0; 32]);
1511 let mut payment_preimage = None;
1512 let mut payment_secret = None;
1513 let mut amount_msat = 0;
1514 let mut counterparty_skimmed_fee_msat_opt = None;
1515 let mut receiver_node_id = None;
1516 let mut _user_payment_id = None::<u64>; // Used in 0.0.103 and earlier, no longer written in 0.0.116+.
1517 let mut via_channel_id = None;
1518 let mut claim_deadline = None;
1519 let mut via_user_channel_id = None;
1520 let mut onion_fields = None;
1521 let mut payment_context = None;
1522 read_tlv_fields!(reader, {
1523 (0, payment_hash, required),
1524 (1, receiver_node_id, option),
1525 (2, payment_secret, option),
1526 (3, via_channel_id, option),
1527 (4, amount_msat, required),
1528 (5, via_user_channel_id, option),
1529 (6, _user_payment_id, option),
1530 (7, claim_deadline, option),
1531 (8, payment_preimage, option),
1532 (9, onion_fields, option),
1533 (10, counterparty_skimmed_fee_msat_opt, option),
1534 (11, payment_context, option),
1536 let purpose = match payment_secret {
1537 Some(secret) => PaymentPurpose::from_parts(payment_preimage, secret, payment_context),
1538 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1539 None => return Err(msgs::DecodeError::InvalidValue),
1541 Ok(Some(Event::PaymentClaimable {
1545 counterparty_skimmed_fee_msat: counterparty_skimmed_fee_msat_opt.unwrap_or(0),
1548 via_user_channel_id,
1557 let mut payment_preimage = PaymentPreimage([0; 32]);
1558 let mut payment_hash = None;
1559 let mut payment_id = None;
1560 let mut fee_paid_msat = None;
1561 read_tlv_fields!(reader, {
1562 (0, payment_preimage, required),
1563 (1, payment_hash, option),
1564 (3, payment_id, option),
1565 (5, fee_paid_msat, option),
1567 if payment_hash.is_none() {
1568 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()));
1570 Ok(Some(Event::PaymentSent {
1573 payment_hash: payment_hash.unwrap(),
1582 let error_code = Readable::read(reader)?;
1584 let error_data = Readable::read(reader)?;
1585 let mut payment_hash = PaymentHash([0; 32]);
1586 let mut payment_failed_permanently = false;
1587 let mut network_update = None;
1588 let mut blinded_tail: Option<BlindedTail> = None;
1589 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1590 let mut short_channel_id = None;
1591 let mut payment_id = None;
1592 let mut failure_opt = None;
1593 read_tlv_fields!(reader, {
1594 (0, payment_hash, required),
1595 (1, network_update, upgradable_option),
1596 (2, payment_failed_permanently, required),
1597 (4, blinded_tail, option),
1598 // Added as a part of LDK 0.0.101 and always filled in since.
1599 // Defaults to an empty Vec, though likely should have been `Option`al.
1600 (5, path, optional_vec),
1601 (7, short_channel_id, option),
1602 (11, payment_id, option),
1603 (13, failure_opt, upgradable_option),
1605 let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1606 Ok(Some(Event::PaymentPathFailed {
1609 payment_failed_permanently,
1611 path: Path { hops: path.unwrap(), blinded_tail },
1624 let mut outputs = WithoutLength(Vec::new());
1625 let mut channel_id: Option<ChannelId> = None;
1626 read_tlv_fields!(reader, {
1627 (0, outputs, required),
1628 (1, channel_id, option),
1630 Ok(Some(Event::SpendableOutputs { outputs: outputs.0, channel_id }))
1635 let mut payment_hash = PaymentHash([0; 32]);
1636 let mut intercept_id = InterceptId([0; 32]);
1637 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1638 let mut inbound_amount_msat = 0;
1639 let mut expected_outbound_amount_msat = 0;
1640 read_tlv_fields!(reader, {
1641 (0, intercept_id, required),
1642 (2, requested_next_hop_scid, required),
1643 (4, payment_hash, required),
1644 (6, inbound_amount_msat, required),
1645 (8, expected_outbound_amount_msat, required),
1647 let next_scid = match requested_next_hop_scid {
1648 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1650 Ok(Some(Event::HTLCIntercepted {
1652 requested_next_hop_scid: next_scid,
1653 inbound_amount_msat,
1654 expected_outbound_amount_msat,
1660 let mut prev_channel_id = None;
1661 let mut next_channel_id = None;
1662 let mut prev_user_channel_id = None;
1663 let mut next_user_channel_id = None;
1664 let mut total_fee_earned_msat = None;
1665 let mut skimmed_fee_msat = None;
1666 let mut claim_from_onchain_tx = false;
1667 let mut outbound_amount_forwarded_msat = None;
1668 read_tlv_fields!(reader, {
1669 (0, total_fee_earned_msat, option),
1670 (1, prev_channel_id, option),
1671 (2, claim_from_onchain_tx, required),
1672 (3, next_channel_id, option),
1673 (5, outbound_amount_forwarded_msat, option),
1674 (7, skimmed_fee_msat, option),
1675 (9, prev_user_channel_id, option),
1676 (11, next_user_channel_id, option),
1678 Ok(Some(Event::PaymentForwarded {
1679 prev_channel_id, next_channel_id, prev_user_channel_id,
1680 next_user_channel_id, total_fee_earned_msat, skimmed_fee_msat,
1681 claim_from_onchain_tx, outbound_amount_forwarded_msat,
1688 let mut channel_id = ChannelId::new_zero();
1689 let mut reason = UpgradableRequired(None);
1690 let mut user_channel_id_low_opt: Option<u64> = None;
1691 let mut user_channel_id_high_opt: Option<u64> = None;
1692 let mut counterparty_node_id = None;
1693 let mut channel_capacity_sats = None;
1694 let mut channel_funding_txo = None;
1695 read_tlv_fields!(reader, {
1696 (0, channel_id, required),
1697 (1, user_channel_id_low_opt, option),
1698 (2, reason, upgradable_required),
1699 (3, user_channel_id_high_opt, option),
1700 (5, counterparty_node_id, option),
1701 (7, channel_capacity_sats, option),
1702 (9, channel_funding_txo, option),
1705 // `user_channel_id` used to be a single u64 value. In order to remain
1706 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1707 // as two separate u64 values.
1708 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1709 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1711 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required),
1712 counterparty_node_id, channel_capacity_sats, channel_funding_txo }))
1718 let mut channel_id = ChannelId::new_zero();
1719 let mut transaction = Transaction{ version: Version::TWO, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
1720 read_tlv_fields!(reader, {
1721 (0, channel_id, required),
1722 (2, transaction, required),
1724 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1730 _init_and_read_len_prefixed_tlv_fields!(reader, {
1731 (0, payment_id, required),
1732 (2, payment_hash, option),
1733 (4, path, required_vec),
1734 (6, blinded_tail, option),
1736 Ok(Some(Event::PaymentPathSuccessful {
1737 payment_id: payment_id.0.unwrap(),
1739 path: Path { hops: path, blinded_tail },
1746 let mut payment_hash = PaymentHash([0; 32]);
1747 let mut payment_id = PaymentId([0; 32]);
1748 let mut reason = None;
1749 read_tlv_fields!(reader, {
1750 (0, payment_id, required),
1751 (1, reason, upgradable_option),
1752 (2, payment_hash, required),
1754 Ok(Some(Event::PaymentFailed {
1763 // Value 17 is used for `Event::OpenChannelRequest`.
1768 let mut payment_hash = PaymentHash([0; 32]);
1769 let mut purpose = UpgradableRequired(None);
1770 let mut amount_msat = 0;
1771 let mut receiver_node_id = None;
1772 let mut htlcs: Option<Vec<ClaimedHTLC>> = Some(vec![]);
1773 let mut sender_intended_total_msat: Option<u64> = None;
1774 let mut onion_fields = None;
1775 read_tlv_fields!(reader, {
1776 (0, payment_hash, required),
1777 (1, receiver_node_id, option),
1778 (2, purpose, upgradable_required),
1779 (4, amount_msat, required),
1780 (5, htlcs, optional_vec),
1781 (7, sender_intended_total_msat, option),
1782 (9, onion_fields, option),
1784 Ok(Some(Event::PaymentClaimed {
1787 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1789 htlcs: htlcs.unwrap_or(vec![]),
1790 sender_intended_total_msat,
1798 _init_and_read_len_prefixed_tlv_fields!(reader, {
1799 (0, payment_id, required),
1800 (2, payment_hash, required),
1801 (4, path, required_vec),
1802 (6, blinded_tail, option),
1804 Ok(Some(Event::ProbeSuccessful {
1805 payment_id: payment_id.0.unwrap(),
1806 payment_hash: payment_hash.0.unwrap(),
1807 path: Path { hops: path, blinded_tail },
1814 _init_and_read_len_prefixed_tlv_fields!(reader, {
1815 (0, payment_id, required),
1816 (2, payment_hash, required),
1817 (4, path, required_vec),
1818 (6, short_channel_id, option),
1819 (8, blinded_tail, option),
1821 Ok(Some(Event::ProbeFailed {
1822 payment_id: payment_id.0.unwrap(),
1823 payment_hash: payment_hash.0.unwrap(),
1824 path: Path { hops: path, blinded_tail },
1832 let mut prev_channel_id = ChannelId::new_zero();
1833 let mut failed_next_destination_opt = UpgradableRequired(None);
1834 read_tlv_fields!(reader, {
1835 (0, prev_channel_id, required),
1836 (2, failed_next_destination_opt, upgradable_required),
1838 Ok(Some(Event::HTLCHandlingFailed {
1840 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1848 let mut channel_id = ChannelId::new_zero();
1849 let mut user_channel_id: u128 = 0;
1850 let mut counterparty_node_id = RequiredWrapper(None);
1851 let mut channel_type = RequiredWrapper(None);
1852 read_tlv_fields!(reader, {
1853 (0, channel_id, required),
1854 (2, user_channel_id, required),
1855 (4, counterparty_node_id, required),
1856 (6, channel_type, required),
1859 Ok(Some(Event::ChannelReady {
1862 counterparty_node_id: counterparty_node_id.0.unwrap(),
1863 channel_type: channel_type.0.unwrap()
1870 let mut channel_id = ChannelId::new_zero();
1871 let mut user_channel_id: u128 = 0;
1872 let mut former_temporary_channel_id = None;
1873 let mut counterparty_node_id = RequiredWrapper(None);
1874 let mut funding_txo = RequiredWrapper(None);
1875 let mut channel_type = None;
1876 read_tlv_fields!(reader, {
1877 (0, channel_id, required),
1878 (1, channel_type, option),
1879 (2, user_channel_id, required),
1880 (4, former_temporary_channel_id, required),
1881 (6, counterparty_node_id, required),
1882 (8, funding_txo, required),
1885 Ok(Some(Event::ChannelPending {
1888 former_temporary_channel_id,
1889 counterparty_node_id: counterparty_node_id.0.unwrap(),
1890 funding_txo: funding_txo.0.unwrap(),
1898 _init_and_read_len_prefixed_tlv_fields!(reader, {
1899 (0, payment_id, required),
1901 Ok(Some(Event::InvoiceRequestFailed {
1902 payment_id: payment_id.0.unwrap(),
1907 // Note that we do not write a length-prefixed TLV for ConnectionNeeded events.
1911 _init_and_read_len_prefixed_tlv_fields!(reader, {
1912 (0, peer_node_id, required),
1913 (2, message, required),
1915 Ok(Some(Event::OnionMessageIntercepted {
1916 peer_node_id: peer_node_id.0.unwrap(), message: message.0.unwrap()
1923 _init_and_read_len_prefixed_tlv_fields!(reader, {
1924 (0, peer_node_id, required),
1926 Ok(Some(Event::OnionMessagePeerConnected {
1927 peer_node_id: peer_node_id.0.unwrap()
1932 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1933 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1935 x if x % 2 == 1 => {
1936 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1937 // which prefixes the whole thing with a length BigSize. Because the event is
1938 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1939 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1940 // exactly the number of bytes specified, ignoring them entirely.
1941 let tlv_len: BigSize = Readable::read(reader)?;
1942 FixedLengthReader::new(reader, tlv_len.0)
1943 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1946 _ => Err(msgs::DecodeError::InvalidValue)
1951 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1952 /// broadcast to most peers).
1953 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1954 #[derive(Clone, Debug)]
1955 #[cfg_attr(test, derive(PartialEq))]
1956 pub enum MessageSendEvent {
1957 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1958 /// message provided to the given peer.
1960 /// The node_id of the node which should receive this message
1962 /// The message which should be sent.
1963 msg: msgs::AcceptChannel,
1965 /// Used to indicate that we've accepted a V2 channel open and should send the accept_channel2
1966 /// message provided to the given peer.
1967 SendAcceptChannelV2 {
1968 /// The node_id of the node which should receive this message
1970 /// The message which should be sent.
1971 msg: msgs::AcceptChannelV2,
1973 /// Used to indicate that we've initiated a channel open and should send the open_channel
1974 /// message provided to the given peer.
1976 /// The node_id of the node which should receive this message
1978 /// The message which should be sent.
1979 msg: msgs::OpenChannel,
1981 /// Used to indicate that we've initiated a V2 channel open and should send the open_channel2
1982 /// message provided to the given peer.
1984 /// The node_id of the node which should receive this message
1986 /// The message which should be sent.
1987 msg: msgs::OpenChannelV2,
1989 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1990 SendFundingCreated {
1991 /// The node_id of the node which should receive this message
1993 /// The message which should be sent.
1994 msg: msgs::FundingCreated,
1996 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1998 /// The node_id of the node which should receive this message
2000 /// The message which should be sent.
2001 msg: msgs::FundingSigned,
2003 /// Used to indicate that a stfu message should be sent to the peer with the given node id.
2005 /// The node_id of the node which should receive this message
2007 /// The message which should be sent.
2010 /// Used to indicate that a splice message should be sent to the peer with the given node id.
2012 /// The node_id of the node which should receive this message
2014 /// The message which should be sent.
2017 /// Used to indicate that a splice_ack message should be sent to the peer with the given node id.
2019 /// The node_id of the node which should receive this message
2021 /// The message which should be sent.
2022 msg: msgs::SpliceAck,
2024 /// Used to indicate that a splice_locked message should be sent to the peer with the given node id.
2026 /// The node_id of the node which should receive this message
2028 /// The message which should be sent.
2029 msg: msgs::SpliceLocked,
2031 /// Used to indicate that a tx_add_input message should be sent to the peer with the given node_id.
2033 /// The node_id of the node which should receive this message
2035 /// The message which should be sent.
2036 msg: msgs::TxAddInput,
2038 /// Used to indicate that a tx_add_output message should be sent to the peer with the given node_id.
2040 /// The node_id of the node which should receive this message
2042 /// The message which should be sent.
2043 msg: msgs::TxAddOutput,
2045 /// Used to indicate that a tx_remove_input message should be sent to the peer with the given node_id.
2047 /// The node_id of the node which should receive this message
2049 /// The message which should be sent.
2050 msg: msgs::TxRemoveInput,
2052 /// Used to indicate that a tx_remove_output message should be sent to the peer with the given node_id.
2053 SendTxRemoveOutput {
2054 /// The node_id of the node which should receive this message
2056 /// The message which should be sent.
2057 msg: msgs::TxRemoveOutput,
2059 /// Used to indicate that a tx_complete message should be sent to the peer with the given node_id.
2061 /// The node_id of the node which should receive this message
2063 /// The message which should be sent.
2064 msg: msgs::TxComplete,
2066 /// Used to indicate that a tx_signatures message should be sent to the peer with the given node_id.
2068 /// The node_id of the node which should receive this message
2070 /// The message which should be sent.
2071 msg: msgs::TxSignatures,
2073 /// Used to indicate that a tx_init_rbf message should be sent to the peer with the given node_id.
2075 /// The node_id of the node which should receive this message
2077 /// The message which should be sent.
2078 msg: msgs::TxInitRbf,
2080 /// Used to indicate that a tx_ack_rbf message should be sent to the peer with the given node_id.
2082 /// The node_id of the node which should receive this message
2084 /// The message which should be sent.
2085 msg: msgs::TxAckRbf,
2087 /// Used to indicate that a tx_abort message should be sent to the peer with the given node_id.
2089 /// The node_id of the node which should receive this message
2091 /// The message which should be sent.
2094 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
2096 /// The node_id of the node which should receive these message(s)
2098 /// The channel_ready message which should be sent.
2099 msg: msgs::ChannelReady,
2101 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
2102 SendAnnouncementSignatures {
2103 /// The node_id of the node which should receive these message(s)
2105 /// The announcement_signatures message which should be sent.
2106 msg: msgs::AnnouncementSignatures,
2108 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
2109 /// message should be sent to the peer with the given node_id.
2111 /// The node_id of the node which should receive these message(s)
2113 /// The update messages which should be sent. ALL messages in the struct should be sent!
2114 updates: msgs::CommitmentUpdate,
2116 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
2118 /// The node_id of the node which should receive this message
2120 /// The message which should be sent.
2121 msg: msgs::RevokeAndACK,
2123 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
2125 /// The node_id of the node which should receive this message
2127 /// The message which should be sent.
2128 msg: msgs::ClosingSigned,
2130 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
2132 /// The node_id of the node which should receive this message
2134 /// The message which should be sent.
2135 msg: msgs::Shutdown,
2137 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
2138 SendChannelReestablish {
2139 /// The node_id of the node which should receive this message
2141 /// The message which should be sent.
2142 msg: msgs::ChannelReestablish,
2144 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
2145 /// initial connection to ensure our peers know about our channels.
2146 SendChannelAnnouncement {
2147 /// The node_id of the node which should receive this message
2149 /// The channel_announcement which should be sent.
2150 msg: msgs::ChannelAnnouncement,
2151 /// The followup channel_update which should be sent.
2152 update_msg: msgs::ChannelUpdate,
2154 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
2155 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
2157 /// Note that after doing so, you very likely (unless you did so very recently) want to
2158 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
2159 /// ensures that any nodes which see our channel_announcement also have a relevant
2160 /// node_announcement, including relevant feature flags which may be important for routing
2161 /// through or to us.
2163 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
2164 BroadcastChannelAnnouncement {
2165 /// The channel_announcement which should be sent.
2166 msg: msgs::ChannelAnnouncement,
2167 /// The followup channel_update which should be sent.
2168 update_msg: Option<msgs::ChannelUpdate>,
2170 /// Used to indicate that a channel_update should be broadcast to all peers.
2171 BroadcastChannelUpdate {
2172 /// The channel_update which should be sent.
2173 msg: msgs::ChannelUpdate,
2175 /// Used to indicate that a node_announcement should be broadcast to all peers.
2176 BroadcastNodeAnnouncement {
2177 /// The node_announcement which should be sent.
2178 msg: msgs::NodeAnnouncement,
2180 /// Used to indicate that a channel_update should be sent to a single peer.
2181 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
2182 /// private channel and we shouldn't be informing all of our peers of channel parameters.
2184 /// The node_id of the node which should receive this message
2186 /// The channel_update which should be sent.
2187 msg: msgs::ChannelUpdate,
2189 /// Broadcast an error downstream to be handled
2191 /// The node_id of the node which should receive this message
2193 /// The action which should be taken.
2194 action: msgs::ErrorAction
2196 /// Query a peer for channels with funding transaction UTXOs in a block range.
2197 SendChannelRangeQuery {
2198 /// The node_id of this message recipient
2200 /// The query_channel_range which should be sent.
2201 msg: msgs::QueryChannelRange,
2203 /// Request routing gossip messages from a peer for a list of channels identified by
2204 /// their short_channel_ids.
2206 /// The node_id of this message recipient
2208 /// The query_short_channel_ids which should be sent.
2209 msg: msgs::QueryShortChannelIds,
2211 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
2212 /// emitted during processing of the query.
2213 SendReplyChannelRange {
2214 /// The node_id of this message recipient
2216 /// The reply_channel_range which should be sent.
2217 msg: msgs::ReplyChannelRange,
2219 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
2220 /// enable receiving gossip messages from the peer.
2221 SendGossipTimestampFilter {
2222 /// The node_id of this message recipient
2224 /// The gossip_timestamp_filter which should be sent.
2225 msg: msgs::GossipTimestampFilter,
2229 /// A trait indicating an object may generate message send events
2230 pub trait MessageSendEventsProvider {
2231 /// Gets the list of pending events which were generated by previous actions, clearing the list
2233 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
2236 /// A trait indicating an object may generate events.
2238 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
2240 /// Implementations of this trait may also feature an async version of event handling, as shown with
2241 /// [`ChannelManager::process_pending_events_async`] and
2242 /// [`ChainMonitor::process_pending_events_async`].
2246 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
2247 /// event since the last invocation.
2249 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
2250 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
2251 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
2252 /// relevant changes to disk *before* returning.
2254 /// Further, because an application may crash between an [`Event`] being handled and the
2255 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
2256 /// effect, [`Event`]s may be replayed.
2258 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
2259 /// consult the provider's documentation on the implication of processing events and how a handler
2260 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
2261 /// [`ChainMonitor::process_pending_events`]).
2263 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
2266 /// [`process_pending_events`]: Self::process_pending_events
2267 /// [`handle_event`]: EventHandler::handle_event
2268 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
2269 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
2270 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
2271 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
2272 pub trait EventsProvider {
2273 /// Processes any events generated since the last call using the given event handler.
2275 /// See the trait-level documentation for requirements.
2276 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
2279 /// A trait implemented for objects handling events from [`EventsProvider`].
2281 /// An async variation also exists for implementations of [`EventsProvider`] that support async
2282 /// event handling. The async event handler should satisfy the generic bounds: `F:
2283 /// core::future::Future, H: Fn(Event) -> F`.
2284 pub trait EventHandler {
2285 /// Handles the given [`Event`].
2287 /// See [`EventsProvider`] for details that must be considered when implementing this method.
2288 fn handle_event(&self, event: Event);
2291 impl<F> EventHandler for F where F: Fn(Event) {
2292 fn handle_event(&self, event: Event) {
2297 impl<T: EventHandler> EventHandler for Arc<T> {
2298 fn handle_event(&self, event: Event) {
2299 self.deref().handle_event(event)