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::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
27 use crate::chain::transaction;
28 use crate::routing::gossip::NetworkUpdate;
29 use crate::util::errors::APIError;
30 use crate::util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, RequiredWrapper, UpgradableRequired, WithoutLength};
31 use crate::util::string::UntrustedString;
32 use crate::routing::router::{BlindedTail, Path, RouteHop, RouteParameters};
34 use bitcoin::{Transaction, OutPoint};
35 use bitcoin::blockdata::locktime::absolute::LockTime;
36 use bitcoin::blockdata::script::ScriptBuf;
37 use bitcoin::hashes::Hash;
38 use bitcoin::hashes::sha256::Hash as Sha256;
39 use bitcoin::secp256k1::PublicKey;
41 use crate::prelude::*;
42 use core::time::Duration;
46 /// Some information provided on receipt of payment depends on whether the payment received is a
47 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
48 #[derive(Clone, Debug, PartialEq, Eq)]
49 pub enum PaymentPurpose {
50 /// Information for receiving a payment that we generated an invoice for.
52 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
53 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
54 /// [`ChannelManager::claim_funds`].
56 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
57 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
58 payment_preimage: Option<PaymentPreimage>,
59 /// The "payment secret". This authenticates the sender to the recipient, preventing a
60 /// number of deanonymization attacks during the routing process.
61 /// It is provided here for your reference, however its accuracy is enforced directly by
62 /// [`ChannelManager`] using the values you previously provided to
63 /// [`ChannelManager::create_inbound_payment`] or
64 /// [`ChannelManager::create_inbound_payment_for_hash`].
66 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
67 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
68 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
69 payment_secret: PaymentSecret,
71 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
72 /// (the payee) providing a preimage.
73 SpontaneousPayment(PaymentPreimage),
77 /// Returns the preimage for this payment, if it is known.
78 pub fn preimage(&self) -> Option<PaymentPreimage> {
80 PaymentPurpose::InvoicePayment { payment_preimage, .. } => *payment_preimage,
81 PaymentPurpose::SpontaneousPayment(preimage) => Some(*preimage),
86 impl_writeable_tlv_based_enum!(PaymentPurpose,
87 (0, InvoicePayment) => {
88 (0, payment_preimage, option),
89 (2, payment_secret, required),
91 (2, SpontaneousPayment)
94 /// Information about an HTLC that is part of a payment that can be claimed.
95 #[derive(Clone, Debug, PartialEq, Eq)]
96 pub struct ClaimedHTLC {
97 /// The `channel_id` of the channel over which the HTLC was received.
98 pub channel_id: ChannelId,
99 /// The `user_channel_id` of the channel over which the HTLC was received. This is the value
100 /// passed in to [`ChannelManager::create_channel`] for outbound channels, or to
101 /// [`ChannelManager::accept_inbound_channel`] for inbound channels if
102 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
103 /// `user_channel_id` will be randomized for an inbound channel.
105 /// This field will be zero for a payment that was serialized prior to LDK version 0.0.117. (This
106 /// should only happen in the case that a payment was claimable prior to LDK version 0.0.117, but
107 /// was not actually claimed until after upgrading.)
109 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
110 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
111 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
112 pub user_channel_id: u128,
113 /// The block height at which this HTLC expires.
114 pub cltv_expiry: u32,
115 /// The amount (in msats) of this part of an MPP.
117 /// The extra fee our counterparty skimmed off the top of this HTLC, if any.
119 /// This value will always be 0 for [`ClaimedHTLC`]s serialized with LDK versions prior to
121 pub counterparty_skimmed_fee_msat: u64,
123 impl_writeable_tlv_based!(ClaimedHTLC, {
124 (0, channel_id, required),
125 (1, counterparty_skimmed_fee_msat, (default_value, 0u64)),
126 (2, user_channel_id, required),
127 (4, cltv_expiry, required),
128 (6, value_msat, required),
131 /// When the payment path failure took place and extra details about it. [`PathFailure::OnPath`] may
132 /// contain a [`NetworkUpdate`] that needs to be applied to the [`NetworkGraph`].
134 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
135 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
136 #[derive(Clone, Debug, Eq, PartialEq)]
137 pub enum PathFailure {
138 /// We failed to initially send the payment and no HTLC was committed to. Contains the relevant
141 /// The error surfaced from initial send.
144 /// A hop on the path failed to forward our payment.
146 /// If present, this [`NetworkUpdate`] should be applied to the [`NetworkGraph`] so that routing
147 /// decisions can take into account the update.
149 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
150 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
151 network_update: Option<NetworkUpdate>,
155 impl_writeable_tlv_based_enum_upgradable!(PathFailure,
157 (0, network_update, upgradable_option),
159 (2, InitialSend) => {
160 (0, err, upgradable_required),
164 #[derive(Clone, Debug, PartialEq, Eq)]
165 /// The reason the channel was closed. See individual variants for more details.
166 pub enum ClosureReason {
167 /// Closure generated from receiving a peer error message.
169 /// Our counterparty may have broadcasted their latest commitment state, and we have
171 CounterpartyForceClosed {
172 /// The error which the peer sent us.
174 /// Be careful about printing the peer_msg, a well-crafted message could exploit
175 /// a security vulnerability in the terminal emulator or the logging subsystem.
176 /// To be safe, use `Display` on `UntrustedString`
178 /// [`UntrustedString`]: crate::util::string::UntrustedString
179 peer_msg: UntrustedString,
181 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
183 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
185 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
186 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
187 //TODO: split between CounterpartyInitiated/LocallyInitiated
189 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
190 /// commitment transaction came from our counterparty, but it may also have come from
191 /// a copy of our own `ChannelMonitor`.
192 CommitmentTxConfirmed,
193 /// The funding transaction failed to confirm in a timely manner on an inbound channel.
195 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
197 /// A developer-readable error message which we generated.
200 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
201 /// forget the channel entirely - we can attempt again if the peer reconnects.
203 /// This includes cases where we restarted prior to funding completion, including prior to the
204 /// initial [`ChannelMonitor`] persistence completing.
206 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
207 /// peer because of mutual incompatibility between us and our channel counterparty.
209 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
211 /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
212 /// the [`ChannelManager`] deserialized.
214 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
215 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
216 OutdatedChannelManager,
217 /// The counterparty requested a cooperative close of a channel that had not been funded yet.
218 /// The channel has been immediately closed.
219 CounterpartyCoopClosedUnfundedChannel,
220 /// Another channel in the same funding batch closed before the funding transaction
221 /// was ready to be broadcast.
225 impl core::fmt::Display for ClosureReason {
226 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
227 f.write_str("Channel closed because ")?;
229 ClosureReason::CounterpartyForceClosed { peer_msg } => {
230 f.write_fmt(format_args!("counterparty force-closed with message: {}", peer_msg))
232 ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
233 ClosureReason::CooperativeClosure => f.write_str("the channel was cooperatively closed"),
234 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
235 ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
236 ClosureReason::ProcessingError { err } => {
237 f.write_str("of an exception: ")?;
240 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
241 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
242 ClosureReason::CounterpartyCoopClosedUnfundedChannel => f.write_str("the peer requested the unfunded channel be closed"),
243 ClosureReason::FundingBatchClosure => f.write_str("another channel in the same funding batch closed"),
248 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
249 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
250 (1, FundingTimedOut) => {},
251 (2, HolderForceClosed) => {},
252 (6, CommitmentTxConfirmed) => {},
253 (4, CooperativeClosure) => {},
254 (8, ProcessingError) => { (1, err, required) },
255 (10, DisconnectedPeer) => {},
256 (12, OutdatedChannelManager) => {},
257 (13, CounterpartyCoopClosedUnfundedChannel) => {},
258 (15, FundingBatchClosure) => {}
261 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
262 #[derive(Clone, Debug, PartialEq, Eq)]
263 pub enum HTLCDestination {
264 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
265 /// there is insufficient capacity in our outbound channel.
267 /// The `node_id` of the next node. For backwards compatibility, this field is
268 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
269 /// counterparty node information.
270 node_id: Option<PublicKey>,
271 /// The outgoing `channel_id` between us and the next node.
272 channel_id: ChannelId,
274 /// Scenario where we are unsure of the next node to forward the HTLC to.
276 /// Short channel id we are requesting to forward an HTLC to.
277 requested_forward_scid: u64,
279 /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
282 /// Short channel id we are requesting to forward an HTLC to.
283 requested_forward_scid: u64
285 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
286 /// but is invalid for some reason, so we reject it.
288 /// Some of the reasons may include:
290 /// * Excess HTLCs for a payment that we have already fully received, over-paying for the
292 /// * The counterparty node modified the HTLC in transit,
293 /// * A probing attack where an intermediary node is trying to detect if we are the ultimate
294 /// recipient for a payment.
296 /// The payment hash of the payment we attempted to process.
297 payment_hash: PaymentHash
301 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
302 (0, NextHopChannel) => {
303 (0, node_id, required),
304 (2, channel_id, required),
306 (1, InvalidForward) => {
307 (0, requested_forward_scid, required),
309 (2, UnknownNextHop) => {
310 (0, requested_forward_scid, required),
312 (4, FailedPayment) => {
313 (0, payment_hash, required),
317 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
318 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
319 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
320 /// intercepts in upcoming work.
321 enum InterceptNextHop {
323 requested_next_hop_scid: u64,
327 impl_writeable_tlv_based_enum!(InterceptNextHop,
329 (0, requested_next_hop_scid, required),
333 /// The reason the payment failed. Used in [`Event::PaymentFailed`].
334 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
335 pub enum PaymentFailureReason {
336 /// The intended recipient rejected our payment.
338 /// The user chose to abandon this payment by calling [`ChannelManager::abandon_payment`].
340 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
342 /// We exhausted all of our retry attempts while trying to send the payment, or we
343 /// exhausted the [`Retry::Timeout`] if the user set one. If at any point a retry
344 /// attempt failed while being forwarded along the path, an [`Event::PaymentPathFailed`] will
345 /// have come before this.
347 /// [`Retry::Timeout`]: crate::ln::channelmanager::Retry::Timeout
349 /// The payment expired while retrying, based on the provided
350 /// [`PaymentParameters::expiry_time`].
352 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
354 /// We failed to find a route while retrying the payment.
356 /// This error should generally never happen. This likely means that there is a problem with
361 impl_writeable_tlv_based_enum!(PaymentFailureReason,
362 (0, RecipientRejected) => {},
363 (2, UserAbandoned) => {},
364 (4, RetriesExhausted) => {},
365 (6, PaymentExpired) => {},
366 (8, RouteNotFound) => {},
367 (10, UnexpectedError) => {}, ;
370 /// An Event which you should probably take some action in response to.
372 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
373 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
374 /// written as it makes no sense to respond to it after reconnecting to peers).
375 #[derive(Clone, Debug, PartialEq, Eq)]
377 /// Used to indicate that the client should generate a funding transaction with the given
378 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
379 /// Generated in [`ChannelManager`] message handling.
380 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
381 /// counterparty can steal your funds!
383 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
384 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
385 FundingGenerationReady {
386 /// The random channel_id we picked which you'll need to pass into
387 /// [`ChannelManager::funding_transaction_generated`].
389 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
390 temporary_channel_id: ChannelId,
391 /// The counterparty's node_id, which you'll need to pass back into
392 /// [`ChannelManager::funding_transaction_generated`].
394 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
395 counterparty_node_id: PublicKey,
396 /// The value, in satoshis, that the output should have.
397 channel_value_satoshis: u64,
398 /// The script which should be used in the transaction output.
399 output_script: ScriptBuf,
400 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
401 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
402 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
403 /// `user_channel_id` will be randomized for an inbound channel. This may be zero for objects
404 /// serialized with LDK versions prior to 0.0.113.
406 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
407 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
408 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
409 user_channel_id: u128,
411 /// Indicates that we've been offered a payment and it needs to be claimed via calling
412 /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
414 /// Note that if the preimage is not known, you should call
415 /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
416 /// to free up resources for this HTLC and avoid network congestion.
418 /// If [`Event::PaymentClaimable::onion_fields`] is `Some`, and includes custom TLVs with even type
419 /// numbers, you should use [`ChannelManager::fail_htlc_backwards_with_reason`] with
420 /// [`FailureCode::InvalidOnionPayload`] if you fail to understand and handle the contents, or
421 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`] upon successful handling.
422 /// If you don't intend to check for custom TLVs, you can simply use
423 /// [`ChannelManager::claim_funds`], which will automatically fail back even custom TLVs.
425 /// If you fail to call [`ChannelManager::claim_funds`],
426 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`],
427 /// [`ChannelManager::fail_htlc_backwards`], or
428 /// [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will
429 /// be automatically failed.
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. In such a case it is
434 /// polite (and required in the lightning specification) to fail the payment the second time
435 /// and give the sender their money back rather than accepting double payment.
438 /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
440 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
441 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`]: crate::ln::channelmanager::ChannelManager::claim_funds_with_known_custom_tlvs
442 /// [`FailureCode::InvalidOnionPayload`]: crate::ln::channelmanager::FailureCode::InvalidOnionPayload
443 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
444 /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
446 /// The node that will receive the payment after it has been claimed.
447 /// This is useful to identify payments received via [phantom nodes].
448 /// This field will always be filled in when the event was generated by LDK versions
449 /// 0.0.113 and above.
451 /// [phantom nodes]: crate::sign::PhantomKeysManager
452 receiver_node_id: Option<PublicKey>,
453 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
454 /// not stop you from registering duplicate payment hashes for inbound payments.
455 payment_hash: PaymentHash,
456 /// The fields in the onion which were received with each HTLC. Only fields which were
457 /// identical in each HTLC involved in the payment will be included here.
459 /// Payments received on LDK versions prior to 0.0.115 will have this field unset.
460 onion_fields: Option<RecipientOnionFields>,
461 /// The value, in thousandths of a satoshi, that this payment is claimable for. May be greater
462 /// than the invoice amount.
464 /// May be less than the invoice amount if [`ChannelConfig::accept_underpaying_htlcs`] is set
465 /// and the previous hop took an extra fee.
468 /// If [`ChannelConfig::accept_underpaying_htlcs`] is set and you claim without verifying this
469 /// field, you may lose money!
471 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
473 /// The value, in thousands of a satoshi, that was skimmed off of this payment as an extra fee
474 /// taken by our channel counterparty.
476 /// Will always be 0 unless [`ChannelConfig::accept_underpaying_htlcs`] is set.
478 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
479 counterparty_skimmed_fee_msat: u64,
480 /// Information for claiming this received payment, based on whether the purpose of the
481 /// payment is to pay an invoice or to send a spontaneous payment.
482 purpose: PaymentPurpose,
483 /// The `channel_id` indicating over which channel we received the payment.
484 via_channel_id: Option<ChannelId>,
485 /// The `user_channel_id` indicating over which channel we received the payment.
486 via_user_channel_id: Option<u128>,
487 /// The block height at which this payment will be failed back and will no longer be
488 /// eligible for claiming.
490 /// Prior to this height, a call to [`ChannelManager::claim_funds`] is guaranteed to
491 /// succeed, however you should wait for [`Event::PaymentClaimed`] to be sure.
493 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
494 claim_deadline: Option<u32>,
496 /// Indicates a payment has been claimed and we've received money!
498 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
499 /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
500 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
501 /// [`Event::PaymentClaimable`] event.
504 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
505 /// `PaymentClaimable` events may be generated for the same payment. If you then call
506 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
507 /// multiple `PaymentClaimed` events.
509 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
511 /// The node that received the payment.
512 /// This is useful to identify payments which were received via [phantom nodes].
513 /// This field will always be filled in when the event was generated by LDK versions
514 /// 0.0.113 and above.
516 /// [phantom nodes]: crate::sign::PhantomKeysManager
517 receiver_node_id: Option<PublicKey>,
518 /// The payment hash of the claimed payment. Note that LDK will not stop you from
519 /// registering duplicate payment hashes for inbound payments.
520 payment_hash: PaymentHash,
521 /// The value, in thousandths of a satoshi, that this payment is for. May be greater than the
524 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
525 /// spontaneous payment.
526 purpose: PaymentPurpose,
527 /// The HTLCs that comprise the claimed payment. This will be empty for events serialized prior
528 /// to LDK version 0.0.117.
529 htlcs: Vec<ClaimedHTLC>,
530 /// The sender-intended sum total of all the MPP parts. This will be `None` for events
531 /// serialized prior to LDK version 0.0.117.
532 sender_intended_total_msat: Option<u64>,
534 /// Indicates that a peer connection with a node is needed in order to send an [`OnionMessage`].
536 /// Typically, this happens when a [`MessageRouter`] is unable to find a complete path to a
537 /// [`Destination`]. Once a connection is established, any messages buffered by an
538 /// [`OnionMessageHandler`] may be sent.
540 /// This event will not be generated for onion message forwards; only for sends including
541 /// replies. Handlers should connect to the node otherwise any buffered messages may be lost.
543 /// [`OnionMessage`]: msgs::OnionMessage
544 /// [`MessageRouter`]: crate::onion_message::messenger::MessageRouter
545 /// [`Destination`]: crate::onion_message::messenger::Destination
546 /// [`OnionMessageHandler`]: crate::ln::msgs::OnionMessageHandler
548 /// The node id for the node needing a connection.
550 /// Sockets for connecting to the node.
551 addresses: Vec<msgs::SocketAddress>,
553 /// Indicates a request for an invoice failed to yield a response in a reasonable amount of time
554 /// or was explicitly abandoned by [`ChannelManager::abandon_payment`]. This may be for an
555 /// [`InvoiceRequest`] sent for an [`Offer`] or for a [`Refund`] that hasn't been redeemed.
557 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
558 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
559 /// [`Offer`]: crate::offers::offer::Offer
560 /// [`Refund`]: crate::offers::refund::Refund
561 InvoiceRequestFailed {
562 /// The `payment_id` to have been associated with payment for the requested invoice.
563 payment_id: PaymentId,
565 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
566 /// and we got back the payment preimage for it).
568 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
569 /// event. In this situation, you SHOULD treat this payment as having succeeded.
571 /// The `payment_id` passed to [`ChannelManager::send_payment`].
573 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
574 payment_id: Option<PaymentId>,
575 /// The preimage to the hash given to ChannelManager::send_payment.
576 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
577 /// store it somehow!
578 payment_preimage: PaymentPreimage,
579 /// The hash that was given to [`ChannelManager::send_payment`].
581 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
582 payment_hash: PaymentHash,
583 /// The total fee which was spent at intermediate hops in this payment, across all paths.
585 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
586 /// overpayment to the recipient node.
588 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
589 /// overstate the amount paid, though this is unlikely.
591 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
592 fee_paid_msat: Option<u64>,
594 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
595 /// provide failure information for each path attempt in the payment, including retries.
597 /// This event is provided once there are no further pending HTLCs for the payment and the
598 /// payment is no longer retryable, due either to the [`Retry`] provided or
599 /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
601 /// In exceedingly rare cases, it is possible that an [`Event::PaymentFailed`] is generated for
602 /// a payment after an [`Event::PaymentSent`] event for this same payment has already been
603 /// received and processed. In this case, the [`Event::PaymentFailed`] event MUST be ignored,
604 /// and the payment MUST be treated as having succeeded.
606 /// [`Retry`]: crate::ln::channelmanager::Retry
607 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
609 /// The `payment_id` passed to [`ChannelManager::send_payment`].
611 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
612 payment_id: PaymentId,
613 /// The hash that was given to [`ChannelManager::send_payment`].
615 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
616 payment_hash: PaymentHash,
617 /// The reason the payment failed. This is only `None` for events generated or serialized
618 /// by versions prior to 0.0.115.
619 reason: Option<PaymentFailureReason>,
621 /// Indicates that a path for an outbound payment was successful.
623 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
624 /// [`Event::PaymentSent`] for obtaining the payment preimage.
625 PaymentPathSuccessful {
626 /// The `payment_id` passed to [`ChannelManager::send_payment`].
628 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
629 payment_id: PaymentId,
630 /// The hash that was given to [`ChannelManager::send_payment`].
632 /// This will be `Some` for all payments which completed on LDK 0.0.104 or later.
634 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
635 payment_hash: Option<PaymentHash>,
636 /// The payment path that was successful.
638 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
641 /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
644 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
645 /// [`Event::PaymentFailed`].
647 /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
650 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
652 /// The `payment_id` passed to [`ChannelManager::send_payment`].
654 /// This will be `Some` for all payment paths which failed on LDK 0.0.103 or later.
656 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
657 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
658 payment_id: Option<PaymentId>,
659 /// The hash that was given to [`ChannelManager::send_payment`].
661 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
662 payment_hash: PaymentHash,
663 /// Indicates the payment was rejected for some reason by the recipient. This implies that
664 /// the payment has failed, not just the route in question. If this is not set, the payment may
665 /// be retried via a different route.
666 payment_failed_permanently: bool,
667 /// Extra error details based on the failure type. May contain an update that needs to be
668 /// applied to the [`NetworkGraph`].
670 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
671 failure: PathFailure,
672 /// The payment path that failed.
674 /// The channel responsible for the failed payment path.
676 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
677 /// may not refer to a channel in the public network graph. These aliases may also collide
678 /// with channels in the public network graph.
680 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
681 /// retried. May be `None` for older [`Event`] serializations.
682 short_channel_id: Option<u64>,
684 error_code: Option<u16>,
686 error_data: Option<Vec<u8>>,
688 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
690 /// The id returned by [`ChannelManager::send_probe`].
692 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
693 payment_id: PaymentId,
694 /// The hash generated by [`ChannelManager::send_probe`].
696 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
697 payment_hash: PaymentHash,
698 /// The payment path that was successful.
701 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
703 /// The id returned by [`ChannelManager::send_probe`].
705 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
706 payment_id: PaymentId,
707 /// The hash generated by [`ChannelManager::send_probe`].
709 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
710 payment_hash: PaymentHash,
711 /// The payment path that failed.
713 /// The channel responsible for the failed probe.
715 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
716 /// may not refer to a channel in the public network graph. These aliases may also collide
717 /// with channels in the public network graph.
718 short_channel_id: Option<u64>,
720 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
721 /// a time in the future.
723 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
724 PendingHTLCsForwardable {
725 /// The minimum amount of time that should be waited prior to calling
726 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
727 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
728 /// now + 5*time_forwardable).
729 time_forwardable: Duration,
731 /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
732 /// you've encoded an intercept scid in the receiver's invoice route hints using
733 /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
735 /// [`ChannelManager::forward_intercepted_htlc`] or
736 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
737 /// their docs for more information.
739 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
740 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
741 /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
742 /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
744 /// An id to help LDK identify which HTLC is being forwarded or failed.
745 intercept_id: InterceptId,
746 /// The fake scid that was programmed as the next hop's scid, generated using
747 /// [`ChannelManager::get_intercept_scid`].
749 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
750 requested_next_hop_scid: u64,
751 /// The payment hash used for this HTLC.
752 payment_hash: PaymentHash,
753 /// How many msats were received on the inbound edge of this HTLC.
754 inbound_amount_msat: u64,
755 /// How many msats the payer intended to route to the next node. Depending on the reason you are
756 /// intercepting this payment, you might take a fee by forwarding less than this amount.
757 /// Forwarding less than this amount may break compatibility with LDK versions prior to 0.0.116.
759 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
760 /// check that whatever fee you want has been included here or subtract it as required. Further,
761 /// LDK will not stop you from forwarding more than you received.
762 expected_outbound_amount_msat: u64,
764 /// Used to indicate that an output which you should know how to spend was confirmed on chain
765 /// and is now spendable.
766 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
767 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
768 /// somewhere and spend them when you create on-chain transactions.
770 /// The outputs which you should store as spendable by you.
771 outputs: Vec<SpendableOutputDescriptor>,
772 /// The `channel_id` indicating which channel the spendable outputs belong to.
774 /// This will always be `Some` for events generated by LDK versions 0.0.117 and above.
775 channel_id: Option<ChannelId>,
777 /// This event is generated when a payment has been successfully forwarded through us and a
778 /// forwarding fee earned.
780 /// The incoming channel between the previous node and us. This is only `None` for events
781 /// generated or serialized by versions prior to 0.0.107.
782 prev_channel_id: Option<ChannelId>,
783 /// The outgoing channel between the next node and us. This is only `None` for events
784 /// generated or serialized by versions prior to 0.0.107.
785 next_channel_id: Option<ChannelId>,
786 /// The total fee, in milli-satoshis, which was earned as a result of the payment.
788 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
789 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
790 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
791 /// claimed the full value in millisatoshis from the source. In this case,
792 /// `claim_from_onchain_tx` will be set.
794 /// If the channel which sent us the payment has been force-closed, we will claim the funds
795 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
796 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
797 /// `PaymentForwarded` events are generated for the same payment iff `total_fee_earned_msat` is
799 total_fee_earned_msat: Option<u64>,
800 /// The share of the total fee, in milli-satoshis, which was withheld in addition to the
803 /// This will only be `Some` if we forwarded an intercepted HTLC with less than the
804 /// expected amount. This means our counterparty accepted to receive less than the invoice
805 /// amount, e.g., by claiming the payment featuring a corresponding
806 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`].
808 /// Will also always be `None` for events serialized with LDK prior to version 0.0.122.
810 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
812 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`]: Self::PaymentClaimable::counterparty_skimmed_fee_msat
813 skimmed_fee_msat: Option<u64>,
814 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
816 claim_from_onchain_tx: bool,
817 /// The final amount forwarded, in milli-satoshis, after the fee is deducted.
819 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
820 outbound_amount_forwarded_msat: Option<u64>,
822 /// Used to indicate that a channel with the given `channel_id` is being opened and pending
823 /// confirmation on-chain.
825 /// This event is emitted when the funding transaction has been signed and is broadcast to the
826 /// network. For 0conf channels it will be immediately followed by the corresponding
827 /// [`Event::ChannelReady`] event.
829 /// The `channel_id` of the channel that is pending confirmation.
830 channel_id: ChannelId,
831 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
832 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
833 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
834 /// `user_channel_id` will be randomized for an inbound channel.
836 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
837 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
838 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
839 user_channel_id: u128,
840 /// The `temporary_channel_id` this channel used to be known by during channel establishment.
842 /// Will be `None` for channels created prior to LDK version 0.0.115.
843 former_temporary_channel_id: Option<ChannelId>,
844 /// The `node_id` of the channel counterparty.
845 counterparty_node_id: PublicKey,
846 /// The outpoint of the channel's funding transaction.
847 funding_txo: OutPoint,
848 /// The features that this channel will operate with.
850 /// Will be `None` for channels created prior to LDK version 0.0.122.
851 channel_type: Option<ChannelTypeFeatures>,
853 /// Used to indicate that a channel with the given `channel_id` is ready to
854 /// be used. This event is emitted either when the funding transaction has been confirmed
855 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
858 /// The `channel_id` of the channel that is ready.
859 channel_id: ChannelId,
860 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
861 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
862 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
863 /// `user_channel_id` will be randomized for an inbound channel.
865 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
866 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
867 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
868 user_channel_id: u128,
869 /// The `node_id` of the channel counterparty.
870 counterparty_node_id: PublicKey,
871 /// The features that this channel will operate with.
872 channel_type: ChannelTypeFeatures,
874 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
875 /// process of closure.
877 /// Note that this event is only triggered for accepted channels: if the
878 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true and the channel is
879 /// rejected, no `ChannelClosed` event will be sent.
881 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
882 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
884 /// The `channel_id` of the channel which has been closed. Note that on-chain transactions
885 /// resolving the channel are likely still awaiting confirmation.
886 channel_id: ChannelId,
887 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
888 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
889 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
890 /// `user_channel_id` will be randomized for inbound channels.
891 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
892 /// zero for objects serialized with LDK versions prior to 0.0.102.
894 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
895 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
896 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
897 user_channel_id: u128,
898 /// The reason the channel was closed.
899 reason: ClosureReason,
900 /// Counterparty in the closed channel.
902 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
903 counterparty_node_id: Option<PublicKey>,
904 /// Channel capacity of the closing channel (sats).
906 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
907 channel_capacity_sats: Option<u64>,
908 /// The original channel funding TXO; this helps checking for the existence and confirmation
909 /// status of the closing tx.
910 /// Note that for instances serialized in v0.0.119 or prior this will be missing (None).
911 channel_funding_txo: Option<transaction::OutPoint>,
913 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
914 /// inputs for another purpose.
916 /// This event is not guaranteed to be generated for channels that are closed due to a restart.
918 /// The channel_id of the channel which has been closed.
919 channel_id: ChannelId,
920 /// The full transaction received from the user
921 transaction: Transaction
923 /// Indicates a request to open a new channel by a peer.
925 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the request,
926 /// call [`ChannelManager::force_close_without_broadcasting_txn`]. Note that a ['ChannelClosed`]
927 /// event will _not_ be triggered if the channel is rejected.
929 /// The event is only triggered when a new open channel request is received and the
930 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
932 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
933 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
934 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
936 /// The temporary channel ID of the channel requested to be opened.
938 /// When responding to the request, the `temporary_channel_id` should be passed
939 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
940 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
942 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
943 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
944 temporary_channel_id: ChannelId,
945 /// The node_id of the counterparty requesting to open the channel.
947 /// When responding to the request, the `counterparty_node_id` should be passed
948 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
949 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
952 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
953 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
954 counterparty_node_id: PublicKey,
955 /// The channel value of the requested channel.
956 funding_satoshis: u64,
957 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
959 /// The features that this channel will operate with. If you reject the channel, a
960 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
963 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
964 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
967 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
968 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
969 /// 0.0.107. Channels setting this type also need to get manually accepted via
970 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
971 /// or will be rejected otherwise.
973 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
974 channel_type: ChannelTypeFeatures,
976 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
979 /// Some scenarios where this event may be sent include:
980 /// * Insufficient capacity in the outbound channel
981 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
982 /// * When an unknown SCID is requested for forwarding a payment.
983 /// * Expected MPP amount has already been reached
984 /// * The HTLC has timed out
986 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
987 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
989 /// The channel over which the HTLC was received.
990 prev_channel_id: ChannelId,
991 /// Destination of the HTLC that failed to be processed.
992 failed_next_destination: HTLCDestination,
994 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
995 /// requires confirmed external funds to be readily available to spend.
997 /// LDK does not currently generate this event unless the
998 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`] config flag is set to true.
999 /// It is limited to the scope of channels with anchor outputs.
1001 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`]: crate::util::config::ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx
1002 BumpTransaction(BumpTransactionEvent),
1005 impl Writeable for Event {
1006 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1008 &Event::FundingGenerationReady { .. } => {
1010 // We never write out FundingGenerationReady events as, upon disconnection, peers
1011 // drop any channels which have not yet exchanged funding_signed.
1013 &Event::PaymentClaimable { ref payment_hash, ref amount_msat, counterparty_skimmed_fee_msat,
1014 ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id,
1015 ref claim_deadline, ref onion_fields
1018 let mut payment_secret = None;
1019 let payment_preimage;
1021 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
1022 payment_secret = Some(secret);
1023 payment_preimage = *preimage;
1025 PaymentPurpose::SpontaneousPayment(preimage) => {
1026 payment_preimage = Some(*preimage);
1029 let skimmed_fee_opt = if counterparty_skimmed_fee_msat == 0 { None }
1030 else { Some(counterparty_skimmed_fee_msat) };
1031 write_tlv_fields!(writer, {
1032 (0, payment_hash, required),
1033 (1, receiver_node_id, option),
1034 (2, payment_secret, option),
1035 (3, via_channel_id, option),
1036 (4, amount_msat, required),
1037 (5, via_user_channel_id, option),
1038 // Type 6 was `user_payment_id` on 0.0.103 and earlier
1039 (7, claim_deadline, option),
1040 (8, payment_preimage, option),
1041 (9, onion_fields, option),
1042 (10, skimmed_fee_opt, option),
1045 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
1047 write_tlv_fields!(writer, {
1048 (0, payment_preimage, required),
1049 (1, payment_hash, required),
1050 (3, payment_id, option),
1051 (5, fee_paid_msat, option),
1054 &Event::PaymentPathFailed {
1055 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
1056 ref path, ref short_channel_id,
1064 error_code.write(writer)?;
1066 error_data.write(writer)?;
1067 write_tlv_fields!(writer, {
1068 (0, payment_hash, required),
1069 (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
1070 (2, payment_failed_permanently, required),
1071 (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
1072 (4, path.blinded_tail, option),
1073 (5, path.hops, required_vec),
1074 (7, short_channel_id, option),
1075 (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
1076 (11, payment_id, option),
1077 (13, failure, required),
1080 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
1082 // Note that we now ignore these on the read end as we'll re-generate them in
1083 // ChannelManager, we write them here only for backwards compatibility.
1085 &Event::SpendableOutputs { ref outputs, channel_id } => {
1087 write_tlv_fields!(writer, {
1088 (0, WithoutLength(outputs), required),
1089 (1, channel_id, option),
1092 &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1094 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1095 write_tlv_fields!(writer, {
1096 (0, intercept_id, required),
1097 (2, intercept_scid, required),
1098 (4, payment_hash, required),
1099 (6, inbound_amount_msat, required),
1100 (8, expected_outbound_amount_msat, required),
1103 &Event::PaymentForwarded {
1104 total_fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
1105 next_channel_id, outbound_amount_forwarded_msat, skimmed_fee_msat,
1108 write_tlv_fields!(writer, {
1109 (0, total_fee_earned_msat, option),
1110 (1, prev_channel_id, option),
1111 (2, claim_from_onchain_tx, required),
1112 (3, next_channel_id, option),
1113 (5, outbound_amount_forwarded_msat, option),
1114 (7, skimmed_fee_msat, option),
1117 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason,
1118 ref counterparty_node_id, ref channel_capacity_sats, ref channel_funding_txo
1121 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1122 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1123 // separate u64 values.
1124 let user_channel_id_low = *user_channel_id as u64;
1125 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1126 write_tlv_fields!(writer, {
1127 (0, channel_id, required),
1128 (1, user_channel_id_low, required),
1129 (2, reason, required),
1130 (3, user_channel_id_high, required),
1131 (5, counterparty_node_id, option),
1132 (7, channel_capacity_sats, option),
1133 (9, channel_funding_txo, option),
1136 &Event::DiscardFunding { ref channel_id, ref transaction } => {
1137 11u8.write(writer)?;
1138 write_tlv_fields!(writer, {
1139 (0, channel_id, required),
1140 (2, transaction, required)
1143 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1144 13u8.write(writer)?;
1145 write_tlv_fields!(writer, {
1146 (0, payment_id, required),
1147 (2, payment_hash, option),
1148 (4, path.hops, required_vec),
1149 (6, path.blinded_tail, option),
1152 &Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
1153 15u8.write(writer)?;
1154 write_tlv_fields!(writer, {
1155 (0, payment_id, required),
1156 (1, reason, option),
1157 (2, payment_hash, required),
1160 &Event::OpenChannelRequest { .. } => {
1161 17u8.write(writer)?;
1162 // We never write the OpenChannelRequest events as, upon disconnection, peers
1163 // drop any channels which have not yet exchanged funding_signed.
1165 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref htlcs, ref sender_intended_total_msat } => {
1166 19u8.write(writer)?;
1167 write_tlv_fields!(writer, {
1168 (0, payment_hash, required),
1169 (1, receiver_node_id, option),
1170 (2, purpose, required),
1171 (4, amount_msat, required),
1172 (5, *htlcs, optional_vec),
1173 (7, sender_intended_total_msat, option),
1176 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1177 21u8.write(writer)?;
1178 write_tlv_fields!(writer, {
1179 (0, payment_id, required),
1180 (2, payment_hash, required),
1181 (4, path.hops, required_vec),
1182 (6, path.blinded_tail, option),
1185 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1186 23u8.write(writer)?;
1187 write_tlv_fields!(writer, {
1188 (0, payment_id, required),
1189 (2, payment_hash, required),
1190 (4, path.hops, required_vec),
1191 (6, short_channel_id, option),
1192 (8, path.blinded_tail, option),
1195 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1196 25u8.write(writer)?;
1197 write_tlv_fields!(writer, {
1198 (0, prev_channel_id, required),
1199 (2, failed_next_destination, required),
1202 &Event::BumpTransaction(ref event)=> {
1203 27u8.write(writer)?;
1205 // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1206 // upon restarting anyway if they remain unresolved.
1207 BumpTransactionEvent::ChannelClose { .. } => {}
1208 BumpTransactionEvent::HTLCResolution { .. } => {}
1210 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1212 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1213 29u8.write(writer)?;
1214 write_tlv_fields!(writer, {
1215 (0, channel_id, required),
1216 (2, user_channel_id, required),
1217 (4, counterparty_node_id, required),
1218 (6, channel_type, required),
1221 &Event::ChannelPending { ref channel_id, ref user_channel_id,
1222 ref former_temporary_channel_id, ref counterparty_node_id, ref funding_txo,
1225 31u8.write(writer)?;
1226 write_tlv_fields!(writer, {
1227 (0, channel_id, required),
1228 (1, channel_type, option),
1229 (2, user_channel_id, required),
1230 (4, former_temporary_channel_id, required),
1231 (6, counterparty_node_id, required),
1232 (8, funding_txo, required),
1235 &Event::InvoiceRequestFailed { ref payment_id } => {
1236 33u8.write(writer)?;
1237 write_tlv_fields!(writer, {
1238 (0, payment_id, required),
1241 &Event::ConnectionNeeded { .. } => {
1242 35u8.write(writer)?;
1243 // Never write ConnectionNeeded events as buffered onion messages aren't serialized.
1245 // Note that, going forward, all new events must only write data inside of
1246 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1247 // data via `write_tlv_fields`.
1252 impl MaybeReadable for Event {
1253 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1254 match Readable::read(reader)? {
1255 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events.
1259 let mut payment_hash = PaymentHash([0; 32]);
1260 let mut payment_preimage = None;
1261 let mut payment_secret = None;
1262 let mut amount_msat = 0;
1263 let mut counterparty_skimmed_fee_msat_opt = None;
1264 let mut receiver_node_id = None;
1265 let mut _user_payment_id = None::<u64>; // Used in 0.0.103 and earlier, no longer written in 0.0.116+.
1266 let mut via_channel_id = None;
1267 let mut claim_deadline = None;
1268 let mut via_user_channel_id = None;
1269 let mut onion_fields = None;
1270 read_tlv_fields!(reader, {
1271 (0, payment_hash, required),
1272 (1, receiver_node_id, option),
1273 (2, payment_secret, option),
1274 (3, via_channel_id, option),
1275 (4, amount_msat, required),
1276 (5, via_user_channel_id, option),
1277 (6, _user_payment_id, option),
1278 (7, claim_deadline, option),
1279 (8, payment_preimage, option),
1280 (9, onion_fields, option),
1281 (10, counterparty_skimmed_fee_msat_opt, option),
1283 let purpose = match payment_secret {
1284 Some(secret) => PaymentPurpose::InvoicePayment {
1286 payment_secret: secret
1288 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1289 None => return Err(msgs::DecodeError::InvalidValue),
1291 Ok(Some(Event::PaymentClaimable {
1295 counterparty_skimmed_fee_msat: counterparty_skimmed_fee_msat_opt.unwrap_or(0),
1298 via_user_channel_id,
1307 let mut payment_preimage = PaymentPreimage([0; 32]);
1308 let mut payment_hash = None;
1309 let mut payment_id = None;
1310 let mut fee_paid_msat = None;
1311 read_tlv_fields!(reader, {
1312 (0, payment_preimage, required),
1313 (1, payment_hash, option),
1314 (3, payment_id, option),
1315 (5, fee_paid_msat, option),
1317 if payment_hash.is_none() {
1318 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()));
1320 Ok(Some(Event::PaymentSent {
1323 payment_hash: payment_hash.unwrap(),
1332 let error_code = Readable::read(reader)?;
1334 let error_data = Readable::read(reader)?;
1335 let mut payment_hash = PaymentHash([0; 32]);
1336 let mut payment_failed_permanently = false;
1337 let mut network_update = None;
1338 let mut blinded_tail: Option<BlindedTail> = None;
1339 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1340 let mut short_channel_id = None;
1341 let mut payment_id = None;
1342 let mut failure_opt = None;
1343 read_tlv_fields!(reader, {
1344 (0, payment_hash, required),
1345 (1, network_update, upgradable_option),
1346 (2, payment_failed_permanently, required),
1347 (4, blinded_tail, option),
1348 // Added as a part of LDK 0.0.101 and always filled in since.
1349 // Defaults to an empty Vec, though likely should have been `Option`al.
1350 (5, path, optional_vec),
1351 (7, short_channel_id, option),
1352 (11, payment_id, option),
1353 (13, failure_opt, upgradable_option),
1355 let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1356 Ok(Some(Event::PaymentPathFailed {
1359 payment_failed_permanently,
1361 path: Path { hops: path.unwrap(), blinded_tail },
1374 let mut outputs = WithoutLength(Vec::new());
1375 let mut channel_id: Option<ChannelId> = None;
1376 read_tlv_fields!(reader, {
1377 (0, outputs, required),
1378 (1, channel_id, option),
1380 Ok(Some(Event::SpendableOutputs { outputs: outputs.0, channel_id }))
1385 let mut payment_hash = PaymentHash([0; 32]);
1386 let mut intercept_id = InterceptId([0; 32]);
1387 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1388 let mut inbound_amount_msat = 0;
1389 let mut expected_outbound_amount_msat = 0;
1390 read_tlv_fields!(reader, {
1391 (0, intercept_id, required),
1392 (2, requested_next_hop_scid, required),
1393 (4, payment_hash, required),
1394 (6, inbound_amount_msat, required),
1395 (8, expected_outbound_amount_msat, required),
1397 let next_scid = match requested_next_hop_scid {
1398 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1400 Ok(Some(Event::HTLCIntercepted {
1402 requested_next_hop_scid: next_scid,
1403 inbound_amount_msat,
1404 expected_outbound_amount_msat,
1410 let mut total_fee_earned_msat = None;
1411 let mut prev_channel_id = None;
1412 let mut claim_from_onchain_tx = false;
1413 let mut next_channel_id = None;
1414 let mut outbound_amount_forwarded_msat = None;
1415 let mut skimmed_fee_msat = None;
1416 read_tlv_fields!(reader, {
1417 (0, total_fee_earned_msat, option),
1418 (1, prev_channel_id, option),
1419 (2, claim_from_onchain_tx, required),
1420 (3, next_channel_id, option),
1421 (5, outbound_amount_forwarded_msat, option),
1422 (7, skimmed_fee_msat, option),
1424 Ok(Some(Event::PaymentForwarded {
1425 total_fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id,
1426 outbound_amount_forwarded_msat, skimmed_fee_msat,
1433 let mut channel_id = ChannelId::new_zero();
1434 let mut reason = UpgradableRequired(None);
1435 let mut user_channel_id_low_opt: Option<u64> = None;
1436 let mut user_channel_id_high_opt: Option<u64> = None;
1437 let mut counterparty_node_id = None;
1438 let mut channel_capacity_sats = None;
1439 let mut channel_funding_txo = None;
1440 read_tlv_fields!(reader, {
1441 (0, channel_id, required),
1442 (1, user_channel_id_low_opt, option),
1443 (2, reason, upgradable_required),
1444 (3, user_channel_id_high_opt, option),
1445 (5, counterparty_node_id, option),
1446 (7, channel_capacity_sats, option),
1447 (9, channel_funding_txo, option),
1450 // `user_channel_id` used to be a single u64 value. In order to remain
1451 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1452 // as two separate u64 values.
1453 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1454 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1456 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required),
1457 counterparty_node_id, channel_capacity_sats, channel_funding_txo }))
1463 let mut channel_id = ChannelId::new_zero();
1464 let mut transaction = Transaction{ version: 2, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
1465 read_tlv_fields!(reader, {
1466 (0, channel_id, required),
1467 (2, transaction, required),
1469 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1475 _init_and_read_len_prefixed_tlv_fields!(reader, {
1476 (0, payment_id, required),
1477 (2, payment_hash, option),
1478 (4, path, required_vec),
1479 (6, blinded_tail, option),
1481 Ok(Some(Event::PaymentPathSuccessful {
1482 payment_id: payment_id.0.unwrap(),
1484 path: Path { hops: path, blinded_tail },
1491 let mut payment_hash = PaymentHash([0; 32]);
1492 let mut payment_id = PaymentId([0; 32]);
1493 let mut reason = None;
1494 read_tlv_fields!(reader, {
1495 (0, payment_id, required),
1496 (1, reason, upgradable_option),
1497 (2, payment_hash, required),
1499 Ok(Some(Event::PaymentFailed {
1508 // Value 17 is used for `Event::OpenChannelRequest`.
1513 let mut payment_hash = PaymentHash([0; 32]);
1514 let mut purpose = UpgradableRequired(None);
1515 let mut amount_msat = 0;
1516 let mut receiver_node_id = None;
1517 let mut htlcs: Option<Vec<ClaimedHTLC>> = Some(vec![]);
1518 let mut sender_intended_total_msat: Option<u64> = None;
1519 read_tlv_fields!(reader, {
1520 (0, payment_hash, required),
1521 (1, receiver_node_id, option),
1522 (2, purpose, upgradable_required),
1523 (4, amount_msat, required),
1524 (5, htlcs, optional_vec),
1525 (7, sender_intended_total_msat, option),
1527 Ok(Some(Event::PaymentClaimed {
1530 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1532 htlcs: htlcs.unwrap_or(vec![]),
1533 sender_intended_total_msat,
1540 _init_and_read_len_prefixed_tlv_fields!(reader, {
1541 (0, payment_id, required),
1542 (2, payment_hash, required),
1543 (4, path, required_vec),
1544 (6, blinded_tail, option),
1546 Ok(Some(Event::ProbeSuccessful {
1547 payment_id: payment_id.0.unwrap(),
1548 payment_hash: payment_hash.0.unwrap(),
1549 path: Path { hops: path, blinded_tail },
1556 _init_and_read_len_prefixed_tlv_fields!(reader, {
1557 (0, payment_id, required),
1558 (2, payment_hash, required),
1559 (4, path, required_vec),
1560 (6, short_channel_id, option),
1561 (8, blinded_tail, option),
1563 Ok(Some(Event::ProbeFailed {
1564 payment_id: payment_id.0.unwrap(),
1565 payment_hash: payment_hash.0.unwrap(),
1566 path: Path { hops: path, blinded_tail },
1574 let mut prev_channel_id = ChannelId::new_zero();
1575 let mut failed_next_destination_opt = UpgradableRequired(None);
1576 read_tlv_fields!(reader, {
1577 (0, prev_channel_id, required),
1578 (2, failed_next_destination_opt, upgradable_required),
1580 Ok(Some(Event::HTLCHandlingFailed {
1582 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1590 let mut channel_id = ChannelId::new_zero();
1591 let mut user_channel_id: u128 = 0;
1592 let mut counterparty_node_id = RequiredWrapper(None);
1593 let mut channel_type = RequiredWrapper(None);
1594 read_tlv_fields!(reader, {
1595 (0, channel_id, required),
1596 (2, user_channel_id, required),
1597 (4, counterparty_node_id, required),
1598 (6, channel_type, required),
1601 Ok(Some(Event::ChannelReady {
1604 counterparty_node_id: counterparty_node_id.0.unwrap(),
1605 channel_type: channel_type.0.unwrap()
1612 let mut channel_id = ChannelId::new_zero();
1613 let mut user_channel_id: u128 = 0;
1614 let mut former_temporary_channel_id = None;
1615 let mut counterparty_node_id = RequiredWrapper(None);
1616 let mut funding_txo = RequiredWrapper(None);
1617 let mut channel_type = None;
1618 read_tlv_fields!(reader, {
1619 (0, channel_id, required),
1620 (1, channel_type, option),
1621 (2, user_channel_id, required),
1622 (4, former_temporary_channel_id, required),
1623 (6, counterparty_node_id, required),
1624 (8, funding_txo, required),
1627 Ok(Some(Event::ChannelPending {
1630 former_temporary_channel_id,
1631 counterparty_node_id: counterparty_node_id.0.unwrap(),
1632 funding_txo: funding_txo.0.unwrap(),
1640 _init_and_read_len_prefixed_tlv_fields!(reader, {
1641 (0, payment_id, required),
1643 Ok(Some(Event::InvoiceRequestFailed {
1644 payment_id: payment_id.0.unwrap(),
1649 // Note that we do not write a length-prefixed TLV for ConnectionNeeded events.
1651 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1652 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1654 x if x % 2 == 1 => {
1655 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1656 // which prefixes the whole thing with a length BigSize. Because the event is
1657 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1658 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1659 // exactly the number of bytes specified, ignoring them entirely.
1660 let tlv_len: BigSize = Readable::read(reader)?;
1661 FixedLengthReader::new(reader, tlv_len.0)
1662 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1665 _ => Err(msgs::DecodeError::InvalidValue)
1670 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1671 /// broadcast to most peers).
1672 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1673 #[derive(Clone, Debug)]
1674 #[cfg_attr(test, derive(PartialEq))]
1675 pub enum MessageSendEvent {
1676 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1677 /// message provided to the given peer.
1679 /// The node_id of the node which should receive this message
1681 /// The message which should be sent.
1682 msg: msgs::AcceptChannel,
1684 /// Used to indicate that we've accepted a V2 channel open and should send the accept_channel2
1685 /// message provided to the given peer.
1686 SendAcceptChannelV2 {
1687 /// The node_id of the node which should receive this message
1689 /// The message which should be sent.
1690 msg: msgs::AcceptChannelV2,
1692 /// Used to indicate that we've initiated a channel open and should send the open_channel
1693 /// message provided to the given peer.
1695 /// The node_id of the node which should receive this message
1697 /// The message which should be sent.
1698 msg: msgs::OpenChannel,
1700 /// Used to indicate that we've initiated a V2 channel open and should send the open_channel2
1701 /// message provided to the given peer.
1703 /// The node_id of the node which should receive this message
1705 /// The message which should be sent.
1706 msg: msgs::OpenChannelV2,
1708 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1709 SendFundingCreated {
1710 /// The node_id of the node which should receive this message
1712 /// The message which should be sent.
1713 msg: msgs::FundingCreated,
1715 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1717 /// The node_id of the node which should receive this message
1719 /// The message which should be sent.
1720 msg: msgs::FundingSigned,
1722 /// Used to indicate that a stfu message should be sent to the peer with the given node id.
1724 /// The node_id of the node which should receive this message
1726 /// The message which should be sent.
1729 /// Used to indicate that a splice message should be sent to the peer with the given node id.
1731 /// The node_id of the node which should receive this message
1733 /// The message which should be sent.
1736 /// Used to indicate that a splice_ack message should be sent to the peer with the given node id.
1738 /// The node_id of the node which should receive this message
1740 /// The message which should be sent.
1741 msg: msgs::SpliceAck,
1743 /// Used to indicate that a splice_locked message should be sent to the peer with the given node id.
1745 /// The node_id of the node which should receive this message
1747 /// The message which should be sent.
1748 msg: msgs::SpliceLocked,
1750 /// Used to indicate that a tx_add_input message should be sent to the peer with the given node_id.
1752 /// The node_id of the node which should receive this message
1754 /// The message which should be sent.
1755 msg: msgs::TxAddInput,
1757 /// Used to indicate that a tx_add_output message should be sent to the peer with the given node_id.
1759 /// The node_id of the node which should receive this message
1761 /// The message which should be sent.
1762 msg: msgs::TxAddOutput,
1764 /// Used to indicate that a tx_remove_input message should be sent to the peer with the given node_id.
1766 /// The node_id of the node which should receive this message
1768 /// The message which should be sent.
1769 msg: msgs::TxRemoveInput,
1771 /// Used to indicate that a tx_remove_output message should be sent to the peer with the given node_id.
1772 SendTxRemoveOutput {
1773 /// The node_id of the node which should receive this message
1775 /// The message which should be sent.
1776 msg: msgs::TxRemoveOutput,
1778 /// Used to indicate that a tx_complete message should be sent to the peer with the given node_id.
1780 /// The node_id of the node which should receive this message
1782 /// The message which should be sent.
1783 msg: msgs::TxComplete,
1785 /// Used to indicate that a tx_signatures message should be sent to the peer with the given node_id.
1787 /// The node_id of the node which should receive this message
1789 /// The message which should be sent.
1790 msg: msgs::TxSignatures,
1792 /// Used to indicate that a tx_init_rbf message should be sent to the peer with the given node_id.
1794 /// The node_id of the node which should receive this message
1796 /// The message which should be sent.
1797 msg: msgs::TxInitRbf,
1799 /// Used to indicate that a tx_ack_rbf message should be sent to the peer with the given node_id.
1801 /// The node_id of the node which should receive this message
1803 /// The message which should be sent.
1804 msg: msgs::TxAckRbf,
1806 /// Used to indicate that a tx_abort message should be sent to the peer with the given node_id.
1808 /// The node_id of the node which should receive this message
1810 /// The message which should be sent.
1813 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1815 /// The node_id of the node which should receive these message(s)
1817 /// The channel_ready message which should be sent.
1818 msg: msgs::ChannelReady,
1820 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1821 SendAnnouncementSignatures {
1822 /// The node_id of the node which should receive these message(s)
1824 /// The announcement_signatures message which should be sent.
1825 msg: msgs::AnnouncementSignatures,
1827 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1828 /// message should be sent to the peer with the given node_id.
1830 /// The node_id of the node which should receive these message(s)
1832 /// The update messages which should be sent. ALL messages in the struct should be sent!
1833 updates: msgs::CommitmentUpdate,
1835 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1837 /// The node_id of the node which should receive this message
1839 /// The message which should be sent.
1840 msg: msgs::RevokeAndACK,
1842 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1844 /// The node_id of the node which should receive this message
1846 /// The message which should be sent.
1847 msg: msgs::ClosingSigned,
1849 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1851 /// The node_id of the node which should receive this message
1853 /// The message which should be sent.
1854 msg: msgs::Shutdown,
1856 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1857 SendChannelReestablish {
1858 /// The node_id of the node which should receive this message
1860 /// The message which should be sent.
1861 msg: msgs::ChannelReestablish,
1863 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1864 /// initial connection to ensure our peers know about our channels.
1865 SendChannelAnnouncement {
1866 /// The node_id of the node which should receive this message
1868 /// The channel_announcement which should be sent.
1869 msg: msgs::ChannelAnnouncement,
1870 /// The followup channel_update which should be sent.
1871 update_msg: msgs::ChannelUpdate,
1873 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1874 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1876 /// Note that after doing so, you very likely (unless you did so very recently) want to
1877 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1878 /// ensures that any nodes which see our channel_announcement also have a relevant
1879 /// node_announcement, including relevant feature flags which may be important for routing
1880 /// through or to us.
1882 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1883 BroadcastChannelAnnouncement {
1884 /// The channel_announcement which should be sent.
1885 msg: msgs::ChannelAnnouncement,
1886 /// The followup channel_update which should be sent.
1887 update_msg: Option<msgs::ChannelUpdate>,
1889 /// Used to indicate that a channel_update should be broadcast to all peers.
1890 BroadcastChannelUpdate {
1891 /// The channel_update which should be sent.
1892 msg: msgs::ChannelUpdate,
1894 /// Used to indicate that a node_announcement should be broadcast to all peers.
1895 BroadcastNodeAnnouncement {
1896 /// The node_announcement which should be sent.
1897 msg: msgs::NodeAnnouncement,
1899 /// Used to indicate that a channel_update should be sent to a single peer.
1900 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1901 /// private channel and we shouldn't be informing all of our peers of channel parameters.
1903 /// The node_id of the node which should receive this message
1905 /// The channel_update which should be sent.
1906 msg: msgs::ChannelUpdate,
1908 /// Broadcast an error downstream to be handled
1910 /// The node_id of the node which should receive this message
1912 /// The action which should be taken.
1913 action: msgs::ErrorAction
1915 /// Query a peer for channels with funding transaction UTXOs in a block range.
1916 SendChannelRangeQuery {
1917 /// The node_id of this message recipient
1919 /// The query_channel_range which should be sent.
1920 msg: msgs::QueryChannelRange,
1922 /// Request routing gossip messages from a peer for a list of channels identified by
1923 /// their short_channel_ids.
1925 /// The node_id of this message recipient
1927 /// The query_short_channel_ids which should be sent.
1928 msg: msgs::QueryShortChannelIds,
1930 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1931 /// emitted during processing of the query.
1932 SendReplyChannelRange {
1933 /// The node_id of this message recipient
1935 /// The reply_channel_range which should be sent.
1936 msg: msgs::ReplyChannelRange,
1938 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1939 /// enable receiving gossip messages from the peer.
1940 SendGossipTimestampFilter {
1941 /// The node_id of this message recipient
1943 /// The gossip_timestamp_filter which should be sent.
1944 msg: msgs::GossipTimestampFilter,
1948 /// A trait indicating an object may generate message send events
1949 pub trait MessageSendEventsProvider {
1950 /// Gets the list of pending events which were generated by previous actions, clearing the list
1952 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1955 /// A trait indicating an object may generate events.
1957 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1959 /// Implementations of this trait may also feature an async version of event handling, as shown with
1960 /// [`ChannelManager::process_pending_events_async`] and
1961 /// [`ChainMonitor::process_pending_events_async`].
1965 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1966 /// event since the last invocation.
1968 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1969 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1970 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1971 /// relevant changes to disk *before* returning.
1973 /// Further, because an application may crash between an [`Event`] being handled and the
1974 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1975 /// effect, [`Event`]s may be replayed.
1977 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1978 /// consult the provider's documentation on the implication of processing events and how a handler
1979 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1980 /// [`ChainMonitor::process_pending_events`]).
1982 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1985 /// [`process_pending_events`]: Self::process_pending_events
1986 /// [`handle_event`]: EventHandler::handle_event
1987 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1988 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1989 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
1990 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
1991 pub trait EventsProvider {
1992 /// Processes any events generated since the last call using the given event handler.
1994 /// See the trait-level documentation for requirements.
1995 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1998 /// A trait implemented for objects handling events from [`EventsProvider`].
2000 /// An async variation also exists for implementations of [`EventsProvider`] that support async
2001 /// event handling. The async event handler should satisfy the generic bounds: `F:
2002 /// core::future::Future, H: Fn(Event) -> F`.
2003 pub trait EventHandler {
2004 /// Handles the given [`Event`].
2006 /// See [`EventsProvider`] for details that must be considered when implementing this method.
2007 fn handle_event(&self, event: Event);
2010 impl<F> EventHandler for F where F: Fn(Event) {
2011 fn handle_event(&self, event: Event) {
2016 impl<T: EventHandler> EventHandler for Arc<T> {
2017 fn handle_event(&self, event: Event) {
2018 self.deref().handle_event(event)