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
18 pub mod bump_transaction;
21 pub use bump_transaction::BumpTransactionEvent;
23 use crate::sign::SpendableOutputDescriptor;
24 use crate::ln::channelmanager::{InterceptId, PaymentId, RecipientOnionFields};
25 use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
26 use crate::ln::features::ChannelTypeFeatures;
28 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
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::{PackedLockTime, Transaction, OutPoint};
37 use bitcoin::{Txid, TxIn, TxOut, Witness};
38 use bitcoin::blockdata::script::Script;
39 use bitcoin::hashes::Hash;
40 use bitcoin::hashes::sha256::Hash as Sha256;
41 use bitcoin::secp256k1::PublicKey;
43 use crate::prelude::*;
44 use core::time::Duration;
48 /// Some information provided on receipt of payment depends on whether the payment received is a
49 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
50 #[derive(Clone, Debug, PartialEq, Eq)]
51 pub enum PaymentPurpose {
52 /// Information for receiving a payment that we generated an invoice for.
54 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
55 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
56 /// [`ChannelManager::claim_funds`].
58 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
59 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
60 payment_preimage: Option<PaymentPreimage>,
61 /// The "payment secret". This authenticates the sender to the recipient, preventing a
62 /// number of deanonymization attacks during the routing process.
63 /// It is provided here for your reference, however its accuracy is enforced directly by
64 /// [`ChannelManager`] using the values you previously provided to
65 /// [`ChannelManager::create_inbound_payment`] or
66 /// [`ChannelManager::create_inbound_payment_for_hash`].
68 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
69 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
70 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
71 payment_secret: PaymentSecret,
73 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
74 /// (the payee) providing a preimage.
75 SpontaneousPayment(PaymentPreimage),
78 impl_writeable_tlv_based_enum!(PaymentPurpose,
79 (0, InvoicePayment) => {
80 (0, payment_preimage, option),
81 (2, payment_secret, required),
83 (2, SpontaneousPayment)
86 /// When the payment path failure took place and extra details about it. [`PathFailure::OnPath`] may
87 /// contain a [`NetworkUpdate`] that needs to be applied to the [`NetworkGraph`].
89 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
90 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
91 #[derive(Clone, Debug, Eq, PartialEq)]
92 pub enum PathFailure {
93 /// We failed to initially send the payment and no HTLC was committed to. Contains the relevant
96 /// The error surfaced from initial send.
99 /// A hop on the path failed to forward our payment.
101 /// If present, this [`NetworkUpdate`] should be applied to the [`NetworkGraph`] so that routing
102 /// decisions can take into account the update.
104 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
105 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
106 network_update: Option<NetworkUpdate>,
110 impl_writeable_tlv_based_enum_upgradable!(PathFailure,
112 (0, network_update, upgradable_option),
114 (2, InitialSend) => {
115 (0, err, upgradable_required),
119 #[derive(Clone, Debug, PartialEq, Eq)]
120 /// The reason the channel was closed. See individual variants more details.
121 pub enum ClosureReason {
122 /// Closure generated from receiving a peer error message.
124 /// Our counterparty may have broadcasted their latest commitment state, and we have
126 CounterpartyForceClosed {
127 /// The error which the peer sent us.
129 /// Be careful about printing the peer_msg, a well-crafted message could exploit
130 /// a security vulnerability in the terminal emulator or the logging subsystem.
131 /// To be safe, use `Display` on `UntrustedString`
133 /// [`UntrustedString`]: crate::util::string::UntrustedString
134 peer_msg: UntrustedString,
136 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
138 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
140 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
141 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
142 //TODO: split between CounterpartyInitiated/LocallyInitiated
144 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
145 /// commitment transaction came from our counterparty, but it may also have come from
146 /// a copy of our own `ChannelMonitor`.
147 CommitmentTxConfirmed,
148 /// The funding transaction failed to confirm in a timely manner on an inbound channel.
150 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
152 /// A developer-readable error message which we generated.
155 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
156 /// forget the channel entirely - we can attempt again if the peer reconnects.
158 /// This includes cases where we restarted prior to funding completion, including prior to the
159 /// initial [`ChannelMonitor`] persistence completing.
161 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
162 /// peer because of mutual incompatibility between us and our channel counterparty.
164 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
166 /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
167 /// the [`ChannelManager`] deserialized.
169 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
170 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
171 OutdatedChannelManager
174 impl core::fmt::Display for ClosureReason {
175 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
176 f.write_str("Channel closed because ")?;
178 ClosureReason::CounterpartyForceClosed { peer_msg } => {
179 f.write_fmt(format_args!("counterparty force-closed with message: {}", peer_msg))
181 ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
182 ClosureReason::CooperativeClosure => f.write_str("the channel was cooperatively closed"),
183 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
184 ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
185 ClosureReason::ProcessingError { err } => {
186 f.write_str("of an exception: ")?;
189 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
190 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
195 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
196 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
197 (1, FundingTimedOut) => {},
198 (2, HolderForceClosed) => {},
199 (6, CommitmentTxConfirmed) => {},
200 (4, CooperativeClosure) => {},
201 (8, ProcessingError) => { (1, err, required) },
202 (10, DisconnectedPeer) => {},
203 (12, OutdatedChannelManager) => {},
206 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
207 #[derive(Clone, Debug, PartialEq, Eq)]
208 pub enum HTLCDestination {
209 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
210 /// there is insufficient capacity in our outbound channel.
212 /// The `node_id` of the next node. For backwards compatibility, this field is
213 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
214 /// counterparty node information.
215 node_id: Option<PublicKey>,
216 /// The outgoing `channel_id` between us and the next node.
217 channel_id: [u8; 32],
219 /// Scenario where we are unsure of the next node to forward the HTLC to.
221 /// Short channel id we are requesting to forward an HTLC to.
222 requested_forward_scid: u64,
224 /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
227 /// Short channel id we are requesting to forward an HTLC to.
228 requested_forward_scid: u64
230 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
231 /// but is invalid for some reason, so we reject it.
233 /// Some of the reasons may include:
235 /// * Excess HTLCs for a payment that we have already fully received, over-paying for the
237 /// * The counterparty node modified the HTLC in transit,
238 /// * A probing attack where an intermediary node is trying to detect if we are the ultimate
239 /// recipient for a payment.
241 /// The payment hash of the payment we attempted to process.
242 payment_hash: PaymentHash
246 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
247 (0, NextHopChannel) => {
248 (0, node_id, required),
249 (2, channel_id, required),
251 (1, InvalidForward) => {
252 (0, requested_forward_scid, required),
254 (2, UnknownNextHop) => {
255 (0, requested_forward_scid, required),
257 (4, FailedPayment) => {
258 (0, payment_hash, required),
262 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
263 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
264 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
265 /// intercepts in upcoming work.
266 enum InterceptNextHop {
268 requested_next_hop_scid: u64,
272 impl_writeable_tlv_based_enum!(InterceptNextHop,
274 (0, requested_next_hop_scid, required),
278 /// The reason the payment failed. Used in [`Event::PaymentFailed`].
279 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
280 pub enum PaymentFailureReason {
281 /// The intended recipient rejected our payment.
283 /// The user chose to abandon this payment by calling [`ChannelManager::abandon_payment`].
285 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
287 /// We exhausted all of our retry attempts while trying to send the payment, or we
288 /// exhausted the [`Retry::Timeout`] if the user set one. If at any point a retry
289 /// attempt failed while being forwarded along the path, an [`Event::PaymentPathFailed`] will
290 /// have come before this.
292 /// [`Retry::Timeout`]: crate::ln::channelmanager::Retry::Timeout
294 /// The payment expired while retrying, based on the provided
295 /// [`PaymentParameters::expiry_time`].
297 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
299 /// We failed to find a route while retrying the payment.
301 /// This error should generally never happen. This likely means that there is a problem with
306 impl_writeable_tlv_based_enum!(PaymentFailureReason,
307 (0, RecipientRejected) => {},
308 (2, UserAbandoned) => {},
309 (4, RetriesExhausted) => {},
310 (6, PaymentExpired) => {},
311 (8, RouteNotFound) => {},
312 (10, UnexpectedError) => {}, ;
315 /// An Event which you should probably take some action in response to.
317 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
318 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
319 /// written as it makes no sense to respond to it after reconnecting to peers).
320 #[derive(Clone, Debug, PartialEq, Eq)]
322 /// Used to indicate that the client should generate a funding transaction with the given
323 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
324 /// Generated in [`ChannelManager`] message handling.
325 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
326 /// counterparty can steal your funds!
328 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
329 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
330 FundingGenerationReady {
331 /// The random channel_id we picked which you'll need to pass into
332 /// [`ChannelManager::funding_transaction_generated`].
334 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
335 temporary_channel_id: [u8; 32],
336 /// The counterparty's node_id, which you'll need to pass back into
337 /// [`ChannelManager::funding_transaction_generated`].
339 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
340 counterparty_node_id: PublicKey,
341 /// The value, in satoshis, that the output should have.
342 channel_value_satoshis: u64,
343 /// The script which should be used in the transaction output.
344 output_script: Script,
345 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or a
346 /// random value for an inbound channel. This may be zero for objects serialized with LDK
347 /// versions prior to 0.0.113.
349 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
350 user_channel_id: u128,
352 /// Indicates that we've been offered a payment and it needs to be claimed via calling
353 /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
355 /// Note that if the preimage is not known, you should call
356 /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
357 /// to free up resources for this HTLC and avoid network congestion.
358 /// If you fail to call either [`ChannelManager::claim_funds`], [`ChannelManager::fail_htlc_backwards`],
359 /// or [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will be
360 /// automatically failed.
363 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
364 /// `PaymentClaimable` events may be generated for the same payment. In such a case it is
365 /// polite (and required in the lightning specification) to fail the payment the second time
366 /// and give the sender their money back rather than accepting double payment.
369 /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
371 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
372 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
373 /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
375 /// The node that will receive the payment after it has been claimed.
376 /// This is useful to identify payments received via [phantom nodes].
377 /// This field will always be filled in when the event was generated by LDK versions
378 /// 0.0.113 and above.
380 /// [phantom nodes]: crate::sign::PhantomKeysManager
381 receiver_node_id: Option<PublicKey>,
382 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
383 /// not stop you from registering duplicate payment hashes for inbound payments.
384 payment_hash: PaymentHash,
385 /// The fields in the onion which were received with each HTLC. Only fields which were
386 /// identical in each HTLC involved in the payment will be included here.
388 /// Payments received on LDK versions prior to 0.0.115 will have this field unset.
389 onion_fields: Option<RecipientOnionFields>,
390 /// The value, in thousandths of a satoshi, that this payment is claimable for.
392 /// May be less than the invoice amount if [`ChannelConfig::accept_underpaying_htlcs`] is set
393 /// and the previous hop took an extra fee.
396 /// If [`ChannelConfig::accept_underpaying_htlcs`] is set and you claim without verifying this
397 /// field, you may lose money!
399 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
401 /// The value, in thousands of a satoshi, that was skimmed off of this payment as an extra fee
402 /// taken by our channel counterparty.
404 /// Will always be 0 unless [`ChannelConfig::accept_underpaying_htlcs`] is set.
406 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
407 counterparty_skimmed_fee_msat: u64,
408 /// Information for claiming this received payment, based on whether the purpose of the
409 /// payment is to pay an invoice or to send a spontaneous payment.
410 purpose: PaymentPurpose,
411 /// The `channel_id` indicating over which channel we received the payment.
412 via_channel_id: Option<[u8; 32]>,
413 /// The `user_channel_id` indicating over which channel we received the payment.
414 via_user_channel_id: Option<u128>,
415 /// The block height at which this payment will be failed back and will no longer be
416 /// eligible for claiming.
418 /// Prior to this height, a call to [`ChannelManager::claim_funds`] is guaranteed to
419 /// succeed, however you should wait for [`Event::PaymentClaimed`] to be sure.
421 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
422 claim_deadline: Option<u32>,
424 /// Indicates a payment has been claimed and we've received money!
426 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
427 /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
428 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
429 /// [`Event::PaymentClaimable`] event.
432 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
433 /// `PaymentClaimable` events may be generated for the same payment. If you then call
434 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
435 /// multiple `PaymentClaimed` events.
437 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
439 /// The node that received the payment.
440 /// This is useful to identify payments which were received via [phantom nodes].
441 /// This field will always be filled in when the event was generated by LDK versions
442 /// 0.0.113 and above.
444 /// [phantom nodes]: crate::sign::PhantomKeysManager
445 receiver_node_id: Option<PublicKey>,
446 /// The payment hash of the claimed payment. Note that LDK will not stop you from
447 /// registering duplicate payment hashes for inbound payments.
448 payment_hash: PaymentHash,
449 /// The value, in thousandths of a satoshi, that this payment is for.
451 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
452 /// spontaneous payment.
453 purpose: PaymentPurpose,
455 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
456 /// and we got back the payment preimage for it).
458 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
459 /// event. In this situation, you SHOULD treat this payment as having succeeded.
461 /// The `payment_id` passed to [`ChannelManager::send_payment`].
463 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
464 payment_id: Option<PaymentId>,
465 /// The preimage to the hash given to ChannelManager::send_payment.
466 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
467 /// store it somehow!
468 payment_preimage: PaymentPreimage,
469 /// The hash that was given to [`ChannelManager::send_payment`].
471 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
472 payment_hash: PaymentHash,
473 /// The total fee which was spent at intermediate hops in this payment, across all paths.
475 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
476 /// overpayment to the recipient node.
478 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
479 /// overstate the amount paid, though this is unlikely.
481 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
482 fee_paid_msat: Option<u64>,
484 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
485 /// provide failure information for each path attempt in the payment, including retries.
487 /// This event is provided once there are no further pending HTLCs for the payment and the
488 /// payment is no longer retryable, due either to the [`Retry`] provided or
489 /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
491 /// [`Retry`]: crate::ln::channelmanager::Retry
492 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
494 /// The `payment_id` passed to [`ChannelManager::send_payment`].
496 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
497 payment_id: PaymentId,
498 /// The hash that was given to [`ChannelManager::send_payment`].
500 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
501 payment_hash: PaymentHash,
502 /// The reason the payment failed. This is only `None` for events generated or serialized
503 /// by versions prior to 0.0.115.
504 reason: Option<PaymentFailureReason>,
506 /// Indicates that a path for an outbound payment was successful.
508 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
509 /// [`Event::PaymentSent`] for obtaining the payment preimage.
510 PaymentPathSuccessful {
511 /// The `payment_id` passed to [`ChannelManager::send_payment`].
513 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
514 payment_id: PaymentId,
515 /// The hash that was given to [`ChannelManager::send_payment`].
517 /// This will be `Some` for all payments which completed on LDK 0.0.104 or later.
519 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
520 payment_hash: Option<PaymentHash>,
521 /// The payment path that was successful.
523 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
526 /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
529 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
530 /// [`Event::PaymentFailed`].
532 /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
535 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
537 /// The `payment_id` passed to [`ChannelManager::send_payment`].
539 /// This will be `Some` for all payment paths which failed on LDK 0.0.103 or later.
541 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
542 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
543 payment_id: Option<PaymentId>,
544 /// The hash that was given to [`ChannelManager::send_payment`].
546 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
547 payment_hash: PaymentHash,
548 /// Indicates the payment was rejected for some reason by the recipient. This implies that
549 /// the payment has failed, not just the route in question. If this is not set, the payment may
550 /// be retried via a different route.
551 payment_failed_permanently: bool,
552 /// Extra error details based on the failure type. May contain an update that needs to be
553 /// applied to the [`NetworkGraph`].
555 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
556 failure: PathFailure,
557 /// The payment path that failed.
559 /// The channel responsible for the failed payment path.
561 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
562 /// may not refer to a channel in the public network graph. These aliases may also collide
563 /// with channels in the public network graph.
565 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
566 /// retried. May be `None` for older [`Event`] serializations.
567 short_channel_id: Option<u64>,
569 error_code: Option<u16>,
571 error_data: Option<Vec<u8>>,
573 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
575 /// The id returned by [`ChannelManager::send_probe`].
577 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
578 payment_id: PaymentId,
579 /// The hash generated by [`ChannelManager::send_probe`].
581 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
582 payment_hash: PaymentHash,
583 /// The payment path that was successful.
586 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
588 /// The id returned by [`ChannelManager::send_probe`].
590 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
591 payment_id: PaymentId,
592 /// The hash generated by [`ChannelManager::send_probe`].
594 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
595 payment_hash: PaymentHash,
596 /// The payment path that failed.
598 /// The channel responsible for the failed probe.
600 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
601 /// may not refer to a channel in the public network graph. These aliases may also collide
602 /// with channels in the public network graph.
603 short_channel_id: Option<u64>,
605 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
606 /// a time in the future.
608 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
609 PendingHTLCsForwardable {
610 /// The minimum amount of time that should be waited prior to calling
611 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
612 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
613 /// now + 5*time_forwardable).
614 time_forwardable: Duration,
616 /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
617 /// you've encoded an intercept scid in the receiver's invoice route hints using
618 /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
620 /// [`ChannelManager::forward_intercepted_htlc`] or
621 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
622 /// their docs for more information.
624 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
625 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
626 /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
627 /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
629 /// An id to help LDK identify which HTLC is being forwarded or failed.
630 intercept_id: InterceptId,
631 /// The fake scid that was programmed as the next hop's scid, generated using
632 /// [`ChannelManager::get_intercept_scid`].
634 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
635 requested_next_hop_scid: u64,
636 /// The payment hash used for this HTLC.
637 payment_hash: PaymentHash,
638 /// How many msats were received on the inbound edge of this HTLC.
639 inbound_amount_msat: u64,
640 /// How many msats the payer intended to route to the next node. Depending on the reason you are
641 /// intercepting this payment, you might take a fee by forwarding less than this amount.
642 /// Forwarding less than this amount may break compatibility with LDK versions prior to 0.0.116.
644 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
645 /// check that whatever fee you want has been included here or subtract it as required. Further,
646 /// LDK will not stop you from forwarding more than you received.
647 expected_outbound_amount_msat: u64,
649 /// Used to indicate that an output which you should know how to spend was confirmed on chain
650 /// and is now spendable.
651 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
652 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
653 /// somewhere and spend them when you create on-chain transactions.
655 /// The outputs which you should store as spendable by you.
656 outputs: Vec<SpendableOutputDescriptor>,
658 /// This event is generated when a payment has been successfully forwarded through us and a
659 /// forwarding fee earned.
661 /// The incoming channel between the previous node and us. This is only `None` for events
662 /// generated or serialized by versions prior to 0.0.107.
663 prev_channel_id: Option<[u8; 32]>,
664 /// The outgoing channel between the next node and us. This is only `None` for events
665 /// generated or serialized by versions prior to 0.0.107.
666 next_channel_id: Option<[u8; 32]>,
667 /// The fee, in milli-satoshis, which was earned as a result of the payment.
669 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
670 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
671 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
672 /// claimed the full value in millisatoshis from the source. In this case,
673 /// `claim_from_onchain_tx` will be set.
675 /// If the channel which sent us the payment has been force-closed, we will claim the funds
676 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
677 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
678 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
680 fee_earned_msat: Option<u64>,
681 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
683 claim_from_onchain_tx: bool,
684 /// The final amount forwarded, in milli-satoshis, after the fee is deducted.
686 /// The caveat described above the `fee_earned_msat` field applies here as well.
687 outbound_amount_forwarded_msat: Option<u64>,
689 /// Used to indicate that a channel with the given `channel_id` is being opened and pending
690 /// confirmation on-chain.
692 /// This event is emitted when the funding transaction has been signed and is broadcast to the
693 /// network. For 0conf channels it will be immediately followed by the corresponding
694 /// [`Event::ChannelReady`] event.
696 /// The `channel_id` of the channel that is pending confirmation.
697 channel_id: [u8; 32],
698 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
699 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
700 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
701 /// `user_channel_id` will be randomized for an inbound channel.
703 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
704 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
705 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
706 user_channel_id: u128,
707 /// The `temporary_channel_id` this channel used to be known by during channel establishment.
709 /// Will be `None` for channels created prior to LDK version 0.0.115.
710 former_temporary_channel_id: Option<[u8; 32]>,
711 /// The `node_id` of the channel counterparty.
712 counterparty_node_id: PublicKey,
713 /// The outpoint of the channel's funding transaction.
714 funding_txo: OutPoint,
716 /// Used to indicate that a channel with the given `channel_id` is ready to
717 /// be used. This event is emitted either when the funding transaction has been confirmed
718 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
721 /// The `channel_id` of the channel that is ready.
722 channel_id: [u8; 32],
723 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
724 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
725 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
726 /// `user_channel_id` will be randomized for an inbound channel.
728 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
729 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
730 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
731 user_channel_id: u128,
732 /// The `node_id` of the channel counterparty.
733 counterparty_node_id: PublicKey,
734 /// The features that this channel will operate with.
735 channel_type: ChannelTypeFeatures,
737 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
738 /// process of closure.
740 /// The `channel_id` of the channel which has been closed. Note that on-chain transactions
741 /// resolving the channel are likely still awaiting confirmation.
742 channel_id: [u8; 32],
743 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
744 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
745 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
746 /// `user_channel_id` will be randomized for inbound channels.
747 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
748 /// zero for objects serialized with LDK versions prior to 0.0.102.
750 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
751 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
752 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
753 user_channel_id: u128,
754 /// The reason the channel was closed.
755 reason: ClosureReason
757 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
758 /// inputs for another purpose.
760 /// The channel_id of the channel which has been closed.
761 channel_id: [u8; 32],
762 /// The full transaction received from the user
763 transaction: Transaction
765 /// Indicates a request to open a new channel by a peer.
767 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the
768 /// request, call [`ChannelManager::force_close_without_broadcasting_txn`].
770 /// The event is only triggered when a new open channel request is received and the
771 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
773 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
774 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
775 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
777 /// The temporary channel ID of the channel requested to be opened.
779 /// When responding to the request, the `temporary_channel_id` should be passed
780 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
781 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
783 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
784 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
785 temporary_channel_id: [u8; 32],
786 /// The node_id of the counterparty requesting to open the channel.
788 /// When responding to the request, the `counterparty_node_id` should be passed
789 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
790 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
793 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
794 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
795 counterparty_node_id: PublicKey,
796 /// The channel value of the requested channel.
797 funding_satoshis: u64,
798 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
800 /// The features that this channel will operate with. If you reject the channel, a
801 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
804 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
805 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
808 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
809 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
810 /// 0.0.107. Channels setting this type also need to get manually accepted via
811 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
812 /// or will be rejected otherwise.
814 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
815 channel_type: ChannelTypeFeatures,
817 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
820 /// Some scenarios where this event may be sent include:
821 /// * Insufficient capacity in the outbound channel
822 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
823 /// * When an unknown SCID is requested for forwarding a payment.
824 /// * Expected MPP amount has already been reached
825 /// * The HTLC has timed out
827 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
828 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
830 /// The channel over which the HTLC was received.
831 prev_channel_id: [u8; 32],
832 /// Destination of the HTLC that failed to be processed.
833 failed_next_destination: HTLCDestination,
836 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
837 /// requires confirmed external funds to be readily available to spend.
839 /// LDK does not currently generate this event. It is limited to the scope of channels with
840 /// anchor outputs, which will be introduced in a future release.
841 BumpTransaction(BumpTransactionEvent),
844 impl Writeable for Event {
845 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
847 &Event::FundingGenerationReady { .. } => {
849 // We never write out FundingGenerationReady events as, upon disconnection, peers
850 // drop any channels which have not yet exchanged funding_signed.
852 &Event::PaymentClaimable { ref payment_hash, ref amount_msat, counterparty_skimmed_fee_msat,
853 ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id,
854 ref claim_deadline, ref onion_fields
857 let mut payment_secret = None;
858 let payment_preimage;
860 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
861 payment_secret = Some(secret);
862 payment_preimage = *preimage;
864 PaymentPurpose::SpontaneousPayment(preimage) => {
865 payment_preimage = Some(*preimage);
868 let skimmed_fee_opt = if counterparty_skimmed_fee_msat == 0 { None }
869 else { Some(counterparty_skimmed_fee_msat) };
870 write_tlv_fields!(writer, {
871 (0, payment_hash, required),
872 (1, receiver_node_id, option),
873 (2, payment_secret, option),
874 (3, via_channel_id, option),
875 (4, amount_msat, required),
876 (5, via_user_channel_id, option),
877 (6, 0u64, required), // user_payment_id required for compatibility with 0.0.103 and earlier
878 (7, claim_deadline, option),
879 (8, payment_preimage, option),
880 (9, onion_fields, option),
881 (10, skimmed_fee_opt, option),
884 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
886 write_tlv_fields!(writer, {
887 (0, payment_preimage, required),
888 (1, payment_hash, required),
889 (3, payment_id, option),
890 (5, fee_paid_msat, option),
893 &Event::PaymentPathFailed {
894 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
895 ref path, ref short_channel_id,
903 error_code.write(writer)?;
905 error_data.write(writer)?;
906 write_tlv_fields!(writer, {
907 (0, payment_hash, required),
908 (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
909 (2, payment_failed_permanently, required),
910 (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
911 (4, path.blinded_tail, option),
912 (5, path.hops, vec_type),
913 (7, short_channel_id, option),
914 (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
915 (11, payment_id, option),
916 (13, failure, required),
919 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
921 // Note that we now ignore these on the read end as we'll re-generate them in
922 // ChannelManager, we write them here only for backwards compatibility.
924 &Event::SpendableOutputs { ref outputs } => {
926 write_tlv_fields!(writer, {
927 (0, WithoutLength(outputs), required),
930 &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
932 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
933 write_tlv_fields!(writer, {
934 (0, intercept_id, required),
935 (2, intercept_scid, required),
936 (4, payment_hash, required),
937 (6, inbound_amount_msat, required),
938 (8, expected_outbound_amount_msat, required),
941 &Event::PaymentForwarded {
942 fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
943 next_channel_id, outbound_amount_forwarded_msat
946 write_tlv_fields!(writer, {
947 (0, fee_earned_msat, option),
948 (1, prev_channel_id, option),
949 (2, claim_from_onchain_tx, required),
950 (3, next_channel_id, option),
951 (5, outbound_amount_forwarded_msat, option),
954 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
956 // `user_channel_id` used to be a single u64 value. In order to remain backwards
957 // compatible with versions prior to 0.0.113, the u128 is serialized as two
958 // separate u64 values.
959 let user_channel_id_low = *user_channel_id as u64;
960 let user_channel_id_high = (*user_channel_id >> 64) as u64;
961 write_tlv_fields!(writer, {
962 (0, channel_id, required),
963 (1, user_channel_id_low, required),
964 (2, reason, required),
965 (3, user_channel_id_high, required),
968 &Event::DiscardFunding { ref channel_id, ref transaction } => {
970 write_tlv_fields!(writer, {
971 (0, channel_id, required),
972 (2, transaction, required)
975 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
977 write_tlv_fields!(writer, {
978 (0, payment_id, required),
979 (2, payment_hash, option),
980 (4, path.hops, vec_type),
981 (6, path.blinded_tail, option),
984 &Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
986 write_tlv_fields!(writer, {
987 (0, payment_id, required),
989 (2, payment_hash, required),
992 &Event::OpenChannelRequest { .. } => {
994 // We never write the OpenChannelRequest events as, upon disconnection, peers
995 // drop any channels which have not yet exchanged funding_signed.
997 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id } => {
999 write_tlv_fields!(writer, {
1000 (0, payment_hash, required),
1001 (1, receiver_node_id, option),
1002 (2, purpose, required),
1003 (4, amount_msat, required),
1006 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1007 21u8.write(writer)?;
1008 write_tlv_fields!(writer, {
1009 (0, payment_id, required),
1010 (2, payment_hash, required),
1011 (4, path.hops, vec_type),
1012 (6, path.blinded_tail, option),
1015 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1016 23u8.write(writer)?;
1017 write_tlv_fields!(writer, {
1018 (0, payment_id, required),
1019 (2, payment_hash, required),
1020 (4, path.hops, vec_type),
1021 (6, short_channel_id, option),
1022 (8, path.blinded_tail, option),
1025 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1026 25u8.write(writer)?;
1027 write_tlv_fields!(writer, {
1028 (0, prev_channel_id, required),
1029 (2, failed_next_destination, required),
1033 &Event::BumpTransaction(ref event)=> {
1034 27u8.write(writer)?;
1036 // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1037 // upon restarting anyway if they remain unresolved.
1038 BumpTransactionEvent::ChannelClose { .. } => {}
1039 BumpTransactionEvent::HTLCResolution { .. } => {}
1041 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1043 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1044 29u8.write(writer)?;
1045 write_tlv_fields!(writer, {
1046 (0, channel_id, required),
1047 (2, user_channel_id, required),
1048 (4, counterparty_node_id, required),
1049 (6, channel_type, required),
1052 &Event::ChannelPending { ref channel_id, ref user_channel_id, ref former_temporary_channel_id, ref counterparty_node_id, ref funding_txo } => {
1053 31u8.write(writer)?;
1054 write_tlv_fields!(writer, {
1055 (0, channel_id, required),
1056 (2, user_channel_id, required),
1057 (4, former_temporary_channel_id, required),
1058 (6, counterparty_node_id, required),
1059 (8, funding_txo, required),
1062 // Note that, going forward, all new events must only write data inside of
1063 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1064 // data via `write_tlv_fields`.
1069 impl MaybeReadable for Event {
1070 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1071 match Readable::read(reader)? {
1072 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
1073 // unlike all other events, thus we return immediately here.
1077 let mut payment_hash = PaymentHash([0; 32]);
1078 let mut payment_preimage = None;
1079 let mut payment_secret = None;
1080 let mut amount_msat = 0;
1081 let mut counterparty_skimmed_fee_msat_opt = None;
1082 let mut receiver_node_id = None;
1083 let mut _user_payment_id = None::<u64>; // For compatibility with 0.0.103 and earlier
1084 let mut via_channel_id = None;
1085 let mut claim_deadline = None;
1086 let mut via_user_channel_id = None;
1087 let mut onion_fields = None;
1088 read_tlv_fields!(reader, {
1089 (0, payment_hash, required),
1090 (1, receiver_node_id, option),
1091 (2, payment_secret, option),
1092 (3, via_channel_id, option),
1093 (4, amount_msat, required),
1094 (5, via_user_channel_id, option),
1095 (6, _user_payment_id, option),
1096 (7, claim_deadline, option),
1097 (8, payment_preimage, option),
1098 (9, onion_fields, option),
1099 (10, counterparty_skimmed_fee_msat_opt, option),
1101 let purpose = match payment_secret {
1102 Some(secret) => PaymentPurpose::InvoicePayment {
1104 payment_secret: secret
1106 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1107 None => return Err(msgs::DecodeError::InvalidValue),
1109 Ok(Some(Event::PaymentClaimable {
1113 counterparty_skimmed_fee_msat: counterparty_skimmed_fee_msat_opt.unwrap_or(0),
1116 via_user_channel_id,
1125 let mut payment_preimage = PaymentPreimage([0; 32]);
1126 let mut payment_hash = None;
1127 let mut payment_id = None;
1128 let mut fee_paid_msat = None;
1129 read_tlv_fields!(reader, {
1130 (0, payment_preimage, required),
1131 (1, payment_hash, option),
1132 (3, payment_id, option),
1133 (5, fee_paid_msat, option),
1135 if payment_hash.is_none() {
1136 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
1138 Ok(Some(Event::PaymentSent {
1141 payment_hash: payment_hash.unwrap(),
1150 let error_code = Readable::read(reader)?;
1152 let error_data = Readable::read(reader)?;
1153 let mut payment_hash = PaymentHash([0; 32]);
1154 let mut payment_failed_permanently = false;
1155 let mut network_update = None;
1156 let mut blinded_tail: Option<BlindedTail> = None;
1157 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1158 let mut short_channel_id = None;
1159 let mut payment_id = None;
1160 let mut failure_opt = None;
1161 read_tlv_fields!(reader, {
1162 (0, payment_hash, required),
1163 (1, network_update, upgradable_option),
1164 (2, payment_failed_permanently, required),
1165 (4, blinded_tail, option),
1166 (5, path, vec_type),
1167 (7, short_channel_id, option),
1168 (11, payment_id, option),
1169 (13, failure_opt, upgradable_option),
1171 let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1172 Ok(Some(Event::PaymentPathFailed {
1175 payment_failed_permanently,
1177 path: Path { hops: path.unwrap(), blinded_tail },
1190 let mut outputs = WithoutLength(Vec::new());
1191 read_tlv_fields!(reader, {
1192 (0, outputs, required),
1194 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
1199 let mut payment_hash = PaymentHash([0; 32]);
1200 let mut intercept_id = InterceptId([0; 32]);
1201 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1202 let mut inbound_amount_msat = 0;
1203 let mut expected_outbound_amount_msat = 0;
1204 read_tlv_fields!(reader, {
1205 (0, intercept_id, required),
1206 (2, requested_next_hop_scid, required),
1207 (4, payment_hash, required),
1208 (6, inbound_amount_msat, required),
1209 (8, expected_outbound_amount_msat, required),
1211 let next_scid = match requested_next_hop_scid {
1212 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1214 Ok(Some(Event::HTLCIntercepted {
1216 requested_next_hop_scid: next_scid,
1217 inbound_amount_msat,
1218 expected_outbound_amount_msat,
1224 let mut fee_earned_msat = None;
1225 let mut prev_channel_id = None;
1226 let mut claim_from_onchain_tx = false;
1227 let mut next_channel_id = None;
1228 let mut outbound_amount_forwarded_msat = None;
1229 read_tlv_fields!(reader, {
1230 (0, fee_earned_msat, option),
1231 (1, prev_channel_id, option),
1232 (2, claim_from_onchain_tx, required),
1233 (3, next_channel_id, option),
1234 (5, outbound_amount_forwarded_msat, option),
1236 Ok(Some(Event::PaymentForwarded {
1237 fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id,
1238 outbound_amount_forwarded_msat
1245 let mut channel_id = [0; 32];
1246 let mut reason = UpgradableRequired(None);
1247 let mut user_channel_id_low_opt: Option<u64> = None;
1248 let mut user_channel_id_high_opt: Option<u64> = None;
1249 read_tlv_fields!(reader, {
1250 (0, channel_id, required),
1251 (1, user_channel_id_low_opt, option),
1252 (2, reason, upgradable_required),
1253 (3, user_channel_id_high_opt, option),
1256 // `user_channel_id` used to be a single u64 value. In order to remain
1257 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1258 // as two separate u64 values.
1259 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1260 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1262 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required) }))
1268 let mut channel_id = [0; 32];
1269 let mut transaction = Transaction{ version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
1270 read_tlv_fields!(reader, {
1271 (0, channel_id, required),
1272 (2, transaction, required),
1274 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1280 _init_and_read_tlv_fields!(reader, {
1281 (0, payment_id, required),
1282 (2, payment_hash, option),
1283 (4, path, vec_type),
1284 (6, blinded_tail, option),
1286 Ok(Some(Event::PaymentPathSuccessful {
1287 payment_id: payment_id.0.unwrap(),
1289 path: Path { hops: path.unwrap(), blinded_tail },
1296 let mut payment_hash = PaymentHash([0; 32]);
1297 let mut payment_id = PaymentId([0; 32]);
1298 let mut reason = None;
1299 read_tlv_fields!(reader, {
1300 (0, payment_id, required),
1301 (1, reason, upgradable_option),
1302 (2, payment_hash, required),
1304 Ok(Some(Event::PaymentFailed {
1313 // Value 17 is used for `Event::OpenChannelRequest`.
1318 let mut payment_hash = PaymentHash([0; 32]);
1319 let mut purpose = UpgradableRequired(None);
1320 let mut amount_msat = 0;
1321 let mut receiver_node_id = None;
1322 read_tlv_fields!(reader, {
1323 (0, payment_hash, required),
1324 (1, receiver_node_id, option),
1325 (2, purpose, upgradable_required),
1326 (4, amount_msat, required),
1328 Ok(Some(Event::PaymentClaimed {
1331 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1339 _init_and_read_tlv_fields!(reader, {
1340 (0, payment_id, required),
1341 (2, payment_hash, required),
1342 (4, path, vec_type),
1343 (6, blinded_tail, option),
1345 Ok(Some(Event::ProbeSuccessful {
1346 payment_id: payment_id.0.unwrap(),
1347 payment_hash: payment_hash.0.unwrap(),
1348 path: Path { hops: path.unwrap(), blinded_tail },
1355 _init_and_read_tlv_fields!(reader, {
1356 (0, payment_id, required),
1357 (2, payment_hash, required),
1358 (4, path, vec_type),
1359 (6, short_channel_id, option),
1360 (8, blinded_tail, option),
1362 Ok(Some(Event::ProbeFailed {
1363 payment_id: payment_id.0.unwrap(),
1364 payment_hash: payment_hash.0.unwrap(),
1365 path: Path { hops: path.unwrap(), blinded_tail },
1373 let mut prev_channel_id = [0; 32];
1374 let mut failed_next_destination_opt = UpgradableRequired(None);
1375 read_tlv_fields!(reader, {
1376 (0, prev_channel_id, required),
1377 (2, failed_next_destination_opt, upgradable_required),
1379 Ok(Some(Event::HTLCHandlingFailed {
1381 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1389 let mut channel_id = [0; 32];
1390 let mut user_channel_id: u128 = 0;
1391 let mut counterparty_node_id = RequiredWrapper(None);
1392 let mut channel_type = RequiredWrapper(None);
1393 read_tlv_fields!(reader, {
1394 (0, channel_id, required),
1395 (2, user_channel_id, required),
1396 (4, counterparty_node_id, required),
1397 (6, channel_type, required),
1400 Ok(Some(Event::ChannelReady {
1403 counterparty_node_id: counterparty_node_id.0.unwrap(),
1404 channel_type: channel_type.0.unwrap()
1411 let mut channel_id = [0; 32];
1412 let mut user_channel_id: u128 = 0;
1413 let mut former_temporary_channel_id = None;
1414 let mut counterparty_node_id = RequiredWrapper(None);
1415 let mut funding_txo = RequiredWrapper(None);
1416 read_tlv_fields!(reader, {
1417 (0, channel_id, required),
1418 (2, user_channel_id, required),
1419 (4, former_temporary_channel_id, required),
1420 (6, counterparty_node_id, required),
1421 (8, funding_txo, required),
1424 Ok(Some(Event::ChannelPending {
1427 former_temporary_channel_id,
1428 counterparty_node_id: counterparty_node_id.0.unwrap(),
1429 funding_txo: funding_txo.0.unwrap()
1434 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1435 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1437 x if x % 2 == 1 => {
1438 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1439 // which prefixes the whole thing with a length BigSize. Because the event is
1440 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1441 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1442 // exactly the number of bytes specified, ignoring them entirely.
1443 let tlv_len: BigSize = Readable::read(reader)?;
1444 FixedLengthReader::new(reader, tlv_len.0)
1445 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1448 _ => Err(msgs::DecodeError::InvalidValue)
1453 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1454 /// broadcast to most peers).
1455 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1456 #[derive(Clone, Debug)]
1457 pub enum MessageSendEvent {
1458 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1459 /// message provided to the given peer.
1461 /// The node_id of the node which should receive this message
1463 /// The message which should be sent.
1464 msg: msgs::AcceptChannel,
1466 /// Used to indicate that we've accepted a V2 channel open and should send the accept_channel2
1467 /// message provided to the given peer.
1468 SendAcceptChannelV2 {
1469 /// The node_id of the node which should receive this message
1471 /// The message which should be sent.
1472 msg: msgs::AcceptChannelV2,
1474 /// Used to indicate that we've initiated a channel open and should send the open_channel
1475 /// message provided to the given peer.
1477 /// The node_id of the node which should receive this message
1479 /// The message which should be sent.
1480 msg: msgs::OpenChannel,
1482 /// Used to indicate that we've initiated a V2 channel open and should send the open_channel2
1483 /// message provided to the given peer.
1485 /// The node_id of the node which should receive this message
1487 /// The message which should be sent.
1488 msg: msgs::OpenChannelV2,
1490 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1491 SendFundingCreated {
1492 /// The node_id of the node which should receive this message
1494 /// The message which should be sent.
1495 msg: msgs::FundingCreated,
1497 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1499 /// The node_id of the node which should receive this message
1501 /// The message which should be sent.
1502 msg: msgs::FundingSigned,
1504 /// Used to indicate that a tx_add_input message should be sent to the peer with the given node_id.
1506 /// The node_id of the node which should receive this message
1508 /// The message which should be sent.
1509 msg: msgs::TxAddInput,
1511 /// Used to indicate that a tx_add_output message should be sent to the peer with the given node_id.
1513 /// The node_id of the node which should receive this message
1515 /// The message which should be sent.
1516 msg: msgs::TxAddOutput,
1518 /// Used to indicate that a tx_remove_input message should be sent to the peer with the given node_id.
1520 /// The node_id of the node which should receive this message
1522 /// The message which should be sent.
1523 msg: msgs::TxRemoveInput,
1525 /// Used to indicate that a tx_remove_output message should be sent to the peer with the given node_id.
1526 SendTxRemoveOutput {
1527 /// The node_id of the node which should receive this message
1529 /// The message which should be sent.
1530 msg: msgs::TxRemoveOutput,
1532 /// Used to indicate that a tx_complete message should be sent to the peer with the given node_id.
1534 /// The node_id of the node which should receive this message
1536 /// The message which should be sent.
1537 msg: msgs::TxComplete,
1539 /// Used to indicate that a tx_signatures message should be sent to the peer with the given node_id.
1541 /// The node_id of the node which should receive this message
1543 /// The message which should be sent.
1544 msg: msgs::TxSignatures,
1546 /// Used to indicate that a tx_init_rbf message should be sent to the peer with the given node_id.
1548 /// The node_id of the node which should receive this message
1550 /// The message which should be sent.
1551 msg: msgs::TxInitRbf,
1553 /// Used to indicate that a tx_ack_rbf message should be sent to the peer with the given node_id.
1555 /// The node_id of the node which should receive this message
1557 /// The message which should be sent.
1558 msg: msgs::TxAckRbf,
1560 /// Used to indicate that a tx_abort message should be sent to the peer with the given node_id.
1562 /// The node_id of the node which should receive this message
1564 /// The message which should be sent.
1565 msg: msgs::TxAddInput,
1567 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1569 /// The node_id of the node which should receive these message(s)
1571 /// The channel_ready message which should be sent.
1572 msg: msgs::ChannelReady,
1574 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1575 SendAnnouncementSignatures {
1576 /// The node_id of the node which should receive these message(s)
1578 /// The announcement_signatures message which should be sent.
1579 msg: msgs::AnnouncementSignatures,
1581 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1582 /// message should be sent to the peer with the given node_id.
1584 /// The node_id of the node which should receive these message(s)
1586 /// The update messages which should be sent. ALL messages in the struct should be sent!
1587 updates: msgs::CommitmentUpdate,
1589 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1591 /// The node_id of the node which should receive this message
1593 /// The message which should be sent.
1594 msg: msgs::RevokeAndACK,
1596 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1598 /// The node_id of the node which should receive this message
1600 /// The message which should be sent.
1601 msg: msgs::ClosingSigned,
1603 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1605 /// The node_id of the node which should receive this message
1607 /// The message which should be sent.
1608 msg: msgs::Shutdown,
1610 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1611 SendChannelReestablish {
1612 /// The node_id of the node which should receive this message
1614 /// The message which should be sent.
1615 msg: msgs::ChannelReestablish,
1617 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1618 /// initial connection to ensure our peers know about our channels.
1619 SendChannelAnnouncement {
1620 /// The node_id of the node which should receive this message
1622 /// The channel_announcement which should be sent.
1623 msg: msgs::ChannelAnnouncement,
1624 /// The followup channel_update which should be sent.
1625 update_msg: msgs::ChannelUpdate,
1627 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1628 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1630 /// Note that after doing so, you very likely (unless you did so very recently) want to
1631 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1632 /// ensures that any nodes which see our channel_announcement also have a relevant
1633 /// node_announcement, including relevant feature flags which may be important for routing
1634 /// through or to us.
1636 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1637 BroadcastChannelAnnouncement {
1638 /// The channel_announcement which should be sent.
1639 msg: msgs::ChannelAnnouncement,
1640 /// The followup channel_update which should be sent.
1641 update_msg: Option<msgs::ChannelUpdate>,
1643 /// Used to indicate that a channel_update should be broadcast to all peers.
1644 BroadcastChannelUpdate {
1645 /// The channel_update which should be sent.
1646 msg: msgs::ChannelUpdate,
1648 /// Used to indicate that a node_announcement should be broadcast to all peers.
1649 BroadcastNodeAnnouncement {
1650 /// The node_announcement which should be sent.
1651 msg: msgs::NodeAnnouncement,
1653 /// Used to indicate that a channel_update should be sent to a single peer.
1654 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1655 /// private channel and we shouldn't be informing all of our peers of channel parameters.
1657 /// The node_id of the node which should receive this message
1659 /// The channel_update which should be sent.
1660 msg: msgs::ChannelUpdate,
1662 /// Broadcast an error downstream to be handled
1664 /// The node_id of the node which should receive this message
1666 /// The action which should be taken.
1667 action: msgs::ErrorAction
1669 /// Query a peer for channels with funding transaction UTXOs in a block range.
1670 SendChannelRangeQuery {
1671 /// The node_id of this message recipient
1673 /// The query_channel_range which should be sent.
1674 msg: msgs::QueryChannelRange,
1676 /// Request routing gossip messages from a peer for a list of channels identified by
1677 /// their short_channel_ids.
1679 /// The node_id of this message recipient
1681 /// The query_short_channel_ids which should be sent.
1682 msg: msgs::QueryShortChannelIds,
1684 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1685 /// emitted during processing of the query.
1686 SendReplyChannelRange {
1687 /// The node_id of this message recipient
1689 /// The reply_channel_range which should be sent.
1690 msg: msgs::ReplyChannelRange,
1692 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1693 /// enable receiving gossip messages from the peer.
1694 SendGossipTimestampFilter {
1695 /// The node_id of this message recipient
1697 /// The gossip_timestamp_filter which should be sent.
1698 msg: msgs::GossipTimestampFilter,
1702 /// A trait indicating an object may generate message send events
1703 pub trait MessageSendEventsProvider {
1704 /// Gets the list of pending events which were generated by previous actions, clearing the list
1706 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1709 /// A trait indicating an object may generate onion messages to send
1710 pub trait OnionMessageProvider {
1711 /// Gets the next pending onion message for the peer with the given node id.
1712 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<msgs::OnionMessage>;
1715 /// A trait indicating an object may generate events.
1717 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1719 /// Implementations of this trait may also feature an async version of event handling, as shown with
1720 /// [`ChannelManager::process_pending_events_async`] and
1721 /// [`ChainMonitor::process_pending_events_async`].
1725 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1726 /// event since the last invocation.
1728 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1729 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1730 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1731 /// relevant changes to disk *before* returning.
1733 /// Further, because an application may crash between an [`Event`] being handled and the
1734 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1735 /// effect, [`Event`]s may be replayed.
1737 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1738 /// consult the provider's documentation on the implication of processing events and how a handler
1739 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1740 /// [`ChainMonitor::process_pending_events`]).
1742 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1745 /// [`process_pending_events`]: Self::process_pending_events
1746 /// [`handle_event`]: EventHandler::handle_event
1747 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1748 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1749 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
1750 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
1751 pub trait EventsProvider {
1752 /// Processes any events generated since the last call using the given event handler.
1754 /// See the trait-level documentation for requirements.
1755 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1758 /// A trait implemented for objects handling events from [`EventsProvider`].
1760 /// An async variation also exists for implementations of [`EventsProvider`] that support async
1761 /// event handling. The async event handler should satisfy the generic bounds: `F:
1762 /// core::future::Future, H: Fn(Event) -> F`.
1763 pub trait EventHandler {
1764 /// Handles the given [`Event`].
1766 /// See [`EventsProvider`] for details that must be considered when implementing this method.
1767 fn handle_event(&self, event: Event);
1770 impl<F> EventHandler for F where F: Fn(Event) {
1771 fn handle_event(&self, event: Event) {
1776 impl<T: EventHandler> EventHandler for Arc<T> {
1777 fn handle_event(&self, event: Event) {
1778 self.deref().handle_event(event)