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 // Can be removed once we disallow downgrading to 0.0.121
188 LegacyCooperativeClosure,
189 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
190 /// the cooperative close transaction. This indicates that the shutdown was initiated by our
192 CounterpartyInitiatedCooperativeClosure,
193 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
194 /// the cooperative close transaction. This indicates that the shutdown was initiated by us.
195 LocallyInitiatedCooperativeClosure,
196 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
197 /// commitment transaction came from our counterparty, but it may also have come from
198 /// a copy of our own `ChannelMonitor`.
199 CommitmentTxConfirmed,
200 /// The funding transaction failed to confirm in a timely manner on an inbound channel.
202 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
204 /// A developer-readable error message which we generated.
207 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
208 /// forget the channel entirely - we can attempt again if the peer reconnects.
210 /// This includes cases where we restarted prior to funding completion, including prior to the
211 /// initial [`ChannelMonitor`] persistence completing.
213 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
214 /// peer because of mutual incompatibility between us and our channel counterparty.
216 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
218 /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
219 /// the [`ChannelManager`] deserialized.
221 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
222 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
223 OutdatedChannelManager,
224 /// The counterparty requested a cooperative close of a channel that had not been funded yet.
225 /// The channel has been immediately closed.
226 CounterpartyCoopClosedUnfundedChannel,
227 /// Another channel in the same funding batch closed before the funding transaction
228 /// was ready to be broadcast.
232 impl core::fmt::Display for ClosureReason {
233 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
234 f.write_str("Channel closed because ")?;
236 ClosureReason::CounterpartyForceClosed { peer_msg } => {
237 f.write_fmt(format_args!("counterparty force-closed with message: {}", peer_msg))
239 ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
240 ClosureReason::LegacyCooperativeClosure => f.write_str("the channel was cooperatively closed"),
241 ClosureReason::CounterpartyInitiatedCooperativeClosure => f.write_str("the channel was cooperatively closed by our peer"),
242 ClosureReason::LocallyInitiatedCooperativeClosure => f.write_str("the channel was cooperatively closed by us"),
243 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
244 ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
245 ClosureReason::ProcessingError { err } => {
246 f.write_str("of an exception: ")?;
249 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
250 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
251 ClosureReason::CounterpartyCoopClosedUnfundedChannel => f.write_str("the peer requested the unfunded channel be closed"),
252 ClosureReason::FundingBatchClosure => f.write_str("another channel in the same funding batch closed"),
257 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
258 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
259 (1, FundingTimedOut) => {},
260 (2, HolderForceClosed) => {},
261 (6, CommitmentTxConfirmed) => {},
262 (4, LegacyCooperativeClosure) => {},
263 (8, ProcessingError) => { (1, err, required) },
264 (10, DisconnectedPeer) => {},
265 (12, OutdatedChannelManager) => {},
266 (13, CounterpartyCoopClosedUnfundedChannel) => {},
267 (15, FundingBatchClosure) => {},
268 (17, CounterpartyInitiatedCooperativeClosure) => {},
269 (19, LocallyInitiatedCooperativeClosure) => {},
272 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
273 #[derive(Clone, Debug, PartialEq, Eq)]
274 pub enum HTLCDestination {
275 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
276 /// there is insufficient capacity in our outbound channel.
278 /// The `node_id` of the next node. For backwards compatibility, this field is
279 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
280 /// counterparty node information.
281 node_id: Option<PublicKey>,
282 /// The outgoing `channel_id` between us and the next node.
283 channel_id: ChannelId,
285 /// Scenario where we are unsure of the next node to forward the HTLC to.
287 /// Short channel id we are requesting to forward an HTLC to.
288 requested_forward_scid: u64,
290 /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
293 /// Short channel id we are requesting to forward an HTLC to.
294 requested_forward_scid: u64
296 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
297 /// but is invalid for some reason, so we reject it.
299 /// Some of the reasons may include:
301 /// * Excess HTLCs for a payment that we have already fully received, over-paying for the
303 /// * The counterparty node modified the HTLC in transit,
304 /// * A probing attack where an intermediary node is trying to detect if we are the ultimate
305 /// recipient for a payment.
307 /// The payment hash of the payment we attempted to process.
308 payment_hash: PaymentHash
312 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
313 (0, NextHopChannel) => {
314 (0, node_id, required),
315 (2, channel_id, required),
317 (1, InvalidForward) => {
318 (0, requested_forward_scid, required),
320 (2, UnknownNextHop) => {
321 (0, requested_forward_scid, required),
323 (4, FailedPayment) => {
324 (0, payment_hash, required),
328 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
329 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
330 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
331 /// intercepts in upcoming work.
332 enum InterceptNextHop {
334 requested_next_hop_scid: u64,
338 impl_writeable_tlv_based_enum!(InterceptNextHop,
340 (0, requested_next_hop_scid, required),
344 /// The reason the payment failed. Used in [`Event::PaymentFailed`].
345 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
346 pub enum PaymentFailureReason {
347 /// The intended recipient rejected our payment.
349 /// The user chose to abandon this payment by calling [`ChannelManager::abandon_payment`].
351 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
353 /// We exhausted all of our retry attempts while trying to send the payment, or we
354 /// exhausted the [`Retry::Timeout`] if the user set one. If at any point a retry
355 /// attempt failed while being forwarded along the path, an [`Event::PaymentPathFailed`] will
356 /// have come before this.
358 /// [`Retry::Timeout`]: crate::ln::channelmanager::Retry::Timeout
360 /// The payment expired while retrying, based on the provided
361 /// [`PaymentParameters::expiry_time`].
363 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
365 /// We failed to find a route while retrying the payment.
367 /// This error should generally never happen. This likely means that there is a problem with
372 impl_writeable_tlv_based_enum!(PaymentFailureReason,
373 (0, RecipientRejected) => {},
374 (2, UserAbandoned) => {},
375 (4, RetriesExhausted) => {},
376 (6, PaymentExpired) => {},
377 (8, RouteNotFound) => {},
378 (10, UnexpectedError) => {}, ;
381 /// An Event which you should probably take some action in response to.
383 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
384 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
385 /// written as it makes no sense to respond to it after reconnecting to peers).
386 #[derive(Clone, Debug, PartialEq, Eq)]
388 /// Used to indicate that the client should generate a funding transaction with the given
389 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
390 /// Generated in [`ChannelManager`] message handling.
391 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
392 /// counterparty can steal your funds!
394 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
395 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
396 FundingGenerationReady {
397 /// The random channel_id we picked which you'll need to pass into
398 /// [`ChannelManager::funding_transaction_generated`].
400 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
401 temporary_channel_id: ChannelId,
402 /// The counterparty's node_id, which you'll need to pass back into
403 /// [`ChannelManager::funding_transaction_generated`].
405 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
406 counterparty_node_id: PublicKey,
407 /// The value, in satoshis, that the output should have.
408 channel_value_satoshis: u64,
409 /// The script which should be used in the transaction output.
410 output_script: ScriptBuf,
411 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
412 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
413 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
414 /// `user_channel_id` will be randomized for an inbound channel. This may be zero for objects
415 /// serialized with LDK versions prior to 0.0.113.
417 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
418 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
419 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
420 user_channel_id: u128,
422 /// Indicates that we've been offered a payment and it needs to be claimed via calling
423 /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
425 /// Note that if the preimage is not known, you should call
426 /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
427 /// to free up resources for this HTLC and avoid network congestion.
429 /// If [`Event::PaymentClaimable::onion_fields`] is `Some`, and includes custom TLVs with even type
430 /// numbers, you should use [`ChannelManager::fail_htlc_backwards_with_reason`] with
431 /// [`FailureCode::InvalidOnionPayload`] if you fail to understand and handle the contents, or
432 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`] upon successful handling.
433 /// If you don't intend to check for custom TLVs, you can simply use
434 /// [`ChannelManager::claim_funds`], which will automatically fail back even custom TLVs.
436 /// If you fail to call [`ChannelManager::claim_funds`],
437 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`],
438 /// [`ChannelManager::fail_htlc_backwards`], or
439 /// [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will
440 /// be automatically failed.
443 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
444 /// `PaymentClaimable` events may be generated for the same payment. In such a case it is
445 /// polite (and required in the lightning specification) to fail the payment the second time
446 /// and give the sender their money back rather than accepting double payment.
449 /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
451 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
452 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`]: crate::ln::channelmanager::ChannelManager::claim_funds_with_known_custom_tlvs
453 /// [`FailureCode::InvalidOnionPayload`]: crate::ln::channelmanager::FailureCode::InvalidOnionPayload
454 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
455 /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
457 /// The node that will receive the payment after it has been claimed.
458 /// This is useful to identify payments received via [phantom nodes].
459 /// This field will always be filled in when the event was generated by LDK versions
460 /// 0.0.113 and above.
462 /// [phantom nodes]: crate::sign::PhantomKeysManager
463 receiver_node_id: Option<PublicKey>,
464 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
465 /// not stop you from registering duplicate payment hashes for inbound payments.
466 payment_hash: PaymentHash,
467 /// The fields in the onion which were received with each HTLC. Only fields which were
468 /// identical in each HTLC involved in the payment will be included here.
470 /// Payments received on LDK versions prior to 0.0.115 will have this field unset.
471 onion_fields: Option<RecipientOnionFields>,
472 /// The value, in thousandths of a satoshi, that this payment is claimable for. May be greater
473 /// than the invoice amount.
475 /// May be less than the invoice amount if [`ChannelConfig::accept_underpaying_htlcs`] is set
476 /// and the previous hop took an extra fee.
479 /// If [`ChannelConfig::accept_underpaying_htlcs`] is set and you claim without verifying this
480 /// field, you may lose money!
482 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
484 /// The value, in thousands of a satoshi, that was skimmed off of this payment as an extra fee
485 /// taken by our channel counterparty.
487 /// Will always be 0 unless [`ChannelConfig::accept_underpaying_htlcs`] is set.
489 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
490 counterparty_skimmed_fee_msat: u64,
491 /// Information for claiming this received payment, based on whether the purpose of the
492 /// payment is to pay an invoice or to send a spontaneous payment.
493 purpose: PaymentPurpose,
494 /// The `channel_id` indicating over which channel we received the payment.
495 via_channel_id: Option<ChannelId>,
496 /// The `user_channel_id` indicating over which channel we received the payment.
497 via_user_channel_id: Option<u128>,
498 /// The block height at which this payment will be failed back and will no longer be
499 /// eligible for claiming.
501 /// Prior to this height, a call to [`ChannelManager::claim_funds`] is guaranteed to
502 /// succeed, however you should wait for [`Event::PaymentClaimed`] to be sure.
504 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
505 claim_deadline: Option<u32>,
507 /// Indicates a payment has been claimed and we've received money!
509 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
510 /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
511 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
512 /// [`Event::PaymentClaimable`] event.
515 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
516 /// `PaymentClaimable` events may be generated for the same payment. If you then call
517 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
518 /// multiple `PaymentClaimed` events.
520 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
522 /// The node that received the payment.
523 /// This is useful to identify payments which were received via [phantom nodes].
524 /// This field will always be filled in when the event was generated by LDK versions
525 /// 0.0.113 and above.
527 /// [phantom nodes]: crate::sign::PhantomKeysManager
528 receiver_node_id: Option<PublicKey>,
529 /// The payment hash of the claimed payment. Note that LDK will not stop you from
530 /// registering duplicate payment hashes for inbound payments.
531 payment_hash: PaymentHash,
532 /// The value, in thousandths of a satoshi, that this payment is for. May be greater than the
535 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
536 /// spontaneous payment.
537 purpose: PaymentPurpose,
538 /// The HTLCs that comprise the claimed payment. This will be empty for events serialized prior
539 /// to LDK version 0.0.117.
540 htlcs: Vec<ClaimedHTLC>,
541 /// The sender-intended sum total of all the MPP parts. This will be `None` for events
542 /// serialized prior to LDK version 0.0.117.
543 sender_intended_total_msat: Option<u64>,
545 /// Indicates that a peer connection with a node is needed in order to send an [`OnionMessage`].
547 /// Typically, this happens when a [`MessageRouter`] is unable to find a complete path to a
548 /// [`Destination`]. Once a connection is established, any messages buffered by an
549 /// [`OnionMessageHandler`] may be sent.
551 /// This event will not be generated for onion message forwards; only for sends including
552 /// replies. Handlers should connect to the node otherwise any buffered messages may be lost.
554 /// [`OnionMessage`]: msgs::OnionMessage
555 /// [`MessageRouter`]: crate::onion_message::messenger::MessageRouter
556 /// [`Destination`]: crate::onion_message::messenger::Destination
557 /// [`OnionMessageHandler`]: crate::ln::msgs::OnionMessageHandler
559 /// The node id for the node needing a connection.
561 /// Sockets for connecting to the node.
562 addresses: Vec<msgs::SocketAddress>,
564 /// Indicates a request for an invoice failed to yield a response in a reasonable amount of time
565 /// or was explicitly abandoned by [`ChannelManager::abandon_payment`]. This may be for an
566 /// [`InvoiceRequest`] sent for an [`Offer`] or for a [`Refund`] that hasn't been redeemed.
568 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
569 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
570 /// [`Offer`]: crate::offers::offer::Offer
571 /// [`Refund`]: crate::offers::refund::Refund
572 InvoiceRequestFailed {
573 /// The `payment_id` to have been associated with payment for the requested invoice.
574 payment_id: PaymentId,
576 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
577 /// and we got back the payment preimage for it).
579 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
580 /// event. In this situation, you SHOULD treat this payment as having succeeded.
582 /// The `payment_id` passed to [`ChannelManager::send_payment`].
584 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
585 payment_id: Option<PaymentId>,
586 /// The preimage to the hash given to ChannelManager::send_payment.
587 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
588 /// store it somehow!
589 payment_preimage: PaymentPreimage,
590 /// The hash that was given to [`ChannelManager::send_payment`].
592 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
593 payment_hash: PaymentHash,
594 /// The total fee which was spent at intermediate hops in this payment, across all paths.
596 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
597 /// overpayment to the recipient node.
599 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
600 /// overstate the amount paid, though this is unlikely.
602 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
603 fee_paid_msat: Option<u64>,
605 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
606 /// provide failure information for each path attempt in the payment, including retries.
608 /// This event is provided once there are no further pending HTLCs for the payment and the
609 /// payment is no longer retryable, due either to the [`Retry`] provided or
610 /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
612 /// In exceedingly rare cases, it is possible that an [`Event::PaymentFailed`] is generated for
613 /// a payment after an [`Event::PaymentSent`] event for this same payment has already been
614 /// received and processed. In this case, the [`Event::PaymentFailed`] event MUST be ignored,
615 /// and the payment MUST be treated as having succeeded.
617 /// [`Retry`]: crate::ln::channelmanager::Retry
618 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
620 /// The `payment_id` passed to [`ChannelManager::send_payment`].
622 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
623 payment_id: PaymentId,
624 /// The hash that was given to [`ChannelManager::send_payment`].
626 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
627 payment_hash: PaymentHash,
628 /// The reason the payment failed. This is only `None` for events generated or serialized
629 /// by versions prior to 0.0.115.
630 reason: Option<PaymentFailureReason>,
632 /// Indicates that a path for an outbound payment was successful.
634 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
635 /// [`Event::PaymentSent`] for obtaining the payment preimage.
636 PaymentPathSuccessful {
637 /// The `payment_id` passed to [`ChannelManager::send_payment`].
639 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
640 payment_id: PaymentId,
641 /// The hash that was given to [`ChannelManager::send_payment`].
643 /// This will be `Some` for all payments which completed on LDK 0.0.104 or later.
645 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
646 payment_hash: Option<PaymentHash>,
647 /// The payment path that was successful.
649 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
652 /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
655 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
656 /// [`Event::PaymentFailed`].
658 /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
661 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
663 /// The `payment_id` passed to [`ChannelManager::send_payment`].
665 /// This will be `Some` for all payment paths which failed on LDK 0.0.103 or later.
667 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
668 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
669 payment_id: Option<PaymentId>,
670 /// The hash that was given to [`ChannelManager::send_payment`].
672 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
673 payment_hash: PaymentHash,
674 /// Indicates the payment was rejected for some reason by the recipient. This implies that
675 /// the payment has failed, not just the route in question. If this is not set, the payment may
676 /// be retried via a different route.
677 payment_failed_permanently: bool,
678 /// Extra error details based on the failure type. May contain an update that needs to be
679 /// applied to the [`NetworkGraph`].
681 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
682 failure: PathFailure,
683 /// The payment path that failed.
685 /// The channel responsible for the failed payment path.
687 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
688 /// may not refer to a channel in the public network graph. These aliases may also collide
689 /// with channels in the public network graph.
691 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
692 /// retried. May be `None` for older [`Event`] serializations.
693 short_channel_id: Option<u64>,
695 error_code: Option<u16>,
697 error_data: Option<Vec<u8>>,
699 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
701 /// The id returned by [`ChannelManager::send_probe`].
703 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
704 payment_id: PaymentId,
705 /// The hash generated by [`ChannelManager::send_probe`].
707 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
708 payment_hash: PaymentHash,
709 /// The payment path that was successful.
712 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
714 /// The id returned by [`ChannelManager::send_probe`].
716 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
717 payment_id: PaymentId,
718 /// The hash generated by [`ChannelManager::send_probe`].
720 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
721 payment_hash: PaymentHash,
722 /// The payment path that failed.
724 /// The channel responsible for the failed probe.
726 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
727 /// may not refer to a channel in the public network graph. These aliases may also collide
728 /// with channels in the public network graph.
729 short_channel_id: Option<u64>,
731 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
732 /// a time in the future.
734 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
735 PendingHTLCsForwardable {
736 /// The minimum amount of time that should be waited prior to calling
737 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
738 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
739 /// now + 5*time_forwardable).
740 time_forwardable: Duration,
742 /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
743 /// you've encoded an intercept scid in the receiver's invoice route hints using
744 /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
746 /// [`ChannelManager::forward_intercepted_htlc`] or
747 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
748 /// their docs for more information.
750 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
751 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
752 /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
753 /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
755 /// An id to help LDK identify which HTLC is being forwarded or failed.
756 intercept_id: InterceptId,
757 /// The fake scid that was programmed as the next hop's scid, generated using
758 /// [`ChannelManager::get_intercept_scid`].
760 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
761 requested_next_hop_scid: u64,
762 /// The payment hash used for this HTLC.
763 payment_hash: PaymentHash,
764 /// How many msats were received on the inbound edge of this HTLC.
765 inbound_amount_msat: u64,
766 /// How many msats the payer intended to route to the next node. Depending on the reason you are
767 /// intercepting this payment, you might take a fee by forwarding less than this amount.
768 /// Forwarding less than this amount may break compatibility with LDK versions prior to 0.0.116.
770 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
771 /// check that whatever fee you want has been included here or subtract it as required. Further,
772 /// LDK will not stop you from forwarding more than you received.
773 expected_outbound_amount_msat: u64,
775 /// Used to indicate that an output which you should know how to spend was confirmed on chain
776 /// and is now spendable.
777 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
778 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
779 /// somewhere and spend them when you create on-chain transactions.
781 /// The outputs which you should store as spendable by you.
782 outputs: Vec<SpendableOutputDescriptor>,
783 /// The `channel_id` indicating which channel the spendable outputs belong to.
785 /// This will always be `Some` for events generated by LDK versions 0.0.117 and above.
786 channel_id: Option<ChannelId>,
788 /// This event is generated when a payment has been successfully forwarded through us and a
789 /// forwarding fee earned.
791 /// The incoming channel between the previous node and us. This is only `None` for events
792 /// generated or serialized by versions prior to 0.0.107.
793 prev_channel_id: Option<ChannelId>,
794 /// The outgoing channel between the next node and us. This is only `None` for events
795 /// generated or serialized by versions prior to 0.0.107.
796 next_channel_id: Option<ChannelId>,
797 /// The fee, in milli-satoshis, which was earned as a result of the payment.
799 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
800 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
801 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
802 /// claimed the full value in millisatoshis from the source. In this case,
803 /// `claim_from_onchain_tx` will be set.
805 /// If the channel which sent us the payment has been force-closed, we will claim the funds
806 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
807 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
808 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
810 fee_earned_msat: Option<u64>,
811 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
813 claim_from_onchain_tx: bool,
814 /// The final amount forwarded, in milli-satoshis, after the fee is deducted.
816 /// The caveat described above the `fee_earned_msat` field applies here as well.
817 outbound_amount_forwarded_msat: Option<u64>,
819 /// Used to indicate that a channel with the given `channel_id` is being opened and pending
820 /// confirmation on-chain.
822 /// This event is emitted when the funding transaction has been signed and is broadcast to the
823 /// network. For 0conf channels it will be immediately followed by the corresponding
824 /// [`Event::ChannelReady`] event.
826 /// The `channel_id` of the channel that is pending confirmation.
827 channel_id: ChannelId,
828 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
829 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
830 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
831 /// `user_channel_id` will be randomized for an inbound channel.
833 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
834 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
835 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
836 user_channel_id: u128,
837 /// The `temporary_channel_id` this channel used to be known by during channel establishment.
839 /// Will be `None` for channels created prior to LDK version 0.0.115.
840 former_temporary_channel_id: Option<ChannelId>,
841 /// The `node_id` of the channel counterparty.
842 counterparty_node_id: PublicKey,
843 /// The outpoint of the channel's funding transaction.
844 funding_txo: OutPoint,
846 /// Used to indicate that a channel with the given `channel_id` is ready to
847 /// be used. This event is emitted either when the funding transaction has been confirmed
848 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
851 /// The `channel_id` of the channel that is ready.
852 channel_id: ChannelId,
853 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
854 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
855 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
856 /// `user_channel_id` will be randomized for an inbound channel.
858 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
859 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
860 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
861 user_channel_id: u128,
862 /// The `node_id` of the channel counterparty.
863 counterparty_node_id: PublicKey,
864 /// The features that this channel will operate with.
865 channel_type: ChannelTypeFeatures,
867 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
868 /// process of closure.
870 /// Note that this event is only triggered for accepted channels: if the
871 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true and the channel is
872 /// rejected, no `ChannelClosed` event will be sent.
874 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
875 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
877 /// The `channel_id` of the channel which has been closed. Note that on-chain transactions
878 /// resolving the channel are likely still awaiting confirmation.
879 channel_id: ChannelId,
880 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
881 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
882 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
883 /// `user_channel_id` will be randomized for inbound channels.
884 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
885 /// zero for objects serialized with LDK versions prior to 0.0.102.
887 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
888 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
889 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
890 user_channel_id: u128,
891 /// The reason the channel was closed.
892 reason: ClosureReason,
893 /// Counterparty in the closed channel.
895 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
896 counterparty_node_id: Option<PublicKey>,
897 /// Channel capacity of the closing channel (sats).
899 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
900 channel_capacity_sats: Option<u64>,
901 /// The original channel funding TXO; this helps checking for the existence and confirmation
902 /// status of the closing tx.
903 /// Note that for instances serialized in v0.0.119 or prior this will be missing (None).
904 channel_funding_txo: Option<transaction::OutPoint>,
906 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
907 /// inputs for another purpose.
909 /// This event is not guaranteed to be generated for channels that are closed due to a restart.
911 /// The channel_id of the channel which has been closed.
912 channel_id: ChannelId,
913 /// The full transaction received from the user
914 transaction: Transaction
916 /// Indicates a request to open a new channel by a peer.
918 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the request,
919 /// call [`ChannelManager::force_close_without_broadcasting_txn`]. Note that a ['ChannelClosed`]
920 /// event will _not_ be triggered if the channel is rejected.
922 /// The event is only triggered when a new open channel request is received and the
923 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
925 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
926 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
927 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
929 /// The temporary channel ID of the channel requested to be opened.
931 /// When responding to the request, the `temporary_channel_id` should be passed
932 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
933 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
935 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
936 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
937 temporary_channel_id: ChannelId,
938 /// The node_id of the counterparty requesting to open the channel.
940 /// When responding to the request, the `counterparty_node_id` should be passed
941 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
942 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
945 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
946 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
947 counterparty_node_id: PublicKey,
948 /// The channel value of the requested channel.
949 funding_satoshis: u64,
950 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
952 /// The features that this channel will operate with. If you reject the channel, a
953 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
956 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
957 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
960 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
961 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
962 /// 0.0.107. Channels setting this type also need to get manually accepted via
963 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
964 /// or will be rejected otherwise.
966 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
967 channel_type: ChannelTypeFeatures,
969 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
972 /// Some scenarios where this event may be sent include:
973 /// * Insufficient capacity in the outbound channel
974 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
975 /// * When an unknown SCID is requested for forwarding a payment.
976 /// * Expected MPP amount has already been reached
977 /// * The HTLC has timed out
979 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
980 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
982 /// The channel over which the HTLC was received.
983 prev_channel_id: ChannelId,
984 /// Destination of the HTLC that failed to be processed.
985 failed_next_destination: HTLCDestination,
987 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
988 /// requires confirmed external funds to be readily available to spend.
990 /// LDK does not currently generate this event unless the
991 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`] config flag is set to true.
992 /// It is limited to the scope of channels with anchor outputs.
994 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`]: crate::util::config::ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx
995 BumpTransaction(BumpTransactionEvent),
998 impl Writeable for Event {
999 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1001 &Event::FundingGenerationReady { .. } => {
1003 // We never write out FundingGenerationReady events as, upon disconnection, peers
1004 // drop any channels which have not yet exchanged funding_signed.
1006 &Event::PaymentClaimable { ref payment_hash, ref amount_msat, counterparty_skimmed_fee_msat,
1007 ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id,
1008 ref claim_deadline, ref onion_fields
1011 let mut payment_secret = None;
1012 let payment_preimage;
1014 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
1015 payment_secret = Some(secret);
1016 payment_preimage = *preimage;
1018 PaymentPurpose::SpontaneousPayment(preimage) => {
1019 payment_preimage = Some(*preimage);
1022 let skimmed_fee_opt = if counterparty_skimmed_fee_msat == 0 { None }
1023 else { Some(counterparty_skimmed_fee_msat) };
1024 write_tlv_fields!(writer, {
1025 (0, payment_hash, required),
1026 (1, receiver_node_id, option),
1027 (2, payment_secret, option),
1028 (3, via_channel_id, option),
1029 (4, amount_msat, required),
1030 (5, via_user_channel_id, option),
1031 // Type 6 was `user_payment_id` on 0.0.103 and earlier
1032 (7, claim_deadline, option),
1033 (8, payment_preimage, option),
1034 (9, onion_fields, option),
1035 (10, skimmed_fee_opt, option),
1038 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
1040 write_tlv_fields!(writer, {
1041 (0, payment_preimage, required),
1042 (1, payment_hash, required),
1043 (3, payment_id, option),
1044 (5, fee_paid_msat, option),
1047 &Event::PaymentPathFailed {
1048 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
1049 ref path, ref short_channel_id,
1057 error_code.write(writer)?;
1059 error_data.write(writer)?;
1060 write_tlv_fields!(writer, {
1061 (0, payment_hash, required),
1062 (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
1063 (2, payment_failed_permanently, required),
1064 (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
1065 (4, path.blinded_tail, option),
1066 (5, path.hops, required_vec),
1067 (7, short_channel_id, option),
1068 (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
1069 (11, payment_id, option),
1070 (13, failure, required),
1073 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
1075 // Note that we now ignore these on the read end as we'll re-generate them in
1076 // ChannelManager, we write them here only for backwards compatibility.
1078 &Event::SpendableOutputs { ref outputs, channel_id } => {
1080 write_tlv_fields!(writer, {
1081 (0, WithoutLength(outputs), required),
1082 (1, channel_id, option),
1085 &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1087 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1088 write_tlv_fields!(writer, {
1089 (0, intercept_id, required),
1090 (2, intercept_scid, required),
1091 (4, payment_hash, required),
1092 (6, inbound_amount_msat, required),
1093 (8, expected_outbound_amount_msat, required),
1096 &Event::PaymentForwarded {
1097 fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
1098 next_channel_id, outbound_amount_forwarded_msat
1101 write_tlv_fields!(writer, {
1102 (0, fee_earned_msat, option),
1103 (1, prev_channel_id, option),
1104 (2, claim_from_onchain_tx, required),
1105 (3, next_channel_id, option),
1106 (5, outbound_amount_forwarded_msat, option),
1109 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason,
1110 ref counterparty_node_id, ref channel_capacity_sats, ref channel_funding_txo
1113 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1114 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1115 // separate u64 values.
1116 let user_channel_id_low = *user_channel_id as u64;
1117 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1118 write_tlv_fields!(writer, {
1119 (0, channel_id, required),
1120 (1, user_channel_id_low, required),
1121 (2, reason, required),
1122 (3, user_channel_id_high, required),
1123 (5, counterparty_node_id, option),
1124 (7, channel_capacity_sats, option),
1125 (9, channel_funding_txo, option),
1128 &Event::DiscardFunding { ref channel_id, ref transaction } => {
1129 11u8.write(writer)?;
1130 write_tlv_fields!(writer, {
1131 (0, channel_id, required),
1132 (2, transaction, required)
1135 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1136 13u8.write(writer)?;
1137 write_tlv_fields!(writer, {
1138 (0, payment_id, required),
1139 (2, payment_hash, option),
1140 (4, path.hops, required_vec),
1141 (6, path.blinded_tail, option),
1144 &Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
1145 15u8.write(writer)?;
1146 write_tlv_fields!(writer, {
1147 (0, payment_id, required),
1148 (1, reason, option),
1149 (2, payment_hash, required),
1152 &Event::OpenChannelRequest { .. } => {
1153 17u8.write(writer)?;
1154 // We never write the OpenChannelRequest events as, upon disconnection, peers
1155 // drop any channels which have not yet exchanged funding_signed.
1157 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref htlcs, ref sender_intended_total_msat } => {
1158 19u8.write(writer)?;
1159 write_tlv_fields!(writer, {
1160 (0, payment_hash, required),
1161 (1, receiver_node_id, option),
1162 (2, purpose, required),
1163 (4, amount_msat, required),
1164 (5, *htlcs, optional_vec),
1165 (7, sender_intended_total_msat, option),
1168 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1169 21u8.write(writer)?;
1170 write_tlv_fields!(writer, {
1171 (0, payment_id, required),
1172 (2, payment_hash, required),
1173 (4, path.hops, required_vec),
1174 (6, path.blinded_tail, option),
1177 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1178 23u8.write(writer)?;
1179 write_tlv_fields!(writer, {
1180 (0, payment_id, required),
1181 (2, payment_hash, required),
1182 (4, path.hops, required_vec),
1183 (6, short_channel_id, option),
1184 (8, path.blinded_tail, option),
1187 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1188 25u8.write(writer)?;
1189 write_tlv_fields!(writer, {
1190 (0, prev_channel_id, required),
1191 (2, failed_next_destination, required),
1194 &Event::BumpTransaction(ref event)=> {
1195 27u8.write(writer)?;
1197 // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1198 // upon restarting anyway if they remain unresolved.
1199 BumpTransactionEvent::ChannelClose { .. } => {}
1200 BumpTransactionEvent::HTLCResolution { .. } => {}
1202 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1204 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1205 29u8.write(writer)?;
1206 write_tlv_fields!(writer, {
1207 (0, channel_id, required),
1208 (2, user_channel_id, required),
1209 (4, counterparty_node_id, required),
1210 (6, channel_type, required),
1213 &Event::ChannelPending { ref channel_id, ref user_channel_id, ref former_temporary_channel_id, ref counterparty_node_id, ref funding_txo } => {
1214 31u8.write(writer)?;
1215 write_tlv_fields!(writer, {
1216 (0, channel_id, required),
1217 (2, user_channel_id, required),
1218 (4, former_temporary_channel_id, required),
1219 (6, counterparty_node_id, required),
1220 (8, funding_txo, required),
1223 &Event::InvoiceRequestFailed { ref payment_id } => {
1224 33u8.write(writer)?;
1225 write_tlv_fields!(writer, {
1226 (0, payment_id, required),
1229 &Event::ConnectionNeeded { .. } => {
1230 35u8.write(writer)?;
1231 // Never write ConnectionNeeded events as buffered onion messages aren't serialized.
1233 // Note that, going forward, all new events must only write data inside of
1234 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1235 // data via `write_tlv_fields`.
1240 impl MaybeReadable for Event {
1241 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1242 match Readable::read(reader)? {
1243 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events.
1247 let mut payment_hash = PaymentHash([0; 32]);
1248 let mut payment_preimage = None;
1249 let mut payment_secret = None;
1250 let mut amount_msat = 0;
1251 let mut counterparty_skimmed_fee_msat_opt = None;
1252 let mut receiver_node_id = None;
1253 let mut _user_payment_id = None::<u64>; // Used in 0.0.103 and earlier, no longer written in 0.0.116+.
1254 let mut via_channel_id = None;
1255 let mut claim_deadline = None;
1256 let mut via_user_channel_id = None;
1257 let mut onion_fields = None;
1258 read_tlv_fields!(reader, {
1259 (0, payment_hash, required),
1260 (1, receiver_node_id, option),
1261 (2, payment_secret, option),
1262 (3, via_channel_id, option),
1263 (4, amount_msat, required),
1264 (5, via_user_channel_id, option),
1265 (6, _user_payment_id, option),
1266 (7, claim_deadline, option),
1267 (8, payment_preimage, option),
1268 (9, onion_fields, option),
1269 (10, counterparty_skimmed_fee_msat_opt, option),
1271 let purpose = match payment_secret {
1272 Some(secret) => PaymentPurpose::InvoicePayment {
1274 payment_secret: secret
1276 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1277 None => return Err(msgs::DecodeError::InvalidValue),
1279 Ok(Some(Event::PaymentClaimable {
1283 counterparty_skimmed_fee_msat: counterparty_skimmed_fee_msat_opt.unwrap_or(0),
1286 via_user_channel_id,
1295 let mut payment_preimage = PaymentPreimage([0; 32]);
1296 let mut payment_hash = None;
1297 let mut payment_id = None;
1298 let mut fee_paid_msat = None;
1299 read_tlv_fields!(reader, {
1300 (0, payment_preimage, required),
1301 (1, payment_hash, option),
1302 (3, payment_id, option),
1303 (5, fee_paid_msat, option),
1305 if payment_hash.is_none() {
1306 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()));
1308 Ok(Some(Event::PaymentSent {
1311 payment_hash: payment_hash.unwrap(),
1320 let error_code = Readable::read(reader)?;
1322 let error_data = Readable::read(reader)?;
1323 let mut payment_hash = PaymentHash([0; 32]);
1324 let mut payment_failed_permanently = false;
1325 let mut network_update = None;
1326 let mut blinded_tail: Option<BlindedTail> = None;
1327 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1328 let mut short_channel_id = None;
1329 let mut payment_id = None;
1330 let mut failure_opt = None;
1331 read_tlv_fields!(reader, {
1332 (0, payment_hash, required),
1333 (1, network_update, upgradable_option),
1334 (2, payment_failed_permanently, required),
1335 (4, blinded_tail, option),
1336 // Added as a part of LDK 0.0.101 and always filled in since.
1337 // Defaults to an empty Vec, though likely should have been `Option`al.
1338 (5, path, optional_vec),
1339 (7, short_channel_id, option),
1340 (11, payment_id, option),
1341 (13, failure_opt, upgradable_option),
1343 let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1344 Ok(Some(Event::PaymentPathFailed {
1347 payment_failed_permanently,
1349 path: Path { hops: path.unwrap(), blinded_tail },
1362 let mut outputs = WithoutLength(Vec::new());
1363 let mut channel_id: Option<ChannelId> = None;
1364 read_tlv_fields!(reader, {
1365 (0, outputs, required),
1366 (1, channel_id, option),
1368 Ok(Some(Event::SpendableOutputs { outputs: outputs.0, channel_id }))
1373 let mut payment_hash = PaymentHash([0; 32]);
1374 let mut intercept_id = InterceptId([0; 32]);
1375 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1376 let mut inbound_amount_msat = 0;
1377 let mut expected_outbound_amount_msat = 0;
1378 read_tlv_fields!(reader, {
1379 (0, intercept_id, required),
1380 (2, requested_next_hop_scid, required),
1381 (4, payment_hash, required),
1382 (6, inbound_amount_msat, required),
1383 (8, expected_outbound_amount_msat, required),
1385 let next_scid = match requested_next_hop_scid {
1386 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1388 Ok(Some(Event::HTLCIntercepted {
1390 requested_next_hop_scid: next_scid,
1391 inbound_amount_msat,
1392 expected_outbound_amount_msat,
1398 let mut fee_earned_msat = None;
1399 let mut prev_channel_id = None;
1400 let mut claim_from_onchain_tx = false;
1401 let mut next_channel_id = None;
1402 let mut outbound_amount_forwarded_msat = None;
1403 read_tlv_fields!(reader, {
1404 (0, fee_earned_msat, option),
1405 (1, prev_channel_id, option),
1406 (2, claim_from_onchain_tx, required),
1407 (3, next_channel_id, option),
1408 (5, outbound_amount_forwarded_msat, option),
1410 Ok(Some(Event::PaymentForwarded {
1411 fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id,
1412 outbound_amount_forwarded_msat
1419 let mut channel_id = ChannelId::new_zero();
1420 let mut reason = UpgradableRequired(None);
1421 let mut user_channel_id_low_opt: Option<u64> = None;
1422 let mut user_channel_id_high_opt: Option<u64> = None;
1423 let mut counterparty_node_id = None;
1424 let mut channel_capacity_sats = None;
1425 let mut channel_funding_txo = None;
1426 read_tlv_fields!(reader, {
1427 (0, channel_id, required),
1428 (1, user_channel_id_low_opt, option),
1429 (2, reason, upgradable_required),
1430 (3, user_channel_id_high_opt, option),
1431 (5, counterparty_node_id, option),
1432 (7, channel_capacity_sats, option),
1433 (9, channel_funding_txo, option),
1436 // `user_channel_id` used to be a single u64 value. In order to remain
1437 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1438 // as two separate u64 values.
1439 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1440 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1442 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required),
1443 counterparty_node_id, channel_capacity_sats, channel_funding_txo }))
1449 let mut channel_id = ChannelId::new_zero();
1450 let mut transaction = Transaction{ version: 2, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
1451 read_tlv_fields!(reader, {
1452 (0, channel_id, required),
1453 (2, transaction, required),
1455 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1461 _init_and_read_len_prefixed_tlv_fields!(reader, {
1462 (0, payment_id, required),
1463 (2, payment_hash, option),
1464 (4, path, required_vec),
1465 (6, blinded_tail, option),
1467 Ok(Some(Event::PaymentPathSuccessful {
1468 payment_id: payment_id.0.unwrap(),
1470 path: Path { hops: path, blinded_tail },
1477 let mut payment_hash = PaymentHash([0; 32]);
1478 let mut payment_id = PaymentId([0; 32]);
1479 let mut reason = None;
1480 read_tlv_fields!(reader, {
1481 (0, payment_id, required),
1482 (1, reason, upgradable_option),
1483 (2, payment_hash, required),
1485 Ok(Some(Event::PaymentFailed {
1494 // Value 17 is used for `Event::OpenChannelRequest`.
1499 let mut payment_hash = PaymentHash([0; 32]);
1500 let mut purpose = UpgradableRequired(None);
1501 let mut amount_msat = 0;
1502 let mut receiver_node_id = None;
1503 let mut htlcs: Option<Vec<ClaimedHTLC>> = Some(vec![]);
1504 let mut sender_intended_total_msat: Option<u64> = None;
1505 read_tlv_fields!(reader, {
1506 (0, payment_hash, required),
1507 (1, receiver_node_id, option),
1508 (2, purpose, upgradable_required),
1509 (4, amount_msat, required),
1510 (5, htlcs, optional_vec),
1511 (7, sender_intended_total_msat, option),
1513 Ok(Some(Event::PaymentClaimed {
1516 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1518 htlcs: htlcs.unwrap_or(vec![]),
1519 sender_intended_total_msat,
1526 _init_and_read_len_prefixed_tlv_fields!(reader, {
1527 (0, payment_id, required),
1528 (2, payment_hash, required),
1529 (4, path, required_vec),
1530 (6, blinded_tail, option),
1532 Ok(Some(Event::ProbeSuccessful {
1533 payment_id: payment_id.0.unwrap(),
1534 payment_hash: payment_hash.0.unwrap(),
1535 path: Path { hops: path, blinded_tail },
1542 _init_and_read_len_prefixed_tlv_fields!(reader, {
1543 (0, payment_id, required),
1544 (2, payment_hash, required),
1545 (4, path, required_vec),
1546 (6, short_channel_id, option),
1547 (8, blinded_tail, option),
1549 Ok(Some(Event::ProbeFailed {
1550 payment_id: payment_id.0.unwrap(),
1551 payment_hash: payment_hash.0.unwrap(),
1552 path: Path { hops: path, blinded_tail },
1560 let mut prev_channel_id = ChannelId::new_zero();
1561 let mut failed_next_destination_opt = UpgradableRequired(None);
1562 read_tlv_fields!(reader, {
1563 (0, prev_channel_id, required),
1564 (2, failed_next_destination_opt, upgradable_required),
1566 Ok(Some(Event::HTLCHandlingFailed {
1568 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1576 let mut channel_id = ChannelId::new_zero();
1577 let mut user_channel_id: u128 = 0;
1578 let mut counterparty_node_id = RequiredWrapper(None);
1579 let mut channel_type = RequiredWrapper(None);
1580 read_tlv_fields!(reader, {
1581 (0, channel_id, required),
1582 (2, user_channel_id, required),
1583 (4, counterparty_node_id, required),
1584 (6, channel_type, required),
1587 Ok(Some(Event::ChannelReady {
1590 counterparty_node_id: counterparty_node_id.0.unwrap(),
1591 channel_type: channel_type.0.unwrap()
1598 let mut channel_id = ChannelId::new_zero();
1599 let mut user_channel_id: u128 = 0;
1600 let mut former_temporary_channel_id = None;
1601 let mut counterparty_node_id = RequiredWrapper(None);
1602 let mut funding_txo = RequiredWrapper(None);
1603 read_tlv_fields!(reader, {
1604 (0, channel_id, required),
1605 (2, user_channel_id, required),
1606 (4, former_temporary_channel_id, required),
1607 (6, counterparty_node_id, required),
1608 (8, funding_txo, required),
1611 Ok(Some(Event::ChannelPending {
1614 former_temporary_channel_id,
1615 counterparty_node_id: counterparty_node_id.0.unwrap(),
1616 funding_txo: funding_txo.0.unwrap()
1623 _init_and_read_len_prefixed_tlv_fields!(reader, {
1624 (0, payment_id, required),
1626 Ok(Some(Event::InvoiceRequestFailed {
1627 payment_id: payment_id.0.unwrap(),
1632 // Note that we do not write a length-prefixed TLV for ConnectionNeeded events.
1634 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1635 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1637 x if x % 2 == 1 => {
1638 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1639 // which prefixes the whole thing with a length BigSize. Because the event is
1640 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1641 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1642 // exactly the number of bytes specified, ignoring them entirely.
1643 let tlv_len: BigSize = Readable::read(reader)?;
1644 FixedLengthReader::new(reader, tlv_len.0)
1645 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1648 _ => Err(msgs::DecodeError::InvalidValue)
1653 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1654 /// broadcast to most peers).
1655 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1656 #[derive(Clone, Debug)]
1657 #[cfg_attr(test, derive(PartialEq))]
1658 pub enum MessageSendEvent {
1659 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1660 /// message provided to the given peer.
1662 /// The node_id of the node which should receive this message
1664 /// The message which should be sent.
1665 msg: msgs::AcceptChannel,
1667 /// Used to indicate that we've accepted a V2 channel open and should send the accept_channel2
1668 /// message provided to the given peer.
1669 SendAcceptChannelV2 {
1670 /// The node_id of the node which should receive this message
1672 /// The message which should be sent.
1673 msg: msgs::AcceptChannelV2,
1675 /// Used to indicate that we've initiated a channel open and should send the open_channel
1676 /// message provided to the given peer.
1678 /// The node_id of the node which should receive this message
1680 /// The message which should be sent.
1681 msg: msgs::OpenChannel,
1683 /// Used to indicate that we've initiated a V2 channel open and should send the open_channel2
1684 /// message provided to the given peer.
1686 /// The node_id of the node which should receive this message
1688 /// The message which should be sent.
1689 msg: msgs::OpenChannelV2,
1691 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1692 SendFundingCreated {
1693 /// The node_id of the node which should receive this message
1695 /// The message which should be sent.
1696 msg: msgs::FundingCreated,
1698 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1700 /// The node_id of the node which should receive this message
1702 /// The message which should be sent.
1703 msg: msgs::FundingSigned,
1705 /// Used to indicate that a stfu message should be sent to the peer with the given node id.
1707 /// The node_id of the node which should receive this message
1709 /// The message which should be sent.
1712 /// Used to indicate that a splice message should be sent to the peer with the given node id.
1714 /// The node_id of the node which should receive this message
1716 /// The message which should be sent.
1719 /// Used to indicate that a splice_ack message should be sent to the peer with the given node id.
1721 /// The node_id of the node which should receive this message
1723 /// The message which should be sent.
1724 msg: msgs::SpliceAck,
1726 /// Used to indicate that a splice_locked message should be sent to the peer with the given node id.
1728 /// The node_id of the node which should receive this message
1730 /// The message which should be sent.
1731 msg: msgs::SpliceLocked,
1733 /// Used to indicate that a tx_add_input message should be sent to the peer with the given node_id.
1735 /// The node_id of the node which should receive this message
1737 /// The message which should be sent.
1738 msg: msgs::TxAddInput,
1740 /// Used to indicate that a tx_add_output message should be sent to the peer with the given node_id.
1742 /// The node_id of the node which should receive this message
1744 /// The message which should be sent.
1745 msg: msgs::TxAddOutput,
1747 /// Used to indicate that a tx_remove_input message should be sent to the peer with the given node_id.
1749 /// The node_id of the node which should receive this message
1751 /// The message which should be sent.
1752 msg: msgs::TxRemoveInput,
1754 /// Used to indicate that a tx_remove_output message should be sent to the peer with the given node_id.
1755 SendTxRemoveOutput {
1756 /// The node_id of the node which should receive this message
1758 /// The message which should be sent.
1759 msg: msgs::TxRemoveOutput,
1761 /// Used to indicate that a tx_complete message should be sent to the peer with the given node_id.
1763 /// The node_id of the node which should receive this message
1765 /// The message which should be sent.
1766 msg: msgs::TxComplete,
1768 /// Used to indicate that a tx_signatures message should be sent to the peer with the given node_id.
1770 /// The node_id of the node which should receive this message
1772 /// The message which should be sent.
1773 msg: msgs::TxSignatures,
1775 /// Used to indicate that a tx_init_rbf message should be sent to the peer with the given node_id.
1777 /// The node_id of the node which should receive this message
1779 /// The message which should be sent.
1780 msg: msgs::TxInitRbf,
1782 /// Used to indicate that a tx_ack_rbf message should be sent to the peer with the given node_id.
1784 /// The node_id of the node which should receive this message
1786 /// The message which should be sent.
1787 msg: msgs::TxAckRbf,
1789 /// Used to indicate that a tx_abort message should be sent to the peer with the given node_id.
1791 /// The node_id of the node which should receive this message
1793 /// The message which should be sent.
1796 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1798 /// The node_id of the node which should receive these message(s)
1800 /// The channel_ready message which should be sent.
1801 msg: msgs::ChannelReady,
1803 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1804 SendAnnouncementSignatures {
1805 /// The node_id of the node which should receive these message(s)
1807 /// The announcement_signatures message which should be sent.
1808 msg: msgs::AnnouncementSignatures,
1810 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1811 /// message should be sent to the peer with the given node_id.
1813 /// The node_id of the node which should receive these message(s)
1815 /// The update messages which should be sent. ALL messages in the struct should be sent!
1816 updates: msgs::CommitmentUpdate,
1818 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1820 /// The node_id of the node which should receive this message
1822 /// The message which should be sent.
1823 msg: msgs::RevokeAndACK,
1825 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1827 /// The node_id of the node which should receive this message
1829 /// The message which should be sent.
1830 msg: msgs::ClosingSigned,
1832 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1834 /// The node_id of the node which should receive this message
1836 /// The message which should be sent.
1837 msg: msgs::Shutdown,
1839 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1840 SendChannelReestablish {
1841 /// The node_id of the node which should receive this message
1843 /// The message which should be sent.
1844 msg: msgs::ChannelReestablish,
1846 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1847 /// initial connection to ensure our peers know about our channels.
1848 SendChannelAnnouncement {
1849 /// The node_id of the node which should receive this message
1851 /// The channel_announcement which should be sent.
1852 msg: msgs::ChannelAnnouncement,
1853 /// The followup channel_update which should be sent.
1854 update_msg: msgs::ChannelUpdate,
1856 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1857 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1859 /// Note that after doing so, you very likely (unless you did so very recently) want to
1860 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1861 /// ensures that any nodes which see our channel_announcement also have a relevant
1862 /// node_announcement, including relevant feature flags which may be important for routing
1863 /// through or to us.
1865 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1866 BroadcastChannelAnnouncement {
1867 /// The channel_announcement which should be sent.
1868 msg: msgs::ChannelAnnouncement,
1869 /// The followup channel_update which should be sent.
1870 update_msg: Option<msgs::ChannelUpdate>,
1872 /// Used to indicate that a channel_update should be broadcast to all peers.
1873 BroadcastChannelUpdate {
1874 /// The channel_update which should be sent.
1875 msg: msgs::ChannelUpdate,
1877 /// Used to indicate that a node_announcement should be broadcast to all peers.
1878 BroadcastNodeAnnouncement {
1879 /// The node_announcement which should be sent.
1880 msg: msgs::NodeAnnouncement,
1882 /// Used to indicate that a channel_update should be sent to a single peer.
1883 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1884 /// private channel and we shouldn't be informing all of our peers of channel parameters.
1886 /// The node_id of the node which should receive this message
1888 /// The channel_update which should be sent.
1889 msg: msgs::ChannelUpdate,
1891 /// Broadcast an error downstream to be handled
1893 /// The node_id of the node which should receive this message
1895 /// The action which should be taken.
1896 action: msgs::ErrorAction
1898 /// Query a peer for channels with funding transaction UTXOs in a block range.
1899 SendChannelRangeQuery {
1900 /// The node_id of this message recipient
1902 /// The query_channel_range which should be sent.
1903 msg: msgs::QueryChannelRange,
1905 /// Request routing gossip messages from a peer for a list of channels identified by
1906 /// their short_channel_ids.
1908 /// The node_id of this message recipient
1910 /// The query_short_channel_ids which should be sent.
1911 msg: msgs::QueryShortChannelIds,
1913 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1914 /// emitted during processing of the query.
1915 SendReplyChannelRange {
1916 /// The node_id of this message recipient
1918 /// The reply_channel_range which should be sent.
1919 msg: msgs::ReplyChannelRange,
1921 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1922 /// enable receiving gossip messages from the peer.
1923 SendGossipTimestampFilter {
1924 /// The node_id of this message recipient
1926 /// The gossip_timestamp_filter which should be sent.
1927 msg: msgs::GossipTimestampFilter,
1931 /// A trait indicating an object may generate message send events
1932 pub trait MessageSendEventsProvider {
1933 /// Gets the list of pending events which were generated by previous actions, clearing the list
1935 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1938 /// A trait indicating an object may generate events.
1940 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1942 /// Implementations of this trait may also feature an async version of event handling, as shown with
1943 /// [`ChannelManager::process_pending_events_async`] and
1944 /// [`ChainMonitor::process_pending_events_async`].
1948 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1949 /// event since the last invocation.
1951 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1952 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1953 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1954 /// relevant changes to disk *before* returning.
1956 /// Further, because an application may crash between an [`Event`] being handled and the
1957 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1958 /// effect, [`Event`]s may be replayed.
1960 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1961 /// consult the provider's documentation on the implication of processing events and how a handler
1962 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1963 /// [`ChainMonitor::process_pending_events`]).
1965 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1968 /// [`process_pending_events`]: Self::process_pending_events
1969 /// [`handle_event`]: EventHandler::handle_event
1970 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1971 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1972 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
1973 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
1974 pub trait EventsProvider {
1975 /// Processes any events generated since the last call using the given event handler.
1977 /// See the trait-level documentation for requirements.
1978 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1981 /// A trait implemented for objects handling events from [`EventsProvider`].
1983 /// An async variation also exists for implementations of [`EventsProvider`] that support async
1984 /// event handling. The async event handler should satisfy the generic bounds: `F:
1985 /// core::future::Future, H: Fn(Event) -> F`.
1986 pub trait EventHandler {
1987 /// Handles the given [`Event`].
1989 /// See [`EventsProvider`] for details that must be considered when implementing this method.
1990 fn handle_event(&self, event: Event);
1993 impl<F> EventHandler for F where F: Fn(Event) {
1994 fn handle_event(&self, event: Event) {
1999 impl<T: EventHandler> EventHandler for Arc<T> {
2000 fn handle_event(&self, event: Event) {
2001 self.deref().handle_event(event)