1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Events are returned from various bits in the library which indicate some action must be taken
13 //! Because we don't have a built-in runtime, it's up to the client to call events at a time in the
14 //! future, as well as generate and broadcast funding transactions handle payment preimages and a
17 pub mod bump_transaction;
19 pub use bump_transaction::BumpTransactionEvent;
21 use crate::sign::SpendableOutputDescriptor;
22 use crate::ln::channelmanager::{InterceptId, PaymentId, RecipientOnionFields};
23 use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
24 use crate::ln::features::ChannelTypeFeatures;
26 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
27 use crate::routing::gossip::NetworkUpdate;
28 use crate::util::errors::APIError;
29 use crate::util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, RequiredWrapper, UpgradableRequired, WithoutLength};
30 use crate::util::string::UntrustedString;
31 use crate::routing::router::{BlindedTail, Path, RouteHop, RouteParameters};
33 use bitcoin::{PackedLockTime, Transaction, OutPoint};
34 use bitcoin::blockdata::script::Script;
35 use bitcoin::hashes::Hash;
36 use bitcoin::hashes::sha256::Hash as Sha256;
37 use bitcoin::secp256k1::PublicKey;
39 use crate::prelude::*;
40 use core::time::Duration;
44 /// Some information provided on receipt of payment depends on whether the payment received is a
45 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
46 #[derive(Clone, Debug, PartialEq, Eq)]
47 pub enum PaymentPurpose {
48 /// Information for receiving a payment that we generated an invoice for.
50 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
51 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
52 /// [`ChannelManager::claim_funds`].
54 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
55 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
56 payment_preimage: Option<PaymentPreimage>,
57 /// The "payment secret". This authenticates the sender to the recipient, preventing a
58 /// number of deanonymization attacks during the routing process.
59 /// It is provided here for your reference, however its accuracy is enforced directly by
60 /// [`ChannelManager`] using the values you previously provided to
61 /// [`ChannelManager::create_inbound_payment`] or
62 /// [`ChannelManager::create_inbound_payment_for_hash`].
64 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
65 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
66 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
67 payment_secret: PaymentSecret,
69 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
70 /// (the payee) providing a preimage.
71 SpontaneousPayment(PaymentPreimage),
74 impl_writeable_tlv_based_enum!(PaymentPurpose,
75 (0, InvoicePayment) => {
76 (0, payment_preimage, option),
77 (2, payment_secret, required),
79 (2, SpontaneousPayment)
82 /// When the payment path failure took place and extra details about it. [`PathFailure::OnPath`] may
83 /// contain a [`NetworkUpdate`] that needs to be applied to the [`NetworkGraph`].
85 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
86 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
87 #[derive(Clone, Debug, Eq, PartialEq)]
88 pub enum PathFailure {
89 /// We failed to initially send the payment and no HTLC was committed to. Contains the relevant
92 /// The error surfaced from initial send.
95 /// A hop on the path failed to forward our payment.
97 /// If present, this [`NetworkUpdate`] should be applied to the [`NetworkGraph`] so that routing
98 /// decisions can take into account the update.
100 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
101 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
102 network_update: Option<NetworkUpdate>,
106 impl_writeable_tlv_based_enum_upgradable!(PathFailure,
108 (0, network_update, upgradable_option),
110 (2, InitialSend) => {
111 (0, err, upgradable_required),
115 #[derive(Clone, Debug, PartialEq, Eq)]
116 /// The reason the channel was closed. See individual variants more details.
117 pub enum ClosureReason {
118 /// Closure generated from receiving a peer error message.
120 /// Our counterparty may have broadcasted their latest commitment state, and we have
122 CounterpartyForceClosed {
123 /// The error which the peer sent us.
125 /// Be careful about printing the peer_msg, a well-crafted message could exploit
126 /// a security vulnerability in the terminal emulator or the logging subsystem.
127 /// To be safe, use `Display` on `UntrustedString`
129 /// [`UntrustedString`]: crate::util::string::UntrustedString
130 peer_msg: UntrustedString,
132 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
134 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
136 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
137 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
138 //TODO: split between CounterpartyInitiated/LocallyInitiated
140 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
141 /// commitment transaction came from our counterparty, but it may also have come from
142 /// a copy of our own `ChannelMonitor`.
143 CommitmentTxConfirmed,
144 /// The funding transaction failed to confirm in a timely manner on an inbound channel.
146 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
148 /// A developer-readable error message which we generated.
151 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
152 /// forget the channel entirely - we can attempt again if the peer reconnects.
154 /// This includes cases where we restarted prior to funding completion, including prior to the
155 /// initial [`ChannelMonitor`] persistence completing.
157 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
158 /// peer because of mutual incompatibility between us and our channel counterparty.
160 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
162 /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
163 /// the [`ChannelManager`] deserialized.
165 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
166 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
167 OutdatedChannelManager
170 impl core::fmt::Display for ClosureReason {
171 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
172 f.write_str("Channel closed because ")?;
174 ClosureReason::CounterpartyForceClosed { peer_msg } => {
175 f.write_fmt(format_args!("counterparty force-closed with message: {}", peer_msg))
177 ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
178 ClosureReason::CooperativeClosure => f.write_str("the channel was cooperatively closed"),
179 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
180 ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
181 ClosureReason::ProcessingError { err } => {
182 f.write_str("of an exception: ")?;
185 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
186 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
191 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
192 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
193 (1, FundingTimedOut) => {},
194 (2, HolderForceClosed) => {},
195 (6, CommitmentTxConfirmed) => {},
196 (4, CooperativeClosure) => {},
197 (8, ProcessingError) => { (1, err, required) },
198 (10, DisconnectedPeer) => {},
199 (12, OutdatedChannelManager) => {},
202 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
203 #[derive(Clone, Debug, PartialEq, Eq)]
204 pub enum HTLCDestination {
205 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
206 /// there is insufficient capacity in our outbound channel.
208 /// The `node_id` of the next node. For backwards compatibility, this field is
209 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
210 /// counterparty node information.
211 node_id: Option<PublicKey>,
212 /// The outgoing `channel_id` between us and the next node.
213 channel_id: [u8; 32],
215 /// Scenario where we are unsure of the next node to forward the HTLC to.
217 /// Short channel id we are requesting to forward an HTLC to.
218 requested_forward_scid: u64,
220 /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
223 /// Short channel id we are requesting to forward an HTLC to.
224 requested_forward_scid: u64
226 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
227 /// but is invalid for some reason, so we reject it.
229 /// Some of the reasons may include:
231 /// * Excess HTLCs for a payment that we have already fully received, over-paying for the
233 /// * The counterparty node modified the HTLC in transit,
234 /// * A probing attack where an intermediary node is trying to detect if we are the ultimate
235 /// recipient for a payment.
237 /// The payment hash of the payment we attempted to process.
238 payment_hash: PaymentHash
242 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
243 (0, NextHopChannel) => {
244 (0, node_id, required),
245 (2, channel_id, required),
247 (1, InvalidForward) => {
248 (0, requested_forward_scid, required),
250 (2, UnknownNextHop) => {
251 (0, requested_forward_scid, required),
253 (4, FailedPayment) => {
254 (0, payment_hash, required),
258 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
259 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
260 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
261 /// intercepts in upcoming work.
262 enum InterceptNextHop {
264 requested_next_hop_scid: u64,
268 impl_writeable_tlv_based_enum!(InterceptNextHop,
270 (0, requested_next_hop_scid, required),
274 /// The reason the payment failed. Used in [`Event::PaymentFailed`].
275 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
276 pub enum PaymentFailureReason {
277 /// The intended recipient rejected our payment.
279 /// The user chose to abandon this payment by calling [`ChannelManager::abandon_payment`].
281 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
283 /// We exhausted all of our retry attempts while trying to send the payment, or we
284 /// exhausted the [`Retry::Timeout`] if the user set one. If at any point a retry
285 /// attempt failed while being forwarded along the path, an [`Event::PaymentPathFailed`] will
286 /// have come before this.
288 /// [`Retry::Timeout`]: crate::ln::channelmanager::Retry::Timeout
290 /// The payment expired while retrying, based on the provided
291 /// [`PaymentParameters::expiry_time`].
293 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
295 /// We failed to find a route while retrying the payment.
297 /// This error should generally never happen. This likely means that there is a problem with
302 impl_writeable_tlv_based_enum!(PaymentFailureReason,
303 (0, RecipientRejected) => {},
304 (2, UserAbandoned) => {},
305 (4, RetriesExhausted) => {},
306 (6, PaymentExpired) => {},
307 (8, RouteNotFound) => {},
308 (10, UnexpectedError) => {}, ;
311 /// An Event which you should probably take some action in response to.
313 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
314 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
315 /// written as it makes no sense to respond to it after reconnecting to peers).
316 #[derive(Clone, Debug, PartialEq, Eq)]
318 /// Used to indicate that the client should generate a funding transaction with the given
319 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
320 /// Generated in [`ChannelManager`] message handling.
321 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
322 /// counterparty can steal your funds!
324 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
325 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
326 FundingGenerationReady {
327 /// The random channel_id we picked which you'll need to pass into
328 /// [`ChannelManager::funding_transaction_generated`].
330 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
331 temporary_channel_id: [u8; 32],
332 /// The counterparty's node_id, which you'll need to pass back into
333 /// [`ChannelManager::funding_transaction_generated`].
335 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
336 counterparty_node_id: PublicKey,
337 /// The value, in satoshis, that the output should have.
338 channel_value_satoshis: u64,
339 /// The script which should be used in the transaction output.
340 output_script: Script,
341 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or a
342 /// random value for an inbound channel. This may be zero for objects serialized with LDK
343 /// versions prior to 0.0.113.
345 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
346 user_channel_id: u128,
348 /// Indicates that we've been offered a payment and it needs to be claimed via calling
349 /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
351 /// Note that if the preimage is not known, you should call
352 /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
353 /// to free up resources for this HTLC and avoid network congestion.
354 /// If you fail to call either [`ChannelManager::claim_funds`], [`ChannelManager::fail_htlc_backwards`],
355 /// or [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will be
356 /// automatically failed.
359 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
360 /// `PaymentClaimable` events may be generated for the same payment. In such a case it is
361 /// polite (and required in the lightning specification) to fail the payment the second time
362 /// and give the sender their money back rather than accepting double payment.
365 /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
367 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
368 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
369 /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
371 /// The node that will receive the payment after it has been claimed.
372 /// This is useful to identify payments received via [phantom nodes].
373 /// This field will always be filled in when the event was generated by LDK versions
374 /// 0.0.113 and above.
376 /// [phantom nodes]: crate::sign::PhantomKeysManager
377 receiver_node_id: Option<PublicKey>,
378 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
379 /// not stop you from registering duplicate payment hashes for inbound payments.
380 payment_hash: PaymentHash,
381 /// The fields in the onion which were received with each HTLC. Only fields which were
382 /// identical in each HTLC involved in the payment will be included here.
384 /// Payments received on LDK versions prior to 0.0.115 will have this field unset.
385 onion_fields: Option<RecipientOnionFields>,
386 /// The value, in thousandths of a satoshi, that this payment is claimable for. May be greater
387 /// than the invoice amount.
389 /// May be less than the invoice amount if [`ChannelConfig::accept_underpaying_htlcs`] is set
390 /// and the previous hop took an extra fee.
393 /// If [`ChannelConfig::accept_underpaying_htlcs`] is set and you claim without verifying this
394 /// field, you may lose money!
396 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
398 /// The value, in thousands of a satoshi, that was skimmed off of this payment as an extra fee
399 /// taken by our channel counterparty.
401 /// Will always be 0 unless [`ChannelConfig::accept_underpaying_htlcs`] is set.
403 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
404 counterparty_skimmed_fee_msat: u64,
405 /// Information for claiming this received payment, based on whether the purpose of the
406 /// payment is to pay an invoice or to send a spontaneous payment.
407 purpose: PaymentPurpose,
408 /// The `channel_id` indicating over which channel we received the payment.
409 via_channel_id: Option<[u8; 32]>,
410 /// The `user_channel_id` indicating over which channel we received the payment.
411 via_user_channel_id: Option<u128>,
412 /// The block height at which this payment will be failed back and will no longer be
413 /// eligible for claiming.
415 /// Prior to this height, a call to [`ChannelManager::claim_funds`] is guaranteed to
416 /// succeed, however you should wait for [`Event::PaymentClaimed`] to be sure.
418 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
419 claim_deadline: Option<u32>,
421 /// Indicates a payment has been claimed and we've received money!
423 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
424 /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
425 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
426 /// [`Event::PaymentClaimable`] event.
429 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
430 /// `PaymentClaimable` events may be generated for the same payment. If you then call
431 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
432 /// multiple `PaymentClaimed` events.
434 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
436 /// The node that received the payment.
437 /// This is useful to identify payments which were received via [phantom nodes].
438 /// This field will always be filled in when the event was generated by LDK versions
439 /// 0.0.113 and above.
441 /// [phantom nodes]: crate::sign::PhantomKeysManager
442 receiver_node_id: Option<PublicKey>,
443 /// The payment hash of the claimed payment. Note that LDK will not stop you from
444 /// registering duplicate payment hashes for inbound payments.
445 payment_hash: PaymentHash,
446 /// The value, in thousandths of a satoshi, that this payment is for. May be greater than the
449 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
450 /// spontaneous payment.
451 purpose: PaymentPurpose,
453 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
454 /// and we got back the payment preimage for it).
456 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
457 /// event. In this situation, you SHOULD treat this payment as having succeeded.
459 /// The `payment_id` passed to [`ChannelManager::send_payment`].
461 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
462 payment_id: Option<PaymentId>,
463 /// The preimage to the hash given to ChannelManager::send_payment.
464 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
465 /// store it somehow!
466 payment_preimage: PaymentPreimage,
467 /// The hash that was given to [`ChannelManager::send_payment`].
469 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
470 payment_hash: PaymentHash,
471 /// The total fee which was spent at intermediate hops in this payment, across all paths.
473 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
474 /// overpayment to the recipient node.
476 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
477 /// overstate the amount paid, though this is unlikely.
479 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
480 fee_paid_msat: Option<u64>,
482 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
483 /// provide failure information for each path attempt in the payment, including retries.
485 /// This event is provided once there are no further pending HTLCs for the payment and the
486 /// payment is no longer retryable, due either to the [`Retry`] provided or
487 /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
489 /// [`Retry`]: crate::ln::channelmanager::Retry
490 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
492 /// The `payment_id` passed to [`ChannelManager::send_payment`].
494 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
495 payment_id: PaymentId,
496 /// The hash that was given to [`ChannelManager::send_payment`].
498 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
499 payment_hash: PaymentHash,
500 /// The reason the payment failed. This is only `None` for events generated or serialized
501 /// by versions prior to 0.0.115.
502 reason: Option<PaymentFailureReason>,
504 /// Indicates that a path for an outbound payment was successful.
506 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
507 /// [`Event::PaymentSent`] for obtaining the payment preimage.
508 PaymentPathSuccessful {
509 /// The `payment_id` passed to [`ChannelManager::send_payment`].
511 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
512 payment_id: PaymentId,
513 /// The hash that was given to [`ChannelManager::send_payment`].
515 /// This will be `Some` for all payments which completed on LDK 0.0.104 or later.
517 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
518 payment_hash: Option<PaymentHash>,
519 /// The payment path that was successful.
521 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
524 /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
527 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
528 /// [`Event::PaymentFailed`].
530 /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
533 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
535 /// The `payment_id` passed to [`ChannelManager::send_payment`].
537 /// This will be `Some` for all payment paths which failed on LDK 0.0.103 or later.
539 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
540 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
541 payment_id: Option<PaymentId>,
542 /// The hash that was given to [`ChannelManager::send_payment`].
544 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
545 payment_hash: PaymentHash,
546 /// Indicates the payment was rejected for some reason by the recipient. This implies that
547 /// the payment has failed, not just the route in question. If this is not set, the payment may
548 /// be retried via a different route.
549 payment_failed_permanently: bool,
550 /// Extra error details based on the failure type. May contain an update that needs to be
551 /// applied to the [`NetworkGraph`].
553 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
554 failure: PathFailure,
555 /// The payment path that failed.
557 /// The channel responsible for the failed payment path.
559 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
560 /// may not refer to a channel in the public network graph. These aliases may also collide
561 /// with channels in the public network graph.
563 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
564 /// retried. May be `None` for older [`Event`] serializations.
565 short_channel_id: Option<u64>,
567 error_code: Option<u16>,
569 error_data: Option<Vec<u8>>,
571 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
573 /// The id returned by [`ChannelManager::send_probe`].
575 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
576 payment_id: PaymentId,
577 /// The hash generated by [`ChannelManager::send_probe`].
579 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
580 payment_hash: PaymentHash,
581 /// The payment path that was successful.
584 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
586 /// The id returned by [`ChannelManager::send_probe`].
588 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
589 payment_id: PaymentId,
590 /// The hash generated by [`ChannelManager::send_probe`].
592 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
593 payment_hash: PaymentHash,
594 /// The payment path that failed.
596 /// The channel responsible for the failed probe.
598 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
599 /// may not refer to a channel in the public network graph. These aliases may also collide
600 /// with channels in the public network graph.
601 short_channel_id: Option<u64>,
603 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
604 /// a time in the future.
606 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
607 PendingHTLCsForwardable {
608 /// The minimum amount of time that should be waited prior to calling
609 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
610 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
611 /// now + 5*time_forwardable).
612 time_forwardable: Duration,
614 /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
615 /// you've encoded an intercept scid in the receiver's invoice route hints using
616 /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
618 /// [`ChannelManager::forward_intercepted_htlc`] or
619 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
620 /// their docs for more information.
622 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
623 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
624 /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
625 /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
627 /// An id to help LDK identify which HTLC is being forwarded or failed.
628 intercept_id: InterceptId,
629 /// The fake scid that was programmed as the next hop's scid, generated using
630 /// [`ChannelManager::get_intercept_scid`].
632 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
633 requested_next_hop_scid: u64,
634 /// The payment hash used for this HTLC.
635 payment_hash: PaymentHash,
636 /// How many msats were received on the inbound edge of this HTLC.
637 inbound_amount_msat: u64,
638 /// How many msats the payer intended to route to the next node. Depending on the reason you are
639 /// intercepting this payment, you might take a fee by forwarding less than this amount.
640 /// Forwarding less than this amount may break compatibility with LDK versions prior to 0.0.116.
642 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
643 /// check that whatever fee you want has been included here or subtract it as required. Further,
644 /// LDK will not stop you from forwarding more than you received.
645 expected_outbound_amount_msat: u64,
647 /// Used to indicate that an output which you should know how to spend was confirmed on chain
648 /// and is now spendable.
649 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
650 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
651 /// somewhere and spend them when you create on-chain transactions.
653 /// The outputs which you should store as spendable by you.
654 outputs: Vec<SpendableOutputDescriptor>,
656 /// This event is generated when a payment has been successfully forwarded through us and a
657 /// forwarding fee earned.
659 /// The incoming channel between the previous node and us. This is only `None` for events
660 /// generated or serialized by versions prior to 0.0.107.
661 prev_channel_id: Option<[u8; 32]>,
662 /// The outgoing channel between the next node and us. This is only `None` for events
663 /// generated or serialized by versions prior to 0.0.107.
664 next_channel_id: Option<[u8; 32]>,
665 /// The fee, in milli-satoshis, which was earned as a result of the payment.
667 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
668 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
669 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
670 /// claimed the full value in millisatoshis from the source. In this case,
671 /// `claim_from_onchain_tx` will be set.
673 /// If the channel which sent us the payment has been force-closed, we will claim the funds
674 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
675 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
676 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
678 fee_earned_msat: Option<u64>,
679 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
681 claim_from_onchain_tx: bool,
682 /// The final amount forwarded, in milli-satoshis, after the fee is deducted.
684 /// The caveat described above the `fee_earned_msat` field applies here as well.
685 outbound_amount_forwarded_msat: Option<u64>,
687 /// Used to indicate that a channel with the given `channel_id` is being opened and pending
688 /// confirmation on-chain.
690 /// This event is emitted when the funding transaction has been signed and is broadcast to the
691 /// network. For 0conf channels it will be immediately followed by the corresponding
692 /// [`Event::ChannelReady`] event.
694 /// The `channel_id` of the channel that is pending confirmation.
695 channel_id: [u8; 32],
696 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
697 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
698 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
699 /// `user_channel_id` will be randomized for an inbound channel.
701 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
702 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
703 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
704 user_channel_id: u128,
705 /// The `temporary_channel_id` this channel used to be known by during channel establishment.
707 /// Will be `None` for channels created prior to LDK version 0.0.115.
708 former_temporary_channel_id: Option<[u8; 32]>,
709 /// The `node_id` of the channel counterparty.
710 counterparty_node_id: PublicKey,
711 /// The outpoint of the channel's funding transaction.
712 funding_txo: OutPoint,
714 /// Used to indicate that a channel with the given `channel_id` is ready to
715 /// be used. This event is emitted either when the funding transaction has been confirmed
716 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
719 /// The `channel_id` of the channel that is ready.
720 channel_id: [u8; 32],
721 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
722 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
723 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
724 /// `user_channel_id` will be randomized for an inbound channel.
726 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
727 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
728 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
729 user_channel_id: u128,
730 /// The `node_id` of the channel counterparty.
731 counterparty_node_id: PublicKey,
732 /// The features that this channel will operate with.
733 channel_type: ChannelTypeFeatures,
735 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
736 /// process of closure.
738 /// The `channel_id` of the channel which has been closed. Note that on-chain transactions
739 /// resolving the channel are likely still awaiting confirmation.
740 channel_id: [u8; 32],
741 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
742 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
743 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
744 /// `user_channel_id` will be randomized for inbound channels.
745 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
746 /// zero for objects serialized with LDK versions prior to 0.0.102.
748 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
749 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
750 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
751 user_channel_id: u128,
752 /// The reason the channel was closed.
753 reason: ClosureReason
755 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
756 /// inputs for another purpose.
758 /// The channel_id of the channel which has been closed.
759 channel_id: [u8; 32],
760 /// The full transaction received from the user
761 transaction: Transaction
763 /// Indicates a request to open a new channel by a peer.
765 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the
766 /// request, call [`ChannelManager::force_close_without_broadcasting_txn`].
768 /// The event is only triggered when a new open channel request is received and the
769 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
771 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
772 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
773 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
775 /// The temporary channel ID of the channel requested to be opened.
777 /// When responding to the request, the `temporary_channel_id` should be passed
778 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
779 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
781 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
782 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
783 temporary_channel_id: [u8; 32],
784 /// The node_id of the counterparty requesting to open the channel.
786 /// When responding to the request, the `counterparty_node_id` should be passed
787 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
788 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
791 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
792 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
793 counterparty_node_id: PublicKey,
794 /// The channel value of the requested channel.
795 funding_satoshis: u64,
796 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
798 /// The features that this channel will operate with. If you reject the channel, a
799 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
802 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
803 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
806 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
807 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
808 /// 0.0.107. Channels setting this type also need to get manually accepted via
809 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
810 /// or will be rejected otherwise.
812 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
813 channel_type: ChannelTypeFeatures,
815 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
818 /// Some scenarios where this event may be sent include:
819 /// * Insufficient capacity in the outbound channel
820 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
821 /// * When an unknown SCID is requested for forwarding a payment.
822 /// * Expected MPP amount has already been reached
823 /// * The HTLC has timed out
825 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
826 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
828 /// The channel over which the HTLC was received.
829 prev_channel_id: [u8; 32],
830 /// Destination of the HTLC that failed to be processed.
831 failed_next_destination: HTLCDestination,
833 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
834 /// requires confirmed external funds to be readily available to spend.
836 /// LDK does not currently generate this event. It is limited to the scope of channels with
837 /// anchor outputs, which will be introduced in a future release.
838 BumpTransaction(BumpTransactionEvent),
841 impl Writeable for Event {
842 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
844 &Event::FundingGenerationReady { .. } => {
846 // We never write out FundingGenerationReady events as, upon disconnection, peers
847 // drop any channels which have not yet exchanged funding_signed.
849 &Event::PaymentClaimable { ref payment_hash, ref amount_msat, counterparty_skimmed_fee_msat,
850 ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id,
851 ref claim_deadline, ref onion_fields
854 let mut payment_secret = None;
855 let payment_preimage;
857 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
858 payment_secret = Some(secret);
859 payment_preimage = *preimage;
861 PaymentPurpose::SpontaneousPayment(preimage) => {
862 payment_preimage = Some(*preimage);
865 let skimmed_fee_opt = if counterparty_skimmed_fee_msat == 0 { None }
866 else { Some(counterparty_skimmed_fee_msat) };
867 write_tlv_fields!(writer, {
868 (0, payment_hash, required),
869 (1, receiver_node_id, option),
870 (2, payment_secret, option),
871 (3, via_channel_id, option),
872 (4, amount_msat, required),
873 (5, via_user_channel_id, option),
874 // Type 6 was `user_payment_id` on 0.0.103 and earlier
875 (7, claim_deadline, option),
876 (8, payment_preimage, option),
877 (9, onion_fields, option),
878 (10, skimmed_fee_opt, option),
881 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
883 write_tlv_fields!(writer, {
884 (0, payment_preimage, required),
885 (1, payment_hash, required),
886 (3, payment_id, option),
887 (5, fee_paid_msat, option),
890 &Event::PaymentPathFailed {
891 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
892 ref path, ref short_channel_id,
900 error_code.write(writer)?;
902 error_data.write(writer)?;
903 write_tlv_fields!(writer, {
904 (0, payment_hash, required),
905 (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
906 (2, payment_failed_permanently, required),
907 (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
908 (4, path.blinded_tail, option),
909 (5, path.hops, vec_type),
910 (7, short_channel_id, option),
911 (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
912 (11, payment_id, option),
913 (13, failure, required),
916 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
918 // Note that we now ignore these on the read end as we'll re-generate them in
919 // ChannelManager, we write them here only for backwards compatibility.
921 &Event::SpendableOutputs { ref outputs } => {
923 write_tlv_fields!(writer, {
924 (0, WithoutLength(outputs), required),
927 &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
929 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
930 write_tlv_fields!(writer, {
931 (0, intercept_id, required),
932 (2, intercept_scid, required),
933 (4, payment_hash, required),
934 (6, inbound_amount_msat, required),
935 (8, expected_outbound_amount_msat, required),
938 &Event::PaymentForwarded {
939 fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
940 next_channel_id, outbound_amount_forwarded_msat
943 write_tlv_fields!(writer, {
944 (0, fee_earned_msat, option),
945 (1, prev_channel_id, option),
946 (2, claim_from_onchain_tx, required),
947 (3, next_channel_id, option),
948 (5, outbound_amount_forwarded_msat, option),
951 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
953 // `user_channel_id` used to be a single u64 value. In order to remain backwards
954 // compatible with versions prior to 0.0.113, the u128 is serialized as two
955 // separate u64 values.
956 let user_channel_id_low = *user_channel_id as u64;
957 let user_channel_id_high = (*user_channel_id >> 64) as u64;
958 write_tlv_fields!(writer, {
959 (0, channel_id, required),
960 (1, user_channel_id_low, required),
961 (2, reason, required),
962 (3, user_channel_id_high, required),
965 &Event::DiscardFunding { ref channel_id, ref transaction } => {
967 write_tlv_fields!(writer, {
968 (0, channel_id, required),
969 (2, transaction, required)
972 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
974 write_tlv_fields!(writer, {
975 (0, payment_id, required),
976 (2, payment_hash, option),
977 (4, path.hops, vec_type),
978 (6, path.blinded_tail, option),
981 &Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
983 write_tlv_fields!(writer, {
984 (0, payment_id, required),
986 (2, payment_hash, required),
989 &Event::OpenChannelRequest { .. } => {
991 // We never write the OpenChannelRequest events as, upon disconnection, peers
992 // drop any channels which have not yet exchanged funding_signed.
994 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id } => {
996 write_tlv_fields!(writer, {
997 (0, payment_hash, required),
998 (1, receiver_node_id, option),
999 (2, purpose, required),
1000 (4, amount_msat, required),
1003 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1004 21u8.write(writer)?;
1005 write_tlv_fields!(writer, {
1006 (0, payment_id, required),
1007 (2, payment_hash, required),
1008 (4, path.hops, vec_type),
1009 (6, path.blinded_tail, option),
1012 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1013 23u8.write(writer)?;
1014 write_tlv_fields!(writer, {
1015 (0, payment_id, required),
1016 (2, payment_hash, required),
1017 (4, path.hops, vec_type),
1018 (6, short_channel_id, option),
1019 (8, path.blinded_tail, option),
1022 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1023 25u8.write(writer)?;
1024 write_tlv_fields!(writer, {
1025 (0, prev_channel_id, required),
1026 (2, failed_next_destination, required),
1029 &Event::BumpTransaction(ref event)=> {
1030 27u8.write(writer)?;
1032 // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1033 // upon restarting anyway if they remain unresolved.
1034 BumpTransactionEvent::ChannelClose { .. } => {}
1035 BumpTransactionEvent::HTLCResolution { .. } => {}
1037 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1039 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1040 29u8.write(writer)?;
1041 write_tlv_fields!(writer, {
1042 (0, channel_id, required),
1043 (2, user_channel_id, required),
1044 (4, counterparty_node_id, required),
1045 (6, channel_type, required),
1048 &Event::ChannelPending { ref channel_id, ref user_channel_id, ref former_temporary_channel_id, ref counterparty_node_id, ref funding_txo } => {
1049 31u8.write(writer)?;
1050 write_tlv_fields!(writer, {
1051 (0, channel_id, required),
1052 (2, user_channel_id, required),
1053 (4, former_temporary_channel_id, required),
1054 (6, counterparty_node_id, required),
1055 (8, funding_txo, required),
1058 // Note that, going forward, all new events must only write data inside of
1059 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1060 // data via `write_tlv_fields`.
1065 impl MaybeReadable for Event {
1066 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1067 match Readable::read(reader)? {
1068 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
1069 // unlike all other events, thus we return immediately here.
1073 let mut payment_hash = PaymentHash([0; 32]);
1074 let mut payment_preimage = None;
1075 let mut payment_secret = None;
1076 let mut amount_msat = 0;
1077 let mut counterparty_skimmed_fee_msat_opt = None;
1078 let mut receiver_node_id = None;
1079 let mut _user_payment_id = None::<u64>; // Used in 0.0.103 and earlier, no longer written in 0.0.116+.
1080 let mut via_channel_id = None;
1081 let mut claim_deadline = None;
1082 let mut via_user_channel_id = None;
1083 let mut onion_fields = None;
1084 read_tlv_fields!(reader, {
1085 (0, payment_hash, required),
1086 (1, receiver_node_id, option),
1087 (2, payment_secret, option),
1088 (3, via_channel_id, option),
1089 (4, amount_msat, required),
1090 (5, via_user_channel_id, option),
1091 (6, _user_payment_id, option),
1092 (7, claim_deadline, option),
1093 (8, payment_preimage, option),
1094 (9, onion_fields, option),
1095 (10, counterparty_skimmed_fee_msat_opt, option),
1097 let purpose = match payment_secret {
1098 Some(secret) => PaymentPurpose::InvoicePayment {
1100 payment_secret: secret
1102 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1103 None => return Err(msgs::DecodeError::InvalidValue),
1105 Ok(Some(Event::PaymentClaimable {
1109 counterparty_skimmed_fee_msat: counterparty_skimmed_fee_msat_opt.unwrap_or(0),
1112 via_user_channel_id,
1121 let mut payment_preimage = PaymentPreimage([0; 32]);
1122 let mut payment_hash = None;
1123 let mut payment_id = None;
1124 let mut fee_paid_msat = None;
1125 read_tlv_fields!(reader, {
1126 (0, payment_preimage, required),
1127 (1, payment_hash, option),
1128 (3, payment_id, option),
1129 (5, fee_paid_msat, option),
1131 if payment_hash.is_none() {
1132 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
1134 Ok(Some(Event::PaymentSent {
1137 payment_hash: payment_hash.unwrap(),
1146 let error_code = Readable::read(reader)?;
1148 let error_data = Readable::read(reader)?;
1149 let mut payment_hash = PaymentHash([0; 32]);
1150 let mut payment_failed_permanently = false;
1151 let mut network_update = None;
1152 let mut blinded_tail: Option<BlindedTail> = None;
1153 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1154 let mut short_channel_id = None;
1155 let mut payment_id = None;
1156 let mut failure_opt = None;
1157 read_tlv_fields!(reader, {
1158 (0, payment_hash, required),
1159 (1, network_update, upgradable_option),
1160 (2, payment_failed_permanently, required),
1161 (4, blinded_tail, option),
1162 (5, path, vec_type),
1163 (7, short_channel_id, option),
1164 (11, payment_id, option),
1165 (13, failure_opt, upgradable_option),
1167 let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1168 Ok(Some(Event::PaymentPathFailed {
1171 payment_failed_permanently,
1173 path: Path { hops: path.unwrap(), blinded_tail },
1186 let mut outputs = WithoutLength(Vec::new());
1187 read_tlv_fields!(reader, {
1188 (0, outputs, required),
1190 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
1195 let mut payment_hash = PaymentHash([0; 32]);
1196 let mut intercept_id = InterceptId([0; 32]);
1197 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1198 let mut inbound_amount_msat = 0;
1199 let mut expected_outbound_amount_msat = 0;
1200 read_tlv_fields!(reader, {
1201 (0, intercept_id, required),
1202 (2, requested_next_hop_scid, required),
1203 (4, payment_hash, required),
1204 (6, inbound_amount_msat, required),
1205 (8, expected_outbound_amount_msat, required),
1207 let next_scid = match requested_next_hop_scid {
1208 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1210 Ok(Some(Event::HTLCIntercepted {
1212 requested_next_hop_scid: next_scid,
1213 inbound_amount_msat,
1214 expected_outbound_amount_msat,
1220 let mut fee_earned_msat = None;
1221 let mut prev_channel_id = None;
1222 let mut claim_from_onchain_tx = false;
1223 let mut next_channel_id = None;
1224 let mut outbound_amount_forwarded_msat = None;
1225 read_tlv_fields!(reader, {
1226 (0, fee_earned_msat, option),
1227 (1, prev_channel_id, option),
1228 (2, claim_from_onchain_tx, required),
1229 (3, next_channel_id, option),
1230 (5, outbound_amount_forwarded_msat, option),
1232 Ok(Some(Event::PaymentForwarded {
1233 fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id,
1234 outbound_amount_forwarded_msat
1241 let mut channel_id = [0; 32];
1242 let mut reason = UpgradableRequired(None);
1243 let mut user_channel_id_low_opt: Option<u64> = None;
1244 let mut user_channel_id_high_opt: Option<u64> = None;
1245 read_tlv_fields!(reader, {
1246 (0, channel_id, required),
1247 (1, user_channel_id_low_opt, option),
1248 (2, reason, upgradable_required),
1249 (3, user_channel_id_high_opt, option),
1252 // `user_channel_id` used to be a single u64 value. In order to remain
1253 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1254 // as two separate u64 values.
1255 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1256 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1258 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required) }))
1264 let mut channel_id = [0; 32];
1265 let mut transaction = Transaction{ version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
1266 read_tlv_fields!(reader, {
1267 (0, channel_id, required),
1268 (2, transaction, required),
1270 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1276 _init_and_read_tlv_fields!(reader, {
1277 (0, payment_id, required),
1278 (2, payment_hash, option),
1279 (4, path, vec_type),
1280 (6, blinded_tail, option),
1282 Ok(Some(Event::PaymentPathSuccessful {
1283 payment_id: payment_id.0.unwrap(),
1285 path: Path { hops: path.unwrap(), blinded_tail },
1292 let mut payment_hash = PaymentHash([0; 32]);
1293 let mut payment_id = PaymentId([0; 32]);
1294 let mut reason = None;
1295 read_tlv_fields!(reader, {
1296 (0, payment_id, required),
1297 (1, reason, upgradable_option),
1298 (2, payment_hash, required),
1300 Ok(Some(Event::PaymentFailed {
1309 // Value 17 is used for `Event::OpenChannelRequest`.
1314 let mut payment_hash = PaymentHash([0; 32]);
1315 let mut purpose = UpgradableRequired(None);
1316 let mut amount_msat = 0;
1317 let mut receiver_node_id = None;
1318 read_tlv_fields!(reader, {
1319 (0, payment_hash, required),
1320 (1, receiver_node_id, option),
1321 (2, purpose, upgradable_required),
1322 (4, amount_msat, required),
1324 Ok(Some(Event::PaymentClaimed {
1327 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1335 _init_and_read_tlv_fields!(reader, {
1336 (0, payment_id, required),
1337 (2, payment_hash, required),
1338 (4, path, vec_type),
1339 (6, blinded_tail, option),
1341 Ok(Some(Event::ProbeSuccessful {
1342 payment_id: payment_id.0.unwrap(),
1343 payment_hash: payment_hash.0.unwrap(),
1344 path: Path { hops: path.unwrap(), blinded_tail },
1351 _init_and_read_tlv_fields!(reader, {
1352 (0, payment_id, required),
1353 (2, payment_hash, required),
1354 (4, path, vec_type),
1355 (6, short_channel_id, option),
1356 (8, blinded_tail, option),
1358 Ok(Some(Event::ProbeFailed {
1359 payment_id: payment_id.0.unwrap(),
1360 payment_hash: payment_hash.0.unwrap(),
1361 path: Path { hops: path.unwrap(), blinded_tail },
1369 let mut prev_channel_id = [0; 32];
1370 let mut failed_next_destination_opt = UpgradableRequired(None);
1371 read_tlv_fields!(reader, {
1372 (0, prev_channel_id, required),
1373 (2, failed_next_destination_opt, upgradable_required),
1375 Ok(Some(Event::HTLCHandlingFailed {
1377 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1385 let mut channel_id = [0; 32];
1386 let mut user_channel_id: u128 = 0;
1387 let mut counterparty_node_id = RequiredWrapper(None);
1388 let mut channel_type = RequiredWrapper(None);
1389 read_tlv_fields!(reader, {
1390 (0, channel_id, required),
1391 (2, user_channel_id, required),
1392 (4, counterparty_node_id, required),
1393 (6, channel_type, required),
1396 Ok(Some(Event::ChannelReady {
1399 counterparty_node_id: counterparty_node_id.0.unwrap(),
1400 channel_type: channel_type.0.unwrap()
1407 let mut channel_id = [0; 32];
1408 let mut user_channel_id: u128 = 0;
1409 let mut former_temporary_channel_id = None;
1410 let mut counterparty_node_id = RequiredWrapper(None);
1411 let mut funding_txo = RequiredWrapper(None);
1412 read_tlv_fields!(reader, {
1413 (0, channel_id, required),
1414 (2, user_channel_id, required),
1415 (4, former_temporary_channel_id, required),
1416 (6, counterparty_node_id, required),
1417 (8, funding_txo, required),
1420 Ok(Some(Event::ChannelPending {
1423 former_temporary_channel_id,
1424 counterparty_node_id: counterparty_node_id.0.unwrap(),
1425 funding_txo: funding_txo.0.unwrap()
1430 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1431 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1433 x if x % 2 == 1 => {
1434 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1435 // which prefixes the whole thing with a length BigSize. Because the event is
1436 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1437 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1438 // exactly the number of bytes specified, ignoring them entirely.
1439 let tlv_len: BigSize = Readable::read(reader)?;
1440 FixedLengthReader::new(reader, tlv_len.0)
1441 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1444 _ => Err(msgs::DecodeError::InvalidValue)
1449 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1450 /// broadcast to most peers).
1451 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1452 #[derive(Clone, Debug)]
1453 pub enum MessageSendEvent {
1454 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1455 /// message provided to the given peer.
1457 /// The node_id of the node which should receive this message
1459 /// The message which should be sent.
1460 msg: msgs::AcceptChannel,
1462 /// Used to indicate that we've accepted a V2 channel open and should send the accept_channel2
1463 /// message provided to the given peer.
1464 SendAcceptChannelV2 {
1465 /// The node_id of the node which should receive this message
1467 /// The message which should be sent.
1468 msg: msgs::AcceptChannelV2,
1470 /// Used to indicate that we've initiated a channel open and should send the open_channel
1471 /// message provided to the given peer.
1473 /// The node_id of the node which should receive this message
1475 /// The message which should be sent.
1476 msg: msgs::OpenChannel,
1478 /// Used to indicate that we've initiated a V2 channel open and should send the open_channel2
1479 /// message provided to the given peer.
1481 /// The node_id of the node which should receive this message
1483 /// The message which should be sent.
1484 msg: msgs::OpenChannelV2,
1486 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1487 SendFundingCreated {
1488 /// The node_id of the node which should receive this message
1490 /// The message which should be sent.
1491 msg: msgs::FundingCreated,
1493 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1495 /// The node_id of the node which should receive this message
1497 /// The message which should be sent.
1498 msg: msgs::FundingSigned,
1500 /// Used to indicate that a tx_add_input message should be sent to the peer with the given node_id.
1502 /// The node_id of the node which should receive this message
1504 /// The message which should be sent.
1505 msg: msgs::TxAddInput,
1507 /// Used to indicate that a tx_add_output message should be sent to the peer with the given node_id.
1509 /// The node_id of the node which should receive this message
1511 /// The message which should be sent.
1512 msg: msgs::TxAddOutput,
1514 /// Used to indicate that a tx_remove_input message should be sent to the peer with the given node_id.
1516 /// The node_id of the node which should receive this message
1518 /// The message which should be sent.
1519 msg: msgs::TxRemoveInput,
1521 /// Used to indicate that a tx_remove_output message should be sent to the peer with the given node_id.
1522 SendTxRemoveOutput {
1523 /// The node_id of the node which should receive this message
1525 /// The message which should be sent.
1526 msg: msgs::TxRemoveOutput,
1528 /// Used to indicate that a tx_complete message should be sent to the peer with the given node_id.
1530 /// The node_id of the node which should receive this message
1532 /// The message which should be sent.
1533 msg: msgs::TxComplete,
1535 /// Used to indicate that a tx_signatures message should be sent to the peer with the given node_id.
1537 /// The node_id of the node which should receive this message
1539 /// The message which should be sent.
1540 msg: msgs::TxSignatures,
1542 /// Used to indicate that a tx_init_rbf message should be sent to the peer with the given node_id.
1544 /// The node_id of the node which should receive this message
1546 /// The message which should be sent.
1547 msg: msgs::TxInitRbf,
1549 /// Used to indicate that a tx_ack_rbf message should be sent to the peer with the given node_id.
1551 /// The node_id of the node which should receive this message
1553 /// The message which should be sent.
1554 msg: msgs::TxAckRbf,
1556 /// Used to indicate that a tx_abort message should be sent to the peer with the given node_id.
1558 /// The node_id of the node which should receive this message
1560 /// The message which should be sent.
1561 msg: msgs::TxAddInput,
1563 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1565 /// The node_id of the node which should receive these message(s)
1567 /// The channel_ready message which should be sent.
1568 msg: msgs::ChannelReady,
1570 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1571 SendAnnouncementSignatures {
1572 /// The node_id of the node which should receive these message(s)
1574 /// The announcement_signatures message which should be sent.
1575 msg: msgs::AnnouncementSignatures,
1577 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1578 /// message should be sent to the peer with the given node_id.
1580 /// The node_id of the node which should receive these message(s)
1582 /// The update messages which should be sent. ALL messages in the struct should be sent!
1583 updates: msgs::CommitmentUpdate,
1585 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1587 /// The node_id of the node which should receive this message
1589 /// The message which should be sent.
1590 msg: msgs::RevokeAndACK,
1592 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1594 /// The node_id of the node which should receive this message
1596 /// The message which should be sent.
1597 msg: msgs::ClosingSigned,
1599 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1601 /// The node_id of the node which should receive this message
1603 /// The message which should be sent.
1604 msg: msgs::Shutdown,
1606 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1607 SendChannelReestablish {
1608 /// The node_id of the node which should receive this message
1610 /// The message which should be sent.
1611 msg: msgs::ChannelReestablish,
1613 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1614 /// initial connection to ensure our peers know about our channels.
1615 SendChannelAnnouncement {
1616 /// The node_id of the node which should receive this message
1618 /// The channel_announcement which should be sent.
1619 msg: msgs::ChannelAnnouncement,
1620 /// The followup channel_update which should be sent.
1621 update_msg: msgs::ChannelUpdate,
1623 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1624 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1626 /// Note that after doing so, you very likely (unless you did so very recently) want to
1627 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1628 /// ensures that any nodes which see our channel_announcement also have a relevant
1629 /// node_announcement, including relevant feature flags which may be important for routing
1630 /// through or to us.
1632 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1633 BroadcastChannelAnnouncement {
1634 /// The channel_announcement which should be sent.
1635 msg: msgs::ChannelAnnouncement,
1636 /// The followup channel_update which should be sent.
1637 update_msg: Option<msgs::ChannelUpdate>,
1639 /// Used to indicate that a channel_update should be broadcast to all peers.
1640 BroadcastChannelUpdate {
1641 /// The channel_update which should be sent.
1642 msg: msgs::ChannelUpdate,
1644 /// Used to indicate that a node_announcement should be broadcast to all peers.
1645 BroadcastNodeAnnouncement {
1646 /// The node_announcement which should be sent.
1647 msg: msgs::NodeAnnouncement,
1649 /// Used to indicate that a channel_update should be sent to a single peer.
1650 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1651 /// private channel and we shouldn't be informing all of our peers of channel parameters.
1653 /// The node_id of the node which should receive this message
1655 /// The channel_update which should be sent.
1656 msg: msgs::ChannelUpdate,
1658 /// Broadcast an error downstream to be handled
1660 /// The node_id of the node which should receive this message
1662 /// The action which should be taken.
1663 action: msgs::ErrorAction
1665 /// Query a peer for channels with funding transaction UTXOs in a block range.
1666 SendChannelRangeQuery {
1667 /// The node_id of this message recipient
1669 /// The query_channel_range which should be sent.
1670 msg: msgs::QueryChannelRange,
1672 /// Request routing gossip messages from a peer for a list of channels identified by
1673 /// their short_channel_ids.
1675 /// The node_id of this message recipient
1677 /// The query_short_channel_ids which should be sent.
1678 msg: msgs::QueryShortChannelIds,
1680 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1681 /// emitted during processing of the query.
1682 SendReplyChannelRange {
1683 /// The node_id of this message recipient
1685 /// The reply_channel_range which should be sent.
1686 msg: msgs::ReplyChannelRange,
1688 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1689 /// enable receiving gossip messages from the peer.
1690 SendGossipTimestampFilter {
1691 /// The node_id of this message recipient
1693 /// The gossip_timestamp_filter which should be sent.
1694 msg: msgs::GossipTimestampFilter,
1698 /// A trait indicating an object may generate message send events
1699 pub trait MessageSendEventsProvider {
1700 /// Gets the list of pending events which were generated by previous actions, clearing the list
1702 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1705 /// A trait indicating an object may generate onion messages to send
1706 pub trait OnionMessageProvider {
1707 /// Gets the next pending onion message for the peer with the given node id.
1708 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<msgs::OnionMessage>;
1711 /// A trait indicating an object may generate events.
1713 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1715 /// Implementations of this trait may also feature an async version of event handling, as shown with
1716 /// [`ChannelManager::process_pending_events_async`] and
1717 /// [`ChainMonitor::process_pending_events_async`].
1721 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1722 /// event since the last invocation.
1724 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1725 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1726 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1727 /// relevant changes to disk *before* returning.
1729 /// Further, because an application may crash between an [`Event`] being handled and the
1730 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1731 /// effect, [`Event`]s may be replayed.
1733 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1734 /// consult the provider's documentation on the implication of processing events and how a handler
1735 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1736 /// [`ChainMonitor::process_pending_events`]).
1738 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1741 /// [`process_pending_events`]: Self::process_pending_events
1742 /// [`handle_event`]: EventHandler::handle_event
1743 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1744 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1745 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
1746 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
1747 pub trait EventsProvider {
1748 /// Processes any events generated since the last call using the given event handler.
1750 /// See the trait-level documentation for requirements.
1751 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1754 /// A trait implemented for objects handling events from [`EventsProvider`].
1756 /// An async variation also exists for implementations of [`EventsProvider`] that support async
1757 /// event handling. The async event handler should satisfy the generic bounds: `F:
1758 /// core::future::Future, H: Fn(Event) -> F`.
1759 pub trait EventHandler {
1760 /// Handles the given [`Event`].
1762 /// See [`EventsProvider`] for details that must be considered when implementing this method.
1763 fn handle_event(&self, event: Event);
1766 impl<F> EventHandler for F where F: Fn(Event) {
1767 fn handle_event(&self, event: Event) {
1772 impl<T: EventHandler> EventHandler for Arc<T> {
1773 fn handle_event(&self, event: Event) {
1774 self.deref().handle_event(event)