1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Events are returned from various bits in the library which indicate some action must be taken
13 //! Because we don't have a built-in runtime, it's up to the client to call events at a time in the
14 //! future, as well as generate and broadcast funding transactions handle payment preimages and a
17 pub mod bump_transaction;
19 pub use bump_transaction::BumpTransactionEvent;
21 use crate::blinded_path::payment::{Bolt12OfferContext, Bolt12RefundContext, PaymentContext, PaymentContextRef};
22 use crate::sign::SpendableOutputDescriptor;
23 use crate::ln::channelmanager::{InterceptId, PaymentId, RecipientOnionFields};
24 use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
25 use crate::ln::features::ChannelTypeFeatures;
27 use crate::ln::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
28 use crate::chain::transaction;
29 use crate::routing::gossip::NetworkUpdate;
30 use crate::util::errors::APIError;
31 use crate::util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, RequiredWrapper, UpgradableRequired, WithoutLength};
32 use crate::util::string::UntrustedString;
33 use crate::routing::router::{BlindedTail, Path, RouteHop, RouteParameters};
35 use bitcoin::{Transaction, OutPoint};
36 use bitcoin::blockdata::locktime::absolute::LockTime;
37 use bitcoin::blockdata::script::ScriptBuf;
38 use bitcoin::hashes::Hash;
39 use bitcoin::hashes::sha256::Hash as Sha256;
40 use bitcoin::secp256k1::PublicKey;
42 use core::time::Duration;
46 #[allow(unused_imports)]
47 use crate::prelude::*;
49 /// Some information provided on receipt of payment depends on whether the payment received is a
50 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
51 #[derive(Clone, Debug, PartialEq, Eq)]
52 pub enum PaymentPurpose {
53 /// A payment for a BOLT 11 invoice.
54 Bolt11InvoicePayment {
55 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
56 /// [`ChannelManager::create_inbound_payment`]. When handling [`Event::PaymentClaimable`],
57 /// this can be passed directly to [`ChannelManager::claim_funds`] to claim the payment. No
58 /// action is needed when seen in [`Event::PaymentClaimed`].
60 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
61 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
62 payment_preimage: Option<PaymentPreimage>,
63 /// The "payment secret". This authenticates the sender to the recipient, preventing a
64 /// number of deanonymization attacks during the routing process.
65 /// It is provided here for your reference, however its accuracy is enforced directly by
66 /// [`ChannelManager`] using the values you previously provided to
67 /// [`ChannelManager::create_inbound_payment`] or
68 /// [`ChannelManager::create_inbound_payment_for_hash`].
70 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
71 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
72 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
73 payment_secret: PaymentSecret,
75 /// A payment for a BOLT 12 [`Offer`].
77 /// [`Offer`]: crate::offers::offer::Offer
79 /// The preimage to the payment hash. When handling [`Event::PaymentClaimable`], this can be
80 /// passed directly to [`ChannelManager::claim_funds`], if provided. No action is needed
81 /// when seen in [`Event::PaymentClaimed`].
83 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
84 payment_preimage: Option<PaymentPreimage>,
85 /// The secret used to authenticate the sender to the recipient, preventing a number of
86 /// de-anonymization attacks while routing a payment.
88 /// See [`PaymentPurpose::Bolt11InvoicePayment::payment_secret`] for further details.
89 payment_secret: PaymentSecret,
90 /// The context of the payment such as information about the corresponding [`Offer`] and
91 /// [`InvoiceRequest`].
93 /// [`Offer`]: crate::offers::offer::Offer
94 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
95 payment_context: Bolt12OfferContext,
97 /// A payment for a BOLT 12 [`Refund`].
99 /// [`Refund`]: crate::offers::refund::Refund
100 Bolt12RefundPayment {
101 /// The preimage to the payment hash. When handling [`Event::PaymentClaimable`], this can be
102 /// passed directly to [`ChannelManager::claim_funds`], if provided. No action is needed
103 /// when seen in [`Event::PaymentClaimed`].
105 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
106 payment_preimage: Option<PaymentPreimage>,
107 /// The secret used to authenticate the sender to the recipient, preventing a number of
108 /// de-anonymization attacks while routing a payment.
110 /// See [`PaymentPurpose::Bolt11InvoicePayment::payment_secret`] for further details.
111 payment_secret: PaymentSecret,
112 /// The context of the payment such as information about the corresponding [`Refund`].
114 /// [`Refund`]: crate::offers::refund::Refund
115 payment_context: Bolt12RefundContext,
117 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
118 /// (the payee) providing a preimage.
119 SpontaneousPayment(PaymentPreimage),
122 impl PaymentPurpose {
123 /// Returns the preimage for this payment, if it is known.
124 pub fn preimage(&self) -> Option<PaymentPreimage> {
126 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, .. } => *payment_preimage,
127 PaymentPurpose::Bolt12OfferPayment { payment_preimage, .. } => *payment_preimage,
128 PaymentPurpose::Bolt12RefundPayment { payment_preimage, .. } => *payment_preimage,
129 PaymentPurpose::SpontaneousPayment(preimage) => Some(*preimage),
133 pub(crate) fn is_keysend(&self) -> bool {
135 PaymentPurpose::Bolt11InvoicePayment { .. } => false,
136 PaymentPurpose::Bolt12OfferPayment { .. } => false,
137 PaymentPurpose::Bolt12RefundPayment { .. } => false,
138 PaymentPurpose::SpontaneousPayment(..) => true,
142 pub(crate) fn from_parts(
143 payment_preimage: Option<PaymentPreimage>, payment_secret: PaymentSecret,
144 payment_context: Option<PaymentContext>,
146 match payment_context {
147 Some(PaymentContext::Unknown(_)) | None => {
148 PaymentPurpose::Bolt11InvoicePayment {
153 Some(PaymentContext::Bolt12Offer(context)) => {
154 PaymentPurpose::Bolt12OfferPayment {
157 payment_context: context,
160 Some(PaymentContext::Bolt12Refund(context)) => {
161 PaymentPurpose::Bolt12RefundPayment {
164 payment_context: context,
171 impl_writeable_tlv_based_enum!(PaymentPurpose,
172 (0, Bolt11InvoicePayment) => {
173 (0, payment_preimage, option),
174 (2, payment_secret, required),
176 (4, Bolt12OfferPayment) => {
177 (0, payment_preimage, option),
178 (2, payment_secret, required),
179 (4, payment_context, required),
181 (6, Bolt12RefundPayment) => {
182 (0, payment_preimage, option),
183 (2, payment_secret, required),
184 (4, payment_context, required),
187 (2, SpontaneousPayment)
190 /// Information about an HTLC that is part of a payment that can be claimed.
191 #[derive(Clone, Debug, PartialEq, Eq)]
192 pub struct ClaimedHTLC {
193 /// The `channel_id` of the channel over which the HTLC was received.
194 pub channel_id: ChannelId,
195 /// The `user_channel_id` of the channel over which the HTLC was received. This is the value
196 /// passed in to [`ChannelManager::create_channel`] for outbound channels, or to
197 /// [`ChannelManager::accept_inbound_channel`] for inbound channels if
198 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
199 /// `user_channel_id` will be randomized for an inbound channel.
201 /// This field will be zero for a payment that was serialized prior to LDK version 0.0.117. (This
202 /// should only happen in the case that a payment was claimable prior to LDK version 0.0.117, but
203 /// was not actually claimed until after upgrading.)
205 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
206 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
207 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
208 pub user_channel_id: u128,
209 /// The block height at which this HTLC expires.
210 pub cltv_expiry: u32,
211 /// The amount (in msats) of this part of an MPP.
213 /// The extra fee our counterparty skimmed off the top of this HTLC, if any.
215 /// This value will always be 0 for [`ClaimedHTLC`]s serialized with LDK versions prior to
217 pub counterparty_skimmed_fee_msat: u64,
219 impl_writeable_tlv_based!(ClaimedHTLC, {
220 (0, channel_id, required),
221 (1, counterparty_skimmed_fee_msat, (default_value, 0u64)),
222 (2, user_channel_id, required),
223 (4, cltv_expiry, required),
224 (6, value_msat, required),
227 /// When the payment path failure took place and extra details about it. [`PathFailure::OnPath`] may
228 /// contain a [`NetworkUpdate`] that needs to be applied to the [`NetworkGraph`].
230 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
231 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
232 #[derive(Clone, Debug, Eq, PartialEq)]
233 pub enum PathFailure {
234 /// We failed to initially send the payment and no HTLC was committed to. Contains the relevant
237 /// The error surfaced from initial send.
240 /// A hop on the path failed to forward our payment.
242 /// If present, this [`NetworkUpdate`] should be applied to the [`NetworkGraph`] so that routing
243 /// decisions can take into account the update.
245 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
246 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
247 network_update: Option<NetworkUpdate>,
251 impl_writeable_tlv_based_enum_upgradable!(PathFailure,
253 (0, network_update, upgradable_option),
255 (2, InitialSend) => {
256 (0, err, upgradable_required),
260 #[derive(Clone, Debug, PartialEq, Eq)]
261 /// The reason the channel was closed. See individual variants for more details.
262 pub enum ClosureReason {
263 /// Closure generated from receiving a peer error message.
265 /// Our counterparty may have broadcasted their latest commitment state, and we have
267 CounterpartyForceClosed {
268 /// The error which the peer sent us.
270 /// Be careful about printing the peer_msg, a well-crafted message could exploit
271 /// a security vulnerability in the terminal emulator or the logging subsystem.
272 /// To be safe, use `Display` on `UntrustedString`
274 /// [`UntrustedString`]: crate::util::string::UntrustedString
275 peer_msg: UntrustedString,
277 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
279 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
281 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
282 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
284 /// This was only set in versions of LDK prior to 0.0.122.
285 // Can be removed once we disallow downgrading to 0.0.121
286 LegacyCooperativeClosure,
287 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
288 /// the cooperative close transaction. This indicates that the shutdown was initiated by our
291 /// In rare cases where we initiated closure immediately prior to shutting down without
292 /// persisting, this value may be provided for channels we initiated closure for.
293 CounterpartyInitiatedCooperativeClosure,
294 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
295 /// the cooperative close transaction. This indicates that the shutdown was initiated by us.
296 LocallyInitiatedCooperativeClosure,
297 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
298 /// commitment transaction came from our counterparty, but it may also have come from
299 /// a copy of our own `ChannelMonitor`.
300 CommitmentTxConfirmed,
301 /// The funding transaction failed to confirm in a timely manner on an inbound channel.
303 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
305 /// A developer-readable error message which we generated.
308 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
309 /// forget the channel entirely - we can attempt again if the peer reconnects.
311 /// This includes cases where we restarted prior to funding completion, including prior to the
312 /// initial [`ChannelMonitor`] persistence completing.
314 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
315 /// peer because of mutual incompatibility between us and our channel counterparty.
317 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
319 /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
320 /// the [`ChannelManager`] deserialized.
322 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
323 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
324 OutdatedChannelManager,
325 /// The counterparty requested a cooperative close of a channel that had not been funded yet.
326 /// The channel has been immediately closed.
327 CounterpartyCoopClosedUnfundedChannel,
328 /// Another channel in the same funding batch closed before the funding transaction
329 /// was ready to be broadcast.
331 /// One of our HTLCs timed out in a channel, causing us to force close the channel.
335 impl core::fmt::Display for ClosureReason {
336 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
337 f.write_str("Channel closed because ")?;
339 ClosureReason::CounterpartyForceClosed { peer_msg } => {
340 f.write_fmt(format_args!("counterparty force-closed with message: {}", peer_msg))
342 ClosureReason::HolderForceClosed => f.write_str("user force-closed the channel"),
343 ClosureReason::LegacyCooperativeClosure => f.write_str("the channel was cooperatively closed"),
344 ClosureReason::CounterpartyInitiatedCooperativeClosure => f.write_str("the channel was cooperatively closed by our peer"),
345 ClosureReason::LocallyInitiatedCooperativeClosure => f.write_str("the channel was cooperatively closed by us"),
346 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
347 ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
348 ClosureReason::ProcessingError { err } => {
349 f.write_str("of an exception: ")?;
352 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
353 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
354 ClosureReason::CounterpartyCoopClosedUnfundedChannel => f.write_str("the peer requested the unfunded channel be closed"),
355 ClosureReason::FundingBatchClosure => f.write_str("another channel in the same funding batch closed"),
356 ClosureReason::HTLCsTimedOut => f.write_str("htlcs on the channel timed out"),
361 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
362 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
363 (1, FundingTimedOut) => {},
364 (2, HolderForceClosed) => {},
365 (6, CommitmentTxConfirmed) => {},
366 (4, LegacyCooperativeClosure) => {},
367 (8, ProcessingError) => { (1, err, required) },
368 (10, DisconnectedPeer) => {},
369 (12, OutdatedChannelManager) => {},
370 (13, CounterpartyCoopClosedUnfundedChannel) => {},
371 (15, FundingBatchClosure) => {},
372 (17, CounterpartyInitiatedCooperativeClosure) => {},
373 (19, LocallyInitiatedCooperativeClosure) => {},
374 (21, HTLCsTimedOut) => {},
377 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
378 #[derive(Clone, Debug, PartialEq, Eq)]
379 pub enum HTLCDestination {
380 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
381 /// there is insufficient capacity in our outbound channel.
383 /// The `node_id` of the next node. For backwards compatibility, this field is
384 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
385 /// counterparty node information.
386 node_id: Option<PublicKey>,
387 /// The outgoing `channel_id` between us and the next node.
388 channel_id: ChannelId,
390 /// Scenario where we are unsure of the next node to forward the HTLC to.
392 /// Short channel id we are requesting to forward an HTLC to.
393 requested_forward_scid: u64,
395 /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
398 /// Short channel id we are requesting to forward an HTLC to.
399 requested_forward_scid: u64
401 /// We couldn't decode the incoming onion to obtain the forwarding details.
403 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
404 /// but is invalid for some reason, so we reject it.
406 /// Some of the reasons may include:
408 /// * Excess HTLCs for a payment that we have already fully received, over-paying for the
410 /// * The counterparty node modified the HTLC in transit,
411 /// * A probing attack where an intermediary node is trying to detect if we are the ultimate
412 /// recipient for a payment.
414 /// The payment hash of the payment we attempted to process.
415 payment_hash: PaymentHash
419 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
420 (0, NextHopChannel) => {
421 (0, node_id, required),
422 (2, channel_id, required),
424 (1, InvalidForward) => {
425 (0, requested_forward_scid, required),
427 (2, UnknownNextHop) => {
428 (0, requested_forward_scid, required),
430 (3, InvalidOnion) => {},
431 (4, FailedPayment) => {
432 (0, payment_hash, required),
436 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
437 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
438 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
439 /// intercepts in upcoming work.
440 enum InterceptNextHop {
442 requested_next_hop_scid: u64,
446 impl_writeable_tlv_based_enum!(InterceptNextHop,
448 (0, requested_next_hop_scid, required),
452 /// The reason the payment failed. Used in [`Event::PaymentFailed`].
453 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
454 pub enum PaymentFailureReason {
455 /// The intended recipient rejected our payment.
457 /// The user chose to abandon this payment by calling [`ChannelManager::abandon_payment`].
459 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
461 /// We exhausted all of our retry attempts while trying to send the payment, or we
462 /// exhausted the [`Retry::Timeout`] if the user set one. If at any point a retry
463 /// attempt failed while being forwarded along the path, an [`Event::PaymentPathFailed`] will
464 /// have come before this.
466 /// [`Retry::Timeout`]: crate::ln::channelmanager::Retry::Timeout
468 /// The payment expired while retrying, based on the provided
469 /// [`PaymentParameters::expiry_time`].
471 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
473 /// We failed to find a route while retrying the payment.
475 /// Note that this generally indicates that we've exhausted the available set of possible
476 /// routes - we tried the payment over a few routes but were not able to find any further
477 /// candidate routes beyond those.
479 /// This error should generally never happen. This likely means that there is a problem with
484 impl_writeable_tlv_based_enum!(PaymentFailureReason,
485 (0, RecipientRejected) => {},
486 (2, UserAbandoned) => {},
487 (4, RetriesExhausted) => {},
488 (6, PaymentExpired) => {},
489 (8, RouteNotFound) => {},
490 (10, UnexpectedError) => {}, ;
493 /// An Event which you should probably take some action in response to.
495 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
496 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
497 /// written as it makes no sense to respond to it after reconnecting to peers).
498 #[derive(Clone, Debug, PartialEq, Eq)]
500 /// Used to indicate that the client should generate a funding transaction with the given
501 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
502 /// Generated in [`ChannelManager`] message handling.
503 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
504 /// counterparty can steal your funds!
506 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
507 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
508 FundingGenerationReady {
509 /// The random channel_id we picked which you'll need to pass into
510 /// [`ChannelManager::funding_transaction_generated`].
512 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
513 temporary_channel_id: ChannelId,
514 /// The counterparty's node_id, which you'll need to pass back into
515 /// [`ChannelManager::funding_transaction_generated`].
517 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
518 counterparty_node_id: PublicKey,
519 /// The value, in satoshis, that the output should have.
520 channel_value_satoshis: u64,
521 /// The script which should be used in the transaction output.
522 output_script: ScriptBuf,
523 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
524 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
525 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
526 /// `user_channel_id` will be randomized for an inbound channel. This may be zero for objects
527 /// serialized with LDK versions prior to 0.0.113.
529 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
530 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
531 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
532 user_channel_id: u128,
534 /// Indicates that we've been offered a payment and it needs to be claimed via calling
535 /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
537 /// Note that if the preimage is not known, you should call
538 /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
539 /// to free up resources for this HTLC and avoid network congestion.
541 /// If [`Event::PaymentClaimable::onion_fields`] is `Some`, and includes custom TLVs with even type
542 /// numbers, you should use [`ChannelManager::fail_htlc_backwards_with_reason`] with
543 /// [`FailureCode::InvalidOnionPayload`] if you fail to understand and handle the contents, or
544 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`] upon successful handling.
545 /// If you don't intend to check for custom TLVs, you can simply use
546 /// [`ChannelManager::claim_funds`], which will automatically fail back even custom TLVs.
548 /// If you fail to call [`ChannelManager::claim_funds`],
549 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`],
550 /// [`ChannelManager::fail_htlc_backwards`], or
551 /// [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will
552 /// be automatically failed.
555 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
556 /// `PaymentClaimable` events may be generated for the same payment. In such a case it is
557 /// polite (and required in the lightning specification) to fail the payment the second time
558 /// and give the sender their money back rather than accepting double payment.
561 /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
563 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
564 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`]: crate::ln::channelmanager::ChannelManager::claim_funds_with_known_custom_tlvs
565 /// [`FailureCode::InvalidOnionPayload`]: crate::ln::channelmanager::FailureCode::InvalidOnionPayload
566 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
567 /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
569 /// The node that will receive the payment after it has been claimed.
570 /// This is useful to identify payments received via [phantom nodes].
571 /// This field will always be filled in when the event was generated by LDK versions
572 /// 0.0.113 and above.
574 /// [phantom nodes]: crate::sign::PhantomKeysManager
575 receiver_node_id: Option<PublicKey>,
576 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
577 /// not stop you from registering duplicate payment hashes for inbound payments.
578 payment_hash: PaymentHash,
579 /// The fields in the onion which were received with each HTLC. Only fields which were
580 /// identical in each HTLC involved in the payment will be included here.
582 /// Payments received on LDK versions prior to 0.0.115 will have this field unset.
583 onion_fields: Option<RecipientOnionFields>,
584 /// The value, in thousandths of a satoshi, that this payment is claimable for. May be greater
585 /// than the invoice amount.
587 /// May be less than the invoice amount if [`ChannelConfig::accept_underpaying_htlcs`] is set
588 /// and the previous hop took an extra fee.
591 /// If [`ChannelConfig::accept_underpaying_htlcs`] is set and you claim without verifying this
592 /// field, you may lose money!
594 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
596 /// The value, in thousands of a satoshi, that was skimmed off of this payment as an extra fee
597 /// taken by our channel counterparty.
599 /// Will always be 0 unless [`ChannelConfig::accept_underpaying_htlcs`] is set.
601 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
602 counterparty_skimmed_fee_msat: u64,
603 /// Information for claiming this received payment, based on whether the purpose of the
604 /// payment is to pay an invoice or to send a spontaneous payment.
605 purpose: PaymentPurpose,
606 /// The `channel_id` indicating over which channel we received the payment.
607 via_channel_id: Option<ChannelId>,
608 /// The `user_channel_id` indicating over which channel we received the payment.
609 via_user_channel_id: Option<u128>,
610 /// The block height at which this payment will be failed back and will no longer be
611 /// eligible for claiming.
613 /// Prior to this height, a call to [`ChannelManager::claim_funds`] is guaranteed to
614 /// succeed, however you should wait for [`Event::PaymentClaimed`] to be sure.
616 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
617 claim_deadline: Option<u32>,
619 /// Indicates a payment has been claimed and we've received money!
621 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
622 /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
623 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
624 /// [`Event::PaymentClaimable`] event.
627 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
628 /// `PaymentClaimable` events may be generated for the same payment. If you then call
629 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
630 /// multiple `PaymentClaimed` events.
632 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
634 /// The node that received the payment.
635 /// This is useful to identify payments which were received via [phantom nodes].
636 /// This field will always be filled in when the event was generated by LDK versions
637 /// 0.0.113 and above.
639 /// [phantom nodes]: crate::sign::PhantomKeysManager
640 receiver_node_id: Option<PublicKey>,
641 /// The payment hash of the claimed payment. Note that LDK will not stop you from
642 /// registering duplicate payment hashes for inbound payments.
643 payment_hash: PaymentHash,
644 /// The value, in thousandths of a satoshi, that this payment is for. May be greater than the
647 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
648 /// spontaneous payment.
649 purpose: PaymentPurpose,
650 /// The HTLCs that comprise the claimed payment. This will be empty for events serialized prior
651 /// to LDK version 0.0.117.
652 htlcs: Vec<ClaimedHTLC>,
653 /// The sender-intended sum total of all the MPP parts. This will be `None` for events
654 /// serialized prior to LDK version 0.0.117.
655 sender_intended_total_msat: Option<u64>,
657 /// Indicates that a peer connection with a node is needed in order to send an [`OnionMessage`].
659 /// Typically, this happens when a [`MessageRouter`] is unable to find a complete path to a
660 /// [`Destination`]. Once a connection is established, any messages buffered by an
661 /// [`OnionMessageHandler`] may be sent.
663 /// This event will not be generated for onion message forwards; only for sends including
664 /// replies. Handlers should connect to the node otherwise any buffered messages may be lost.
666 /// [`OnionMessage`]: msgs::OnionMessage
667 /// [`MessageRouter`]: crate::onion_message::messenger::MessageRouter
668 /// [`Destination`]: crate::onion_message::messenger::Destination
669 /// [`OnionMessageHandler`]: crate::ln::msgs::OnionMessageHandler
671 /// The node id for the node needing a connection.
673 /// Sockets for connecting to the node.
674 addresses: Vec<msgs::SocketAddress>,
676 /// Indicates a request for an invoice failed to yield a response in a reasonable amount of time
677 /// or was explicitly abandoned by [`ChannelManager::abandon_payment`]. This may be for an
678 /// [`InvoiceRequest`] sent for an [`Offer`] or for a [`Refund`] that hasn't been redeemed.
680 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
681 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
682 /// [`Offer`]: crate::offers::offer::Offer
683 /// [`Refund`]: crate::offers::refund::Refund
684 InvoiceRequestFailed {
685 /// The `payment_id` to have been associated with payment for the requested invoice.
686 payment_id: PaymentId,
688 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
689 /// and we got back the payment preimage for it).
691 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
692 /// event. In this situation, you SHOULD treat this payment as having succeeded.
694 /// The `payment_id` passed to [`ChannelManager::send_payment`].
696 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
697 payment_id: Option<PaymentId>,
698 /// The preimage to the hash given to ChannelManager::send_payment.
699 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
700 /// store it somehow!
701 payment_preimage: PaymentPreimage,
702 /// The hash that was given to [`ChannelManager::send_payment`].
704 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
705 payment_hash: PaymentHash,
706 /// The total fee which was spent at intermediate hops in this payment, across all paths.
708 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
709 /// overpayment to the recipient node.
711 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
712 /// overstate the amount paid, though this is unlikely.
714 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
715 fee_paid_msat: Option<u64>,
717 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
718 /// provide failure information for each path attempt in the payment, including retries.
720 /// This event is provided once there are no further pending HTLCs for the payment and the
721 /// payment is no longer retryable, due either to the [`Retry`] provided or
722 /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
724 /// In exceedingly rare cases, it is possible that an [`Event::PaymentFailed`] is generated for
725 /// a payment after an [`Event::PaymentSent`] event for this same payment has already been
726 /// received and processed. In this case, the [`Event::PaymentFailed`] event MUST be ignored,
727 /// and the payment MUST be treated as having succeeded.
729 /// [`Retry`]: crate::ln::channelmanager::Retry
730 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
732 /// The `payment_id` passed to [`ChannelManager::send_payment`].
734 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
735 payment_id: PaymentId,
736 /// The hash that was given to [`ChannelManager::send_payment`].
738 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
739 payment_hash: PaymentHash,
740 /// The reason the payment failed. This is only `None` for events generated or serialized
741 /// by versions prior to 0.0.115.
742 reason: Option<PaymentFailureReason>,
744 /// Indicates that a path for an outbound payment was successful.
746 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
747 /// [`Event::PaymentSent`] for obtaining the payment preimage.
748 PaymentPathSuccessful {
749 /// The `payment_id` passed to [`ChannelManager::send_payment`].
751 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
752 payment_id: PaymentId,
753 /// The hash that was given to [`ChannelManager::send_payment`].
755 /// This will be `Some` for all payments which completed on LDK 0.0.104 or later.
757 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
758 payment_hash: Option<PaymentHash>,
759 /// The payment path that was successful.
761 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
764 /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
767 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
768 /// [`Event::PaymentFailed`].
770 /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
773 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
775 /// The `payment_id` passed to [`ChannelManager::send_payment`].
777 /// This will be `Some` for all payment paths which failed on LDK 0.0.103 or later.
779 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
780 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
781 payment_id: Option<PaymentId>,
782 /// The hash that was given to [`ChannelManager::send_payment`].
784 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
785 payment_hash: PaymentHash,
786 /// Indicates the payment was rejected for some reason by the recipient. This implies that
787 /// the payment has failed, not just the route in question. If this is not set, the payment may
788 /// be retried via a different route.
789 payment_failed_permanently: bool,
790 /// Extra error details based on the failure type. May contain an update that needs to be
791 /// applied to the [`NetworkGraph`].
793 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
794 failure: PathFailure,
795 /// The payment path that failed.
797 /// The channel responsible for the failed payment path.
799 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
800 /// may not refer to a channel in the public network graph. These aliases may also collide
801 /// with channels in the public network graph.
803 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
804 /// retried. May be `None` for older [`Event`] serializations.
805 short_channel_id: Option<u64>,
807 error_code: Option<u16>,
809 error_data: Option<Vec<u8>>,
811 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
813 /// The id returned by [`ChannelManager::send_probe`].
815 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
816 payment_id: PaymentId,
817 /// The hash generated by [`ChannelManager::send_probe`].
819 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
820 payment_hash: PaymentHash,
821 /// The payment path that was successful.
824 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
826 /// The id returned by [`ChannelManager::send_probe`].
828 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
829 payment_id: PaymentId,
830 /// The hash generated by [`ChannelManager::send_probe`].
832 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
833 payment_hash: PaymentHash,
834 /// The payment path that failed.
836 /// The channel responsible for the failed probe.
838 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
839 /// may not refer to a channel in the public network graph. These aliases may also collide
840 /// with channels in the public network graph.
841 short_channel_id: Option<u64>,
843 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
844 /// a time in the future.
846 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
847 PendingHTLCsForwardable {
848 /// The minimum amount of time that should be waited prior to calling
849 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
850 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
851 /// now + 5*time_forwardable).
852 time_forwardable: Duration,
854 /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
855 /// you've encoded an intercept scid in the receiver's invoice route hints using
856 /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
858 /// [`ChannelManager::forward_intercepted_htlc`] or
859 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
860 /// their docs for more information.
862 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
863 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
864 /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
865 /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
867 /// An id to help LDK identify which HTLC is being forwarded or failed.
868 intercept_id: InterceptId,
869 /// The fake scid that was programmed as the next hop's scid, generated using
870 /// [`ChannelManager::get_intercept_scid`].
872 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
873 requested_next_hop_scid: u64,
874 /// The payment hash used for this HTLC.
875 payment_hash: PaymentHash,
876 /// How many msats were received on the inbound edge of this HTLC.
877 inbound_amount_msat: u64,
878 /// How many msats the payer intended to route to the next node. Depending on the reason you are
879 /// intercepting this payment, you might take a fee by forwarding less than this amount.
880 /// Forwarding less than this amount may break compatibility with LDK versions prior to 0.0.116.
882 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
883 /// check that whatever fee you want has been included here or subtract it as required. Further,
884 /// LDK will not stop you from forwarding more than you received.
885 expected_outbound_amount_msat: u64,
887 /// Used to indicate that an output which you should know how to spend was confirmed on chain
888 /// and is now spendable.
889 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
890 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
891 /// somewhere and spend them when you create on-chain transactions.
893 /// The outputs which you should store as spendable by you.
894 outputs: Vec<SpendableOutputDescriptor>,
895 /// The `channel_id` indicating which channel the spendable outputs belong to.
897 /// This will always be `Some` for events generated by LDK versions 0.0.117 and above.
898 channel_id: Option<ChannelId>,
900 /// This event is generated when a payment has been successfully forwarded through us and a
901 /// forwarding fee earned.
903 /// The channel id of the incoming channel between the previous node and us.
905 /// This is only `None` for events generated or serialized by versions prior to 0.0.107.
906 prev_channel_id: Option<ChannelId>,
907 /// The channel id of the outgoing channel between the next node and us.
909 /// This is only `None` for events generated or serialized by versions prior to 0.0.107.
910 next_channel_id: Option<ChannelId>,
911 /// The `user_channel_id` of the incoming channel between the previous node and us.
913 /// This is only `None` for events generated or serialized by versions prior to 0.0.122.
914 prev_user_channel_id: Option<u128>,
915 /// The `user_channel_id` of the outgoing channel between the next node and us.
917 /// This will be `None` if the payment was settled via an on-chain transaction. See the
918 /// caveat described for the `total_fee_earned_msat` field. Moreover it will be `None` for
919 /// events generated or serialized by versions prior to 0.0.122.
920 next_user_channel_id: Option<u128>,
921 /// The total fee, in milli-satoshis, which was earned as a result of the payment.
923 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
924 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
925 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
926 /// claimed the full value in millisatoshis from the source. In this case,
927 /// `claim_from_onchain_tx` will be set.
929 /// If the channel which sent us the payment has been force-closed, we will claim the funds
930 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
931 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
932 /// `PaymentForwarded` events are generated for the same payment iff `total_fee_earned_msat` is
934 total_fee_earned_msat: Option<u64>,
935 /// The share of the total fee, in milli-satoshis, which was withheld in addition to the
938 /// This will only be `Some` if we forwarded an intercepted HTLC with less than the
939 /// expected amount. This means our counterparty accepted to receive less than the invoice
940 /// amount, e.g., by claiming the payment featuring a corresponding
941 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`].
943 /// Will also always be `None` for events serialized with LDK prior to version 0.0.122.
945 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
947 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`]: Self::PaymentClaimable::counterparty_skimmed_fee_msat
948 skimmed_fee_msat: Option<u64>,
949 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
951 claim_from_onchain_tx: bool,
952 /// The final amount forwarded, in milli-satoshis, after the fee is deducted.
954 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
955 outbound_amount_forwarded_msat: Option<u64>,
957 /// Used to indicate that a channel with the given `channel_id` is being opened and pending
958 /// confirmation on-chain.
960 /// This event is emitted when the funding transaction has been signed and is broadcast to the
961 /// network. For 0conf channels it will be immediately followed by the corresponding
962 /// [`Event::ChannelReady`] event.
964 /// The `channel_id` of the channel that is pending confirmation.
965 channel_id: ChannelId,
966 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
967 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
968 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
969 /// `user_channel_id` will be randomized for an inbound channel.
971 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
972 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
973 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
974 user_channel_id: u128,
975 /// The `temporary_channel_id` this channel used to be known by during channel establishment.
977 /// Will be `None` for channels created prior to LDK version 0.0.115.
978 former_temporary_channel_id: Option<ChannelId>,
979 /// The `node_id` of the channel counterparty.
980 counterparty_node_id: PublicKey,
981 /// The outpoint of the channel's funding transaction.
982 funding_txo: OutPoint,
983 /// The features that this channel will operate with.
985 /// Will be `None` for channels created prior to LDK version 0.0.122.
986 channel_type: Option<ChannelTypeFeatures>,
988 /// Used to indicate that a channel with the given `channel_id` is ready to
989 /// be used. This event is emitted either when the funding transaction has been confirmed
990 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
993 /// The `channel_id` of the channel that is ready.
994 channel_id: ChannelId,
995 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
996 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
997 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
998 /// `user_channel_id` will be randomized for an inbound channel.
1000 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1001 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1002 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1003 user_channel_id: u128,
1004 /// The `node_id` of the channel counterparty.
1005 counterparty_node_id: PublicKey,
1006 /// The features that this channel will operate with.
1007 channel_type: ChannelTypeFeatures,
1009 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
1010 /// process of closure.
1012 /// Note that this event is only triggered for accepted channels: if the
1013 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true and the channel is
1014 /// rejected, no `ChannelClosed` event will be sent.
1016 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1017 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1019 /// The `channel_id` of the channel which has been closed. Note that on-chain transactions
1020 /// resolving the channel are likely still awaiting confirmation.
1021 channel_id: ChannelId,
1022 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1023 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1024 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1025 /// `user_channel_id` will be randomized for inbound channels.
1026 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
1027 /// zero for objects serialized with LDK versions prior to 0.0.102.
1029 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1030 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1031 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1032 user_channel_id: u128,
1033 /// The reason the channel was closed.
1034 reason: ClosureReason,
1035 /// Counterparty in the closed channel.
1037 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
1038 counterparty_node_id: Option<PublicKey>,
1039 /// Channel capacity of the closing channel (sats).
1041 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
1042 channel_capacity_sats: Option<u64>,
1043 /// The original channel funding TXO; this helps checking for the existence and confirmation
1044 /// status of the closing tx.
1045 /// Note that for instances serialized in v0.0.119 or prior this will be missing (None).
1046 channel_funding_txo: Option<transaction::OutPoint>,
1048 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
1049 /// inputs for another purpose.
1051 /// This event is not guaranteed to be generated for channels that are closed due to a restart.
1053 /// The channel_id of the channel which has been closed.
1054 channel_id: ChannelId,
1055 /// The full transaction received from the user
1056 transaction: Transaction
1058 /// Indicates a request to open a new channel by a peer.
1060 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the request,
1061 /// call [`ChannelManager::force_close_without_broadcasting_txn`]. Note that a ['ChannelClosed`]
1062 /// event will _not_ be triggered if the channel is rejected.
1064 /// The event is only triggered when a new open channel request is received and the
1065 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
1067 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1068 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1069 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1070 OpenChannelRequest {
1071 /// The temporary channel ID of the channel requested to be opened.
1073 /// When responding to the request, the `temporary_channel_id` should be passed
1074 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
1075 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
1077 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1078 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1079 temporary_channel_id: ChannelId,
1080 /// The node_id of the counterparty requesting to open the channel.
1082 /// When responding to the request, the `counterparty_node_id` should be passed
1083 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
1084 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
1087 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1088 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
1089 counterparty_node_id: PublicKey,
1090 /// The channel value of the requested channel.
1091 funding_satoshis: u64,
1092 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
1094 /// The features that this channel will operate with. If you reject the channel, a
1095 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
1098 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
1099 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1102 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
1103 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1104 /// 0.0.107. Channels setting this type also need to get manually accepted via
1105 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
1106 /// or will be rejected otherwise.
1108 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1109 channel_type: ChannelTypeFeatures,
1111 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
1114 /// Some scenarios where this event may be sent include:
1115 /// * Insufficient capacity in the outbound channel
1116 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
1117 /// * When an unknown SCID is requested for forwarding a payment.
1118 /// * Expected MPP amount has already been reached
1119 /// * The HTLC has timed out
1121 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
1122 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
1123 HTLCHandlingFailed {
1124 /// The channel over which the HTLC was received.
1125 prev_channel_id: ChannelId,
1126 /// Destination of the HTLC that failed to be processed.
1127 failed_next_destination: HTLCDestination,
1129 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
1130 /// requires confirmed external funds to be readily available to spend.
1132 /// LDK does not currently generate this event unless the
1133 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`] config flag is set to true.
1134 /// It is limited to the scope of channels with anchor outputs.
1136 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`]: crate::util::config::ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx
1137 BumpTransaction(BumpTransactionEvent),
1140 impl Writeable for Event {
1141 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1143 &Event::FundingGenerationReady { .. } => {
1145 // We never write out FundingGenerationReady events as, upon disconnection, peers
1146 // drop any channels which have not yet exchanged funding_signed.
1148 &Event::PaymentClaimable { ref payment_hash, ref amount_msat, counterparty_skimmed_fee_msat,
1149 ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id,
1150 ref claim_deadline, ref onion_fields
1153 let mut payment_secret = None;
1154 let payment_preimage;
1155 let mut payment_context = None;
1157 PaymentPurpose::Bolt11InvoicePayment {
1158 payment_preimage: preimage, payment_secret: secret
1160 payment_secret = Some(secret);
1161 payment_preimage = *preimage;
1163 PaymentPurpose::Bolt12OfferPayment {
1164 payment_preimage: preimage, payment_secret: secret, payment_context: context
1166 payment_secret = Some(secret);
1167 payment_preimage = *preimage;
1168 payment_context = Some(PaymentContextRef::Bolt12Offer(context));
1170 PaymentPurpose::Bolt12RefundPayment {
1171 payment_preimage: preimage, payment_secret: secret, payment_context: context
1173 payment_secret = Some(secret);
1174 payment_preimage = *preimage;
1175 payment_context = Some(PaymentContextRef::Bolt12Refund(context));
1177 PaymentPurpose::SpontaneousPayment(preimage) => {
1178 payment_preimage = Some(*preimage);
1181 let skimmed_fee_opt = if counterparty_skimmed_fee_msat == 0 { None }
1182 else { Some(counterparty_skimmed_fee_msat) };
1183 write_tlv_fields!(writer, {
1184 (0, payment_hash, required),
1185 (1, receiver_node_id, option),
1186 (2, payment_secret, option),
1187 (3, via_channel_id, option),
1188 (4, amount_msat, required),
1189 (5, via_user_channel_id, option),
1190 // Type 6 was `user_payment_id` on 0.0.103 and earlier
1191 (7, claim_deadline, option),
1192 (8, payment_preimage, option),
1193 (9, onion_fields, option),
1194 (10, skimmed_fee_opt, option),
1195 (11, payment_context, option),
1198 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
1200 write_tlv_fields!(writer, {
1201 (0, payment_preimage, required),
1202 (1, payment_hash, required),
1203 (3, payment_id, option),
1204 (5, fee_paid_msat, option),
1207 &Event::PaymentPathFailed {
1208 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
1209 ref path, ref short_channel_id,
1217 error_code.write(writer)?;
1219 error_data.write(writer)?;
1220 write_tlv_fields!(writer, {
1221 (0, payment_hash, required),
1222 (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
1223 (2, payment_failed_permanently, required),
1224 (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
1225 (4, path.blinded_tail, option),
1226 (5, path.hops, required_vec),
1227 (7, short_channel_id, option),
1228 (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
1229 (11, payment_id, option),
1230 (13, failure, required),
1233 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
1235 // Note that we now ignore these on the read end as we'll re-generate them in
1236 // ChannelManager, we write them here only for backwards compatibility.
1238 &Event::SpendableOutputs { ref outputs, channel_id } => {
1240 write_tlv_fields!(writer, {
1241 (0, WithoutLength(outputs), required),
1242 (1, channel_id, option),
1245 &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1247 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1248 write_tlv_fields!(writer, {
1249 (0, intercept_id, required),
1250 (2, intercept_scid, required),
1251 (4, payment_hash, required),
1252 (6, inbound_amount_msat, required),
1253 (8, expected_outbound_amount_msat, required),
1256 &Event::PaymentForwarded {
1257 prev_channel_id, next_channel_id, prev_user_channel_id, next_user_channel_id,
1258 total_fee_earned_msat, skimmed_fee_msat, claim_from_onchain_tx,
1259 outbound_amount_forwarded_msat,
1262 write_tlv_fields!(writer, {
1263 (0, total_fee_earned_msat, option),
1264 (1, prev_channel_id, option),
1265 (2, claim_from_onchain_tx, required),
1266 (3, next_channel_id, option),
1267 (5, outbound_amount_forwarded_msat, option),
1268 (7, skimmed_fee_msat, option),
1269 (9, prev_user_channel_id, option),
1270 (11, next_user_channel_id, option),
1273 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason,
1274 ref counterparty_node_id, ref channel_capacity_sats, ref channel_funding_txo
1277 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1278 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1279 // separate u64 values.
1280 let user_channel_id_low = *user_channel_id as u64;
1281 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1282 write_tlv_fields!(writer, {
1283 (0, channel_id, required),
1284 (1, user_channel_id_low, required),
1285 (2, reason, required),
1286 (3, user_channel_id_high, required),
1287 (5, counterparty_node_id, option),
1288 (7, channel_capacity_sats, option),
1289 (9, channel_funding_txo, option),
1292 &Event::DiscardFunding { ref channel_id, ref transaction } => {
1293 11u8.write(writer)?;
1294 write_tlv_fields!(writer, {
1295 (0, channel_id, required),
1296 (2, transaction, required)
1299 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1300 13u8.write(writer)?;
1301 write_tlv_fields!(writer, {
1302 (0, payment_id, required),
1303 (2, payment_hash, option),
1304 (4, path.hops, required_vec),
1305 (6, path.blinded_tail, option),
1308 &Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
1309 15u8.write(writer)?;
1310 write_tlv_fields!(writer, {
1311 (0, payment_id, required),
1312 (1, reason, option),
1313 (2, payment_hash, required),
1316 &Event::OpenChannelRequest { .. } => {
1317 17u8.write(writer)?;
1318 // We never write the OpenChannelRequest events as, upon disconnection, peers
1319 // drop any channels which have not yet exchanged funding_signed.
1321 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref htlcs, ref sender_intended_total_msat } => {
1322 19u8.write(writer)?;
1323 write_tlv_fields!(writer, {
1324 (0, payment_hash, required),
1325 (1, receiver_node_id, option),
1326 (2, purpose, required),
1327 (4, amount_msat, required),
1328 (5, *htlcs, optional_vec),
1329 (7, sender_intended_total_msat, option),
1332 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1333 21u8.write(writer)?;
1334 write_tlv_fields!(writer, {
1335 (0, payment_id, required),
1336 (2, payment_hash, required),
1337 (4, path.hops, required_vec),
1338 (6, path.blinded_tail, option),
1341 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1342 23u8.write(writer)?;
1343 write_tlv_fields!(writer, {
1344 (0, payment_id, required),
1345 (2, payment_hash, required),
1346 (4, path.hops, required_vec),
1347 (6, short_channel_id, option),
1348 (8, path.blinded_tail, option),
1351 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1352 25u8.write(writer)?;
1353 write_tlv_fields!(writer, {
1354 (0, prev_channel_id, required),
1355 (2, failed_next_destination, required),
1358 &Event::BumpTransaction(ref event)=> {
1359 27u8.write(writer)?;
1361 // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1362 // upon restarting anyway if they remain unresolved.
1363 BumpTransactionEvent::ChannelClose { .. } => {}
1364 BumpTransactionEvent::HTLCResolution { .. } => {}
1366 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1368 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1369 29u8.write(writer)?;
1370 write_tlv_fields!(writer, {
1371 (0, channel_id, required),
1372 (2, user_channel_id, required),
1373 (4, counterparty_node_id, required),
1374 (6, channel_type, required),
1377 &Event::ChannelPending { ref channel_id, ref user_channel_id,
1378 ref former_temporary_channel_id, ref counterparty_node_id, ref funding_txo,
1381 31u8.write(writer)?;
1382 write_tlv_fields!(writer, {
1383 (0, channel_id, required),
1384 (1, channel_type, option),
1385 (2, user_channel_id, required),
1386 (4, former_temporary_channel_id, required),
1387 (6, counterparty_node_id, required),
1388 (8, funding_txo, required),
1391 &Event::InvoiceRequestFailed { ref payment_id } => {
1392 33u8.write(writer)?;
1393 write_tlv_fields!(writer, {
1394 (0, payment_id, required),
1397 &Event::ConnectionNeeded { .. } => {
1398 35u8.write(writer)?;
1399 // Never write ConnectionNeeded events as buffered onion messages aren't serialized.
1401 // Note that, going forward, all new events must only write data inside of
1402 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1403 // data via `write_tlv_fields`.
1408 impl MaybeReadable for Event {
1409 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1410 match Readable::read(reader)? {
1411 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events.
1415 let mut payment_hash = PaymentHash([0; 32]);
1416 let mut payment_preimage = None;
1417 let mut payment_secret = None;
1418 let mut amount_msat = 0;
1419 let mut counterparty_skimmed_fee_msat_opt = None;
1420 let mut receiver_node_id = None;
1421 let mut _user_payment_id = None::<u64>; // Used in 0.0.103 and earlier, no longer written in 0.0.116+.
1422 let mut via_channel_id = None;
1423 let mut claim_deadline = None;
1424 let mut via_user_channel_id = None;
1425 let mut onion_fields = None;
1426 let mut payment_context = None;
1427 read_tlv_fields!(reader, {
1428 (0, payment_hash, required),
1429 (1, receiver_node_id, option),
1430 (2, payment_secret, option),
1431 (3, via_channel_id, option),
1432 (4, amount_msat, required),
1433 (5, via_user_channel_id, option),
1434 (6, _user_payment_id, option),
1435 (7, claim_deadline, option),
1436 (8, payment_preimage, option),
1437 (9, onion_fields, option),
1438 (10, counterparty_skimmed_fee_msat_opt, option),
1439 (11, payment_context, option),
1441 let purpose = match payment_secret {
1442 Some(secret) => PaymentPurpose::from_parts(payment_preimage, secret, payment_context),
1443 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1444 None => return Err(msgs::DecodeError::InvalidValue),
1446 Ok(Some(Event::PaymentClaimable {
1450 counterparty_skimmed_fee_msat: counterparty_skimmed_fee_msat_opt.unwrap_or(0),
1453 via_user_channel_id,
1462 let mut payment_preimage = PaymentPreimage([0; 32]);
1463 let mut payment_hash = None;
1464 let mut payment_id = None;
1465 let mut fee_paid_msat = None;
1466 read_tlv_fields!(reader, {
1467 (0, payment_preimage, required),
1468 (1, payment_hash, option),
1469 (3, payment_id, option),
1470 (5, fee_paid_msat, option),
1472 if payment_hash.is_none() {
1473 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()));
1475 Ok(Some(Event::PaymentSent {
1478 payment_hash: payment_hash.unwrap(),
1487 let error_code = Readable::read(reader)?;
1489 let error_data = Readable::read(reader)?;
1490 let mut payment_hash = PaymentHash([0; 32]);
1491 let mut payment_failed_permanently = false;
1492 let mut network_update = None;
1493 let mut blinded_tail: Option<BlindedTail> = None;
1494 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1495 let mut short_channel_id = None;
1496 let mut payment_id = None;
1497 let mut failure_opt = None;
1498 read_tlv_fields!(reader, {
1499 (0, payment_hash, required),
1500 (1, network_update, upgradable_option),
1501 (2, payment_failed_permanently, required),
1502 (4, blinded_tail, option),
1503 // Added as a part of LDK 0.0.101 and always filled in since.
1504 // Defaults to an empty Vec, though likely should have been `Option`al.
1505 (5, path, optional_vec),
1506 (7, short_channel_id, option),
1507 (11, payment_id, option),
1508 (13, failure_opt, upgradable_option),
1510 let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1511 Ok(Some(Event::PaymentPathFailed {
1514 payment_failed_permanently,
1516 path: Path { hops: path.unwrap(), blinded_tail },
1529 let mut outputs = WithoutLength(Vec::new());
1530 let mut channel_id: Option<ChannelId> = None;
1531 read_tlv_fields!(reader, {
1532 (0, outputs, required),
1533 (1, channel_id, option),
1535 Ok(Some(Event::SpendableOutputs { outputs: outputs.0, channel_id }))
1540 let mut payment_hash = PaymentHash([0; 32]);
1541 let mut intercept_id = InterceptId([0; 32]);
1542 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1543 let mut inbound_amount_msat = 0;
1544 let mut expected_outbound_amount_msat = 0;
1545 read_tlv_fields!(reader, {
1546 (0, intercept_id, required),
1547 (2, requested_next_hop_scid, required),
1548 (4, payment_hash, required),
1549 (6, inbound_amount_msat, required),
1550 (8, expected_outbound_amount_msat, required),
1552 let next_scid = match requested_next_hop_scid {
1553 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1555 Ok(Some(Event::HTLCIntercepted {
1557 requested_next_hop_scid: next_scid,
1558 inbound_amount_msat,
1559 expected_outbound_amount_msat,
1565 let mut prev_channel_id = None;
1566 let mut next_channel_id = None;
1567 let mut prev_user_channel_id = None;
1568 let mut next_user_channel_id = None;
1569 let mut total_fee_earned_msat = None;
1570 let mut skimmed_fee_msat = None;
1571 let mut claim_from_onchain_tx = false;
1572 let mut outbound_amount_forwarded_msat = None;
1573 read_tlv_fields!(reader, {
1574 (0, total_fee_earned_msat, option),
1575 (1, prev_channel_id, option),
1576 (2, claim_from_onchain_tx, required),
1577 (3, next_channel_id, option),
1578 (5, outbound_amount_forwarded_msat, option),
1579 (7, skimmed_fee_msat, option),
1580 (9, prev_user_channel_id, option),
1581 (11, next_user_channel_id, option),
1583 Ok(Some(Event::PaymentForwarded {
1584 prev_channel_id, next_channel_id, prev_user_channel_id,
1585 next_user_channel_id, total_fee_earned_msat, skimmed_fee_msat,
1586 claim_from_onchain_tx, outbound_amount_forwarded_msat,
1593 let mut channel_id = ChannelId::new_zero();
1594 let mut reason = UpgradableRequired(None);
1595 let mut user_channel_id_low_opt: Option<u64> = None;
1596 let mut user_channel_id_high_opt: Option<u64> = None;
1597 let mut counterparty_node_id = None;
1598 let mut channel_capacity_sats = None;
1599 let mut channel_funding_txo = None;
1600 read_tlv_fields!(reader, {
1601 (0, channel_id, required),
1602 (1, user_channel_id_low_opt, option),
1603 (2, reason, upgradable_required),
1604 (3, user_channel_id_high_opt, option),
1605 (5, counterparty_node_id, option),
1606 (7, channel_capacity_sats, option),
1607 (9, channel_funding_txo, option),
1610 // `user_channel_id` used to be a single u64 value. In order to remain
1611 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1612 // as two separate u64 values.
1613 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1614 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1616 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required),
1617 counterparty_node_id, channel_capacity_sats, channel_funding_txo }))
1623 let mut channel_id = ChannelId::new_zero();
1624 let mut transaction = Transaction{ version: 2, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
1625 read_tlv_fields!(reader, {
1626 (0, channel_id, required),
1627 (2, transaction, required),
1629 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1635 _init_and_read_len_prefixed_tlv_fields!(reader, {
1636 (0, payment_id, required),
1637 (2, payment_hash, option),
1638 (4, path, required_vec),
1639 (6, blinded_tail, option),
1641 Ok(Some(Event::PaymentPathSuccessful {
1642 payment_id: payment_id.0.unwrap(),
1644 path: Path { hops: path, blinded_tail },
1651 let mut payment_hash = PaymentHash([0; 32]);
1652 let mut payment_id = PaymentId([0; 32]);
1653 let mut reason = None;
1654 read_tlv_fields!(reader, {
1655 (0, payment_id, required),
1656 (1, reason, upgradable_option),
1657 (2, payment_hash, required),
1659 Ok(Some(Event::PaymentFailed {
1668 // Value 17 is used for `Event::OpenChannelRequest`.
1673 let mut payment_hash = PaymentHash([0; 32]);
1674 let mut purpose = UpgradableRequired(None);
1675 let mut amount_msat = 0;
1676 let mut receiver_node_id = None;
1677 let mut htlcs: Option<Vec<ClaimedHTLC>> = Some(vec![]);
1678 let mut sender_intended_total_msat: Option<u64> = None;
1679 read_tlv_fields!(reader, {
1680 (0, payment_hash, required),
1681 (1, receiver_node_id, option),
1682 (2, purpose, upgradable_required),
1683 (4, amount_msat, required),
1684 (5, htlcs, optional_vec),
1685 (7, sender_intended_total_msat, option),
1687 Ok(Some(Event::PaymentClaimed {
1690 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1692 htlcs: htlcs.unwrap_or(vec![]),
1693 sender_intended_total_msat,
1700 _init_and_read_len_prefixed_tlv_fields!(reader, {
1701 (0, payment_id, required),
1702 (2, payment_hash, required),
1703 (4, path, required_vec),
1704 (6, blinded_tail, option),
1706 Ok(Some(Event::ProbeSuccessful {
1707 payment_id: payment_id.0.unwrap(),
1708 payment_hash: payment_hash.0.unwrap(),
1709 path: Path { hops: path, blinded_tail },
1716 _init_and_read_len_prefixed_tlv_fields!(reader, {
1717 (0, payment_id, required),
1718 (2, payment_hash, required),
1719 (4, path, required_vec),
1720 (6, short_channel_id, option),
1721 (8, blinded_tail, option),
1723 Ok(Some(Event::ProbeFailed {
1724 payment_id: payment_id.0.unwrap(),
1725 payment_hash: payment_hash.0.unwrap(),
1726 path: Path { hops: path, blinded_tail },
1734 let mut prev_channel_id = ChannelId::new_zero();
1735 let mut failed_next_destination_opt = UpgradableRequired(None);
1736 read_tlv_fields!(reader, {
1737 (0, prev_channel_id, required),
1738 (2, failed_next_destination_opt, upgradable_required),
1740 Ok(Some(Event::HTLCHandlingFailed {
1742 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1750 let mut channel_id = ChannelId::new_zero();
1751 let mut user_channel_id: u128 = 0;
1752 let mut counterparty_node_id = RequiredWrapper(None);
1753 let mut channel_type = RequiredWrapper(None);
1754 read_tlv_fields!(reader, {
1755 (0, channel_id, required),
1756 (2, user_channel_id, required),
1757 (4, counterparty_node_id, required),
1758 (6, channel_type, required),
1761 Ok(Some(Event::ChannelReady {
1764 counterparty_node_id: counterparty_node_id.0.unwrap(),
1765 channel_type: channel_type.0.unwrap()
1772 let mut channel_id = ChannelId::new_zero();
1773 let mut user_channel_id: u128 = 0;
1774 let mut former_temporary_channel_id = None;
1775 let mut counterparty_node_id = RequiredWrapper(None);
1776 let mut funding_txo = RequiredWrapper(None);
1777 let mut channel_type = None;
1778 read_tlv_fields!(reader, {
1779 (0, channel_id, required),
1780 (1, channel_type, option),
1781 (2, user_channel_id, required),
1782 (4, former_temporary_channel_id, required),
1783 (6, counterparty_node_id, required),
1784 (8, funding_txo, required),
1787 Ok(Some(Event::ChannelPending {
1790 former_temporary_channel_id,
1791 counterparty_node_id: counterparty_node_id.0.unwrap(),
1792 funding_txo: funding_txo.0.unwrap(),
1800 _init_and_read_len_prefixed_tlv_fields!(reader, {
1801 (0, payment_id, required),
1803 Ok(Some(Event::InvoiceRequestFailed {
1804 payment_id: payment_id.0.unwrap(),
1809 // Note that we do not write a length-prefixed TLV for ConnectionNeeded events.
1811 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1812 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1814 x if x % 2 == 1 => {
1815 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1816 // which prefixes the whole thing with a length BigSize. Because the event is
1817 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1818 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1819 // exactly the number of bytes specified, ignoring them entirely.
1820 let tlv_len: BigSize = Readable::read(reader)?;
1821 FixedLengthReader::new(reader, tlv_len.0)
1822 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1825 _ => Err(msgs::DecodeError::InvalidValue)
1830 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1831 /// broadcast to most peers).
1832 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1833 #[derive(Clone, Debug)]
1834 #[cfg_attr(test, derive(PartialEq))]
1835 pub enum MessageSendEvent {
1836 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1837 /// message provided to the given peer.
1839 /// The node_id of the node which should receive this message
1841 /// The message which should be sent.
1842 msg: msgs::AcceptChannel,
1844 /// Used to indicate that we've accepted a V2 channel open and should send the accept_channel2
1845 /// message provided to the given peer.
1846 SendAcceptChannelV2 {
1847 /// The node_id of the node which should receive this message
1849 /// The message which should be sent.
1850 msg: msgs::AcceptChannelV2,
1852 /// Used to indicate that we've initiated a channel open and should send the open_channel
1853 /// message provided to the given peer.
1855 /// The node_id of the node which should receive this message
1857 /// The message which should be sent.
1858 msg: msgs::OpenChannel,
1860 /// Used to indicate that we've initiated a V2 channel open and should send the open_channel2
1861 /// message provided to the given peer.
1863 /// The node_id of the node which should receive this message
1865 /// The message which should be sent.
1866 msg: msgs::OpenChannelV2,
1868 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1869 SendFundingCreated {
1870 /// The node_id of the node which should receive this message
1872 /// The message which should be sent.
1873 msg: msgs::FundingCreated,
1875 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1877 /// The node_id of the node which should receive this message
1879 /// The message which should be sent.
1880 msg: msgs::FundingSigned,
1882 /// Used to indicate that a stfu message should be sent to the peer with the given node id.
1884 /// The node_id of the node which should receive this message
1886 /// The message which should be sent.
1889 /// Used to indicate that a splice message should be sent to the peer with the given node id.
1891 /// The node_id of the node which should receive this message
1893 /// The message which should be sent.
1896 /// Used to indicate that a splice_ack message should be sent to the peer with the given node id.
1898 /// The node_id of the node which should receive this message
1900 /// The message which should be sent.
1901 msg: msgs::SpliceAck,
1903 /// Used to indicate that a splice_locked message should be sent to the peer with the given node id.
1905 /// The node_id of the node which should receive this message
1907 /// The message which should be sent.
1908 msg: msgs::SpliceLocked,
1910 /// Used to indicate that a tx_add_input message should be sent to the peer with the given node_id.
1912 /// The node_id of the node which should receive this message
1914 /// The message which should be sent.
1915 msg: msgs::TxAddInput,
1917 /// Used to indicate that a tx_add_output message should be sent to the peer with the given node_id.
1919 /// The node_id of the node which should receive this message
1921 /// The message which should be sent.
1922 msg: msgs::TxAddOutput,
1924 /// Used to indicate that a tx_remove_input message should be sent to the peer with the given node_id.
1926 /// The node_id of the node which should receive this message
1928 /// The message which should be sent.
1929 msg: msgs::TxRemoveInput,
1931 /// Used to indicate that a tx_remove_output message should be sent to the peer with the given node_id.
1932 SendTxRemoveOutput {
1933 /// The node_id of the node which should receive this message
1935 /// The message which should be sent.
1936 msg: msgs::TxRemoveOutput,
1938 /// Used to indicate that a tx_complete message should be sent to the peer with the given node_id.
1940 /// The node_id of the node which should receive this message
1942 /// The message which should be sent.
1943 msg: msgs::TxComplete,
1945 /// Used to indicate that a tx_signatures message should be sent to the peer with the given node_id.
1947 /// The node_id of the node which should receive this message
1949 /// The message which should be sent.
1950 msg: msgs::TxSignatures,
1952 /// Used to indicate that a tx_init_rbf message should be sent to the peer with the given node_id.
1954 /// The node_id of the node which should receive this message
1956 /// The message which should be sent.
1957 msg: msgs::TxInitRbf,
1959 /// Used to indicate that a tx_ack_rbf message should be sent to the peer with the given node_id.
1961 /// The node_id of the node which should receive this message
1963 /// The message which should be sent.
1964 msg: msgs::TxAckRbf,
1966 /// Used to indicate that a tx_abort message should be sent to the peer with the given node_id.
1968 /// The node_id of the node which should receive this message
1970 /// The message which should be sent.
1973 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1975 /// The node_id of the node which should receive these message(s)
1977 /// The channel_ready message which should be sent.
1978 msg: msgs::ChannelReady,
1980 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1981 SendAnnouncementSignatures {
1982 /// The node_id of the node which should receive these message(s)
1984 /// The announcement_signatures message which should be sent.
1985 msg: msgs::AnnouncementSignatures,
1987 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1988 /// message should be sent to the peer with the given node_id.
1990 /// The node_id of the node which should receive these message(s)
1992 /// The update messages which should be sent. ALL messages in the struct should be sent!
1993 updates: msgs::CommitmentUpdate,
1995 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1997 /// The node_id of the node which should receive this message
1999 /// The message which should be sent.
2000 msg: msgs::RevokeAndACK,
2002 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
2004 /// The node_id of the node which should receive this message
2006 /// The message which should be sent.
2007 msg: msgs::ClosingSigned,
2009 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
2011 /// The node_id of the node which should receive this message
2013 /// The message which should be sent.
2014 msg: msgs::Shutdown,
2016 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
2017 SendChannelReestablish {
2018 /// The node_id of the node which should receive this message
2020 /// The message which should be sent.
2021 msg: msgs::ChannelReestablish,
2023 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
2024 /// initial connection to ensure our peers know about our channels.
2025 SendChannelAnnouncement {
2026 /// The node_id of the node which should receive this message
2028 /// The channel_announcement which should be sent.
2029 msg: msgs::ChannelAnnouncement,
2030 /// The followup channel_update which should be sent.
2031 update_msg: msgs::ChannelUpdate,
2033 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
2034 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
2036 /// Note that after doing so, you very likely (unless you did so very recently) want to
2037 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
2038 /// ensures that any nodes which see our channel_announcement also have a relevant
2039 /// node_announcement, including relevant feature flags which may be important for routing
2040 /// through or to us.
2042 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
2043 BroadcastChannelAnnouncement {
2044 /// The channel_announcement which should be sent.
2045 msg: msgs::ChannelAnnouncement,
2046 /// The followup channel_update which should be sent.
2047 update_msg: Option<msgs::ChannelUpdate>,
2049 /// Used to indicate that a channel_update should be broadcast to all peers.
2050 BroadcastChannelUpdate {
2051 /// The channel_update which should be sent.
2052 msg: msgs::ChannelUpdate,
2054 /// Used to indicate that a node_announcement should be broadcast to all peers.
2055 BroadcastNodeAnnouncement {
2056 /// The node_announcement which should be sent.
2057 msg: msgs::NodeAnnouncement,
2059 /// Used to indicate that a channel_update should be sent to a single peer.
2060 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
2061 /// private channel and we shouldn't be informing all of our peers of channel parameters.
2063 /// The node_id of the node which should receive this message
2065 /// The channel_update which should be sent.
2066 msg: msgs::ChannelUpdate,
2068 /// Broadcast an error downstream to be handled
2070 /// The node_id of the node which should receive this message
2072 /// The action which should be taken.
2073 action: msgs::ErrorAction
2075 /// Query a peer for channels with funding transaction UTXOs in a block range.
2076 SendChannelRangeQuery {
2077 /// The node_id of this message recipient
2079 /// The query_channel_range which should be sent.
2080 msg: msgs::QueryChannelRange,
2082 /// Request routing gossip messages from a peer for a list of channels identified by
2083 /// their short_channel_ids.
2085 /// The node_id of this message recipient
2087 /// The query_short_channel_ids which should be sent.
2088 msg: msgs::QueryShortChannelIds,
2090 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
2091 /// emitted during processing of the query.
2092 SendReplyChannelRange {
2093 /// The node_id of this message recipient
2095 /// The reply_channel_range which should be sent.
2096 msg: msgs::ReplyChannelRange,
2098 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
2099 /// enable receiving gossip messages from the peer.
2100 SendGossipTimestampFilter {
2101 /// The node_id of this message recipient
2103 /// The gossip_timestamp_filter which should be sent.
2104 msg: msgs::GossipTimestampFilter,
2108 /// A trait indicating an object may generate message send events
2109 pub trait MessageSendEventsProvider {
2110 /// Gets the list of pending events which were generated by previous actions, clearing the list
2112 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
2115 /// A trait indicating an object may generate events.
2117 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
2119 /// Implementations of this trait may also feature an async version of event handling, as shown with
2120 /// [`ChannelManager::process_pending_events_async`] and
2121 /// [`ChainMonitor::process_pending_events_async`].
2125 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
2126 /// event since the last invocation.
2128 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
2129 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
2130 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
2131 /// relevant changes to disk *before* returning.
2133 /// Further, because an application may crash between an [`Event`] being handled and the
2134 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
2135 /// effect, [`Event`]s may be replayed.
2137 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
2138 /// consult the provider's documentation on the implication of processing events and how a handler
2139 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
2140 /// [`ChainMonitor::process_pending_events`]).
2142 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
2145 /// [`process_pending_events`]: Self::process_pending_events
2146 /// [`handle_event`]: EventHandler::handle_event
2147 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
2148 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
2149 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
2150 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
2151 pub trait EventsProvider {
2152 /// Processes any events generated since the last call using the given event handler.
2154 /// See the trait-level documentation for requirements.
2155 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
2158 /// A trait implemented for objects handling events from [`EventsProvider`].
2160 /// An async variation also exists for implementations of [`EventsProvider`] that support async
2161 /// event handling. The async event handler should satisfy the generic bounds: `F:
2162 /// core::future::Future, H: Fn(Event) -> F`.
2163 pub trait EventHandler {
2164 /// Handles the given [`Event`].
2166 /// See [`EventsProvider`] for details that must be considered when implementing this method.
2167 fn handle_event(&self, event: Event);
2170 impl<F> EventHandler for F where F: Fn(Event) {
2171 fn handle_event(&self, event: Event) {
2176 impl<T: EventHandler> EventHandler for Arc<T> {
2177 fn handle_event(&self, event: Event) {
2178 self.deref().handle_event(event)