1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Events are returned from various bits in the library which indicate some action must be taken
13 //! Because we don't have a built-in runtime, it's up to the client to call events at a time in the
14 //! future, as well as generate and broadcast funding transactions handle payment preimages and a
17 pub mod bump_transaction;
19 pub use bump_transaction::BumpTransactionEvent;
21 use crate::sign::SpendableOutputDescriptor;
22 use crate::ln::channelmanager::{InterceptId, PaymentId, RecipientOnionFields};
23 use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
24 use crate::ln::features::ChannelTypeFeatures;
26 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
27 use crate::routing::gossip::NetworkUpdate;
28 use crate::util::errors::APIError;
29 use crate::util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, RequiredWrapper, UpgradableRequired, WithoutLength};
30 use crate::util::string::UntrustedString;
31 use crate::routing::router::{BlindedTail, Path, RouteHop, RouteParameters};
33 use bitcoin::{PackedLockTime, Transaction, OutPoint};
34 use bitcoin::blockdata::script::Script;
35 use bitcoin::hashes::Hash;
36 use bitcoin::hashes::sha256::Hash as Sha256;
37 use bitcoin::secp256k1::PublicKey;
39 use crate::prelude::*;
40 use core::time::Duration;
44 /// Some information provided on receipt of payment depends on whether the payment received is a
45 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
46 #[derive(Clone, Debug, PartialEq, Eq)]
47 pub enum PaymentPurpose {
48 /// Information for receiving a payment that we generated an invoice for.
50 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
51 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
52 /// [`ChannelManager::claim_funds`].
54 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
55 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
56 payment_preimage: Option<PaymentPreimage>,
57 /// The "payment secret". This authenticates the sender to the recipient, preventing a
58 /// number of deanonymization attacks during the routing process.
59 /// It is provided here for your reference, however its accuracy is enforced directly by
60 /// [`ChannelManager`] using the values you previously provided to
61 /// [`ChannelManager::create_inbound_payment`] or
62 /// [`ChannelManager::create_inbound_payment_for_hash`].
64 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
65 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
66 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
67 payment_secret: PaymentSecret,
69 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
70 /// (the payee) providing a preimage.
71 SpontaneousPayment(PaymentPreimage),
74 impl_writeable_tlv_based_enum!(PaymentPurpose,
75 (0, InvoicePayment) => {
76 (0, payment_preimage, option),
77 (2, payment_secret, required),
79 (2, SpontaneousPayment)
82 /// Information about an HTLC that is part of a payment that can be claimed.
83 #[derive(Clone, Debug, PartialEq, Eq)]
84 pub struct ClaimedHTLC {
85 /// The `channel_id` of the channel over which the HTLC was received.
86 pub channel_id: [u8; 32],
87 /// The `user_channel_id` of the channel over which the HTLC was received. This is the value
88 /// passed in to [`ChannelManager::create_channel`] for outbound channels, or to
89 /// [`ChannelManager::accept_inbound_channel`] for inbound channels if
90 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
91 /// `user_channel_id` will be randomized for an inbound channel.
93 /// This field will be zero for a payment that was serialized prior to LDK version 0.0.117. (This
94 /// should only happen in the case that a payment was claimable prior to LDK version 0.0.117, but
95 /// was not actually claimed until after upgrading.)
97 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
98 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
99 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
100 pub user_channel_id: u128,
101 /// The block height at which this HTLC expires.
102 pub cltv_expiry: u32,
103 /// The amount (in msats) of this part of an MPP.
106 impl_writeable_tlv_based!(ClaimedHTLC, {
107 (0, channel_id, required),
108 (2, user_channel_id, required),
109 (4, cltv_expiry, required),
110 (6, value_msat, required),
113 /// When the payment path failure took place and extra details about it. [`PathFailure::OnPath`] may
114 /// contain a [`NetworkUpdate`] that needs to be applied to the [`NetworkGraph`].
116 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
117 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
118 #[derive(Clone, Debug, Eq, PartialEq)]
119 pub enum PathFailure {
120 /// We failed to initially send the payment and no HTLC was committed to. Contains the relevant
123 /// The error surfaced from initial send.
126 /// A hop on the path failed to forward our payment.
128 /// If present, this [`NetworkUpdate`] should be applied to the [`NetworkGraph`] so that routing
129 /// decisions can take into account the update.
131 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
132 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
133 network_update: Option<NetworkUpdate>,
137 impl_writeable_tlv_based_enum_upgradable!(PathFailure,
139 (0, network_update, upgradable_option),
141 (2, InitialSend) => {
142 (0, err, upgradable_required),
146 #[derive(Clone, Debug, PartialEq, Eq)]
147 /// The reason the channel was closed. See individual variants for more details.
148 pub enum ClosureReason {
149 /// Closure generated from receiving a peer error message.
151 /// Our counterparty may have broadcasted their latest commitment state, and we have
153 CounterpartyForceClosed {
154 /// The error which the peer sent us.
156 /// Be careful about printing the peer_msg, a well-crafted message could exploit
157 /// a security vulnerability in the terminal emulator or the logging subsystem.
158 /// To be safe, use `Display` on `UntrustedString`
160 /// [`UntrustedString`]: crate::util::string::UntrustedString
161 peer_msg: UntrustedString,
163 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
165 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
167 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
168 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
169 //TODO: split between CounterpartyInitiated/LocallyInitiated
171 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
172 /// commitment transaction came from our counterparty, but it may also have come from
173 /// a copy of our own `ChannelMonitor`.
174 CommitmentTxConfirmed,
175 /// The funding transaction failed to confirm in a timely manner on an inbound channel.
177 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
179 /// A developer-readable error message which we generated.
182 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
183 /// forget the channel entirely - we can attempt again if the peer reconnects.
185 /// This includes cases where we restarted prior to funding completion, including prior to the
186 /// initial [`ChannelMonitor`] persistence completing.
188 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
189 /// peer because of mutual incompatibility between us and our channel counterparty.
191 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
193 /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
194 /// the [`ChannelManager`] deserialized.
196 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
197 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
198 OutdatedChannelManager,
199 /// The counterparty requested a cooperative close of a channel that had not been funded yet.
200 /// The channel has been immediately closed.
201 CounterpartyCoopClosedUnfundedChannel,
204 impl core::fmt::Display for ClosureReason {
205 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
206 f.write_str("Channel closed because ")?;
208 ClosureReason::CounterpartyForceClosed { peer_msg } => {
209 f.write_fmt(format_args!("counterparty force-closed with message: {}", peer_msg))
211 ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
212 ClosureReason::CooperativeClosure => f.write_str("the channel was cooperatively closed"),
213 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
214 ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
215 ClosureReason::ProcessingError { err } => {
216 f.write_str("of an exception: ")?;
219 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
220 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
221 ClosureReason::CounterpartyCoopClosedUnfundedChannel => f.write_str("the peer requested the unfunded channel be closed"),
226 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
227 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
228 (1, FundingTimedOut) => {},
229 (2, HolderForceClosed) => {},
230 (6, CommitmentTxConfirmed) => {},
231 (4, CooperativeClosure) => {},
232 (8, ProcessingError) => { (1, err, required) },
233 (10, DisconnectedPeer) => {},
234 (12, OutdatedChannelManager) => {},
235 (13, CounterpartyCoopClosedUnfundedChannel) => {},
238 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
239 #[derive(Clone, Debug, PartialEq, Eq)]
240 pub enum HTLCDestination {
241 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
242 /// there is insufficient capacity in our outbound channel.
244 /// The `node_id` of the next node. For backwards compatibility, this field is
245 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
246 /// counterparty node information.
247 node_id: Option<PublicKey>,
248 /// The outgoing `channel_id` between us and the next node.
249 channel_id: [u8; 32],
251 /// Scenario where we are unsure of the next node to forward the HTLC to.
253 /// Short channel id we are requesting to forward an HTLC to.
254 requested_forward_scid: u64,
256 /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
259 /// Short channel id we are requesting to forward an HTLC to.
260 requested_forward_scid: u64
262 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
263 /// but is invalid for some reason, so we reject it.
265 /// Some of the reasons may include:
267 /// * Excess HTLCs for a payment that we have already fully received, over-paying for the
269 /// * The counterparty node modified the HTLC in transit,
270 /// * A probing attack where an intermediary node is trying to detect if we are the ultimate
271 /// recipient for a payment.
273 /// The payment hash of the payment we attempted to process.
274 payment_hash: PaymentHash
278 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
279 (0, NextHopChannel) => {
280 (0, node_id, required),
281 (2, channel_id, required),
283 (1, InvalidForward) => {
284 (0, requested_forward_scid, required),
286 (2, UnknownNextHop) => {
287 (0, requested_forward_scid, required),
289 (4, FailedPayment) => {
290 (0, payment_hash, required),
294 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
295 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
296 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
297 /// intercepts in upcoming work.
298 enum InterceptNextHop {
300 requested_next_hop_scid: u64,
304 impl_writeable_tlv_based_enum!(InterceptNextHop,
306 (0, requested_next_hop_scid, required),
310 /// The reason the payment failed. Used in [`Event::PaymentFailed`].
311 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
312 pub enum PaymentFailureReason {
313 /// The intended recipient rejected our payment.
315 /// The user chose to abandon this payment by calling [`ChannelManager::abandon_payment`].
317 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
319 /// We exhausted all of our retry attempts while trying to send the payment, or we
320 /// exhausted the [`Retry::Timeout`] if the user set one. If at any point a retry
321 /// attempt failed while being forwarded along the path, an [`Event::PaymentPathFailed`] will
322 /// have come before this.
324 /// [`Retry::Timeout`]: crate::ln::channelmanager::Retry::Timeout
326 /// The payment expired while retrying, based on the provided
327 /// [`PaymentParameters::expiry_time`].
329 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
331 /// We failed to find a route while retrying the payment.
333 /// This error should generally never happen. This likely means that there is a problem with
338 impl_writeable_tlv_based_enum!(PaymentFailureReason,
339 (0, RecipientRejected) => {},
340 (2, UserAbandoned) => {},
341 (4, RetriesExhausted) => {},
342 (6, PaymentExpired) => {},
343 (8, RouteNotFound) => {},
344 (10, UnexpectedError) => {}, ;
347 /// An Event which you should probably take some action in response to.
349 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
350 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
351 /// written as it makes no sense to respond to it after reconnecting to peers).
352 #[derive(Clone, Debug, PartialEq, Eq)]
354 /// Used to indicate that the client should generate a funding transaction with the given
355 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
356 /// Generated in [`ChannelManager`] message handling.
357 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
358 /// counterparty can steal your funds!
360 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
361 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
362 FundingGenerationReady {
363 /// The random channel_id we picked which you'll need to pass into
364 /// [`ChannelManager::funding_transaction_generated`].
366 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
367 temporary_channel_id: [u8; 32],
368 /// The counterparty's node_id, which you'll need to pass back into
369 /// [`ChannelManager::funding_transaction_generated`].
371 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
372 counterparty_node_id: PublicKey,
373 /// The value, in satoshis, that the output should have.
374 channel_value_satoshis: u64,
375 /// The script which should be used in the transaction output.
376 output_script: Script,
377 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
378 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
379 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
380 /// `user_channel_id` will be randomized for an inbound channel. This may be zero for objects
381 /// serialized with LDK versions prior to 0.0.113.
383 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
384 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
385 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
386 user_channel_id: u128,
388 /// Indicates that we've been offered a payment and it needs to be claimed via calling
389 /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
391 /// Note that if the preimage is not known, you should call
392 /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
393 /// to free up resources for this HTLC and avoid network congestion.
395 /// If [`Event::PaymentClaimable::onion_fields`] is `Some`, and includes custom TLVs with even type
396 /// numbers, you should use [`ChannelManager::fail_htlc_backwards_with_reason`] with
397 /// [`FailureCode::InvalidOnionPayload`] if you fail to understand and handle the contents, or
398 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`] upon successful handling.
399 /// If you don't intend to check for custom TLVs, you can simply use
400 /// [`ChannelManager::claim_funds`], which will automatically fail back even custom TLVs.
402 /// If you fail to call [`ChannelManager::claim_funds`],
403 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`],
404 /// [`ChannelManager::fail_htlc_backwards`], or
405 /// [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will
406 /// be automatically failed.
409 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
410 /// `PaymentClaimable` events may be generated for the same payment. In such a case it is
411 /// polite (and required in the lightning specification) to fail the payment the second time
412 /// and give the sender their money back rather than accepting double payment.
415 /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
417 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
418 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`]: crate::ln::channelmanager::ChannelManager::claim_funds_with_known_custom_tlvs
419 /// [`FailureCode::InvalidOnionPayload`]: crate::ln::channelmanager::FailureCode::InvalidOnionPayload
420 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
421 /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
423 /// The node that will receive the payment after it has been claimed.
424 /// This is useful to identify payments received via [phantom nodes].
425 /// This field will always be filled in when the event was generated by LDK versions
426 /// 0.0.113 and above.
428 /// [phantom nodes]: crate::sign::PhantomKeysManager
429 receiver_node_id: Option<PublicKey>,
430 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
431 /// not stop you from registering duplicate payment hashes for inbound payments.
432 payment_hash: PaymentHash,
433 /// The fields in the onion which were received with each HTLC. Only fields which were
434 /// identical in each HTLC involved in the payment will be included here.
436 /// Payments received on LDK versions prior to 0.0.115 will have this field unset.
437 onion_fields: Option<RecipientOnionFields>,
438 /// The value, in thousandths of a satoshi, that this payment is claimable for. May be greater
439 /// than the invoice amount.
441 /// May be less than the invoice amount if [`ChannelConfig::accept_underpaying_htlcs`] is set
442 /// and the previous hop took an extra fee.
445 /// If [`ChannelConfig::accept_underpaying_htlcs`] is set and you claim without verifying this
446 /// field, you may lose money!
448 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
450 /// The value, in thousands of a satoshi, that was skimmed off of this payment as an extra fee
451 /// taken by our channel counterparty.
453 /// Will always be 0 unless [`ChannelConfig::accept_underpaying_htlcs`] is set.
455 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
456 counterparty_skimmed_fee_msat: u64,
457 /// Information for claiming this received payment, based on whether the purpose of the
458 /// payment is to pay an invoice or to send a spontaneous payment.
459 purpose: PaymentPurpose,
460 /// The `channel_id` indicating over which channel we received the payment.
461 via_channel_id: Option<[u8; 32]>,
462 /// The `user_channel_id` indicating over which channel we received the payment.
463 via_user_channel_id: Option<u128>,
464 /// The block height at which this payment will be failed back and will no longer be
465 /// eligible for claiming.
467 /// Prior to this height, a call to [`ChannelManager::claim_funds`] is guaranteed to
468 /// succeed, however you should wait for [`Event::PaymentClaimed`] to be sure.
470 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
471 claim_deadline: Option<u32>,
473 /// Indicates a payment has been claimed and we've received money!
475 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
476 /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
477 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
478 /// [`Event::PaymentClaimable`] event.
481 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
482 /// `PaymentClaimable` events may be generated for the same payment. If you then call
483 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
484 /// multiple `PaymentClaimed` events.
486 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
488 /// The node that received the payment.
489 /// This is useful to identify payments which were received via [phantom nodes].
490 /// This field will always be filled in when the event was generated by LDK versions
491 /// 0.0.113 and above.
493 /// [phantom nodes]: crate::sign::PhantomKeysManager
494 receiver_node_id: Option<PublicKey>,
495 /// The payment hash of the claimed payment. Note that LDK will not stop you from
496 /// registering duplicate payment hashes for inbound payments.
497 payment_hash: PaymentHash,
498 /// The value, in thousandths of a satoshi, that this payment is for. May be greater than the
501 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
502 /// spontaneous payment.
503 purpose: PaymentPurpose,
504 /// The HTLCs that comprise the claimed payment. This will be empty for events serialized prior
505 /// to LDK version 0.0.117.
506 htlcs: Vec<ClaimedHTLC>,
507 /// The sender-intended sum total of all the MPP parts. This will be `None` for events
508 /// serialized prior to LDK version 0.0.117.
509 sender_intended_total_msat: Option<u64>,
511 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
512 /// and we got back the payment preimage for it).
514 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
515 /// event. In this situation, you SHOULD treat this payment as having succeeded.
517 /// The `payment_id` passed to [`ChannelManager::send_payment`].
519 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
520 payment_id: Option<PaymentId>,
521 /// The preimage to the hash given to ChannelManager::send_payment.
522 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
523 /// store it somehow!
524 payment_preimage: PaymentPreimage,
525 /// The hash that was given to [`ChannelManager::send_payment`].
527 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
528 payment_hash: PaymentHash,
529 /// The total fee which was spent at intermediate hops in this payment, across all paths.
531 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
532 /// overpayment to the recipient node.
534 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
535 /// overstate the amount paid, though this is unlikely.
537 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
538 fee_paid_msat: Option<u64>,
540 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
541 /// provide failure information for each path attempt in the payment, including retries.
543 /// This event is provided once there are no further pending HTLCs for the payment and the
544 /// payment is no longer retryable, due either to the [`Retry`] provided or
545 /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
547 /// In exceedingly rare cases, it is possible that an [`Event::PaymentFailed`] is generated for
548 /// a payment after an [`Event::PaymentSent`] event for this same payment has already been
549 /// received and processed. In this case, the [`Event::PaymentFailed`] event MUST be ignored,
550 /// and the payment MUST be treated as having succeeded.
552 /// [`Retry`]: crate::ln::channelmanager::Retry
553 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
555 /// The `payment_id` passed to [`ChannelManager::send_payment`].
557 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
558 payment_id: PaymentId,
559 /// The hash that was given to [`ChannelManager::send_payment`].
561 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
562 payment_hash: PaymentHash,
563 /// The reason the payment failed. This is only `None` for events generated or serialized
564 /// by versions prior to 0.0.115.
565 reason: Option<PaymentFailureReason>,
567 /// Indicates that a path for an outbound payment was successful.
569 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
570 /// [`Event::PaymentSent`] for obtaining the payment preimage.
571 PaymentPathSuccessful {
572 /// The `payment_id` passed to [`ChannelManager::send_payment`].
574 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
575 payment_id: PaymentId,
576 /// The hash that was given to [`ChannelManager::send_payment`].
578 /// This will be `Some` for all payments which completed on LDK 0.0.104 or later.
580 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
581 payment_hash: Option<PaymentHash>,
582 /// The payment path that was successful.
584 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
587 /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
590 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
591 /// [`Event::PaymentFailed`].
593 /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
596 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
598 /// The `payment_id` passed to [`ChannelManager::send_payment`].
600 /// This will be `Some` for all payment paths which failed on LDK 0.0.103 or later.
602 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
603 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
604 payment_id: Option<PaymentId>,
605 /// The hash that was given to [`ChannelManager::send_payment`].
607 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
608 payment_hash: PaymentHash,
609 /// Indicates the payment was rejected for some reason by the recipient. This implies that
610 /// the payment has failed, not just the route in question. If this is not set, the payment may
611 /// be retried via a different route.
612 payment_failed_permanently: bool,
613 /// Extra error details based on the failure type. May contain an update that needs to be
614 /// applied to the [`NetworkGraph`].
616 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
617 failure: PathFailure,
618 /// The payment path that failed.
620 /// The channel responsible for the failed payment path.
622 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
623 /// may not refer to a channel in the public network graph. These aliases may also collide
624 /// with channels in the public network graph.
626 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
627 /// retried. May be `None` for older [`Event`] serializations.
628 short_channel_id: Option<u64>,
630 error_code: Option<u16>,
632 error_data: Option<Vec<u8>>,
634 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
636 /// The id returned by [`ChannelManager::send_probe`].
638 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
639 payment_id: PaymentId,
640 /// The hash generated by [`ChannelManager::send_probe`].
642 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
643 payment_hash: PaymentHash,
644 /// The payment path that was successful.
647 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
649 /// The id returned by [`ChannelManager::send_probe`].
651 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
652 payment_id: PaymentId,
653 /// The hash generated by [`ChannelManager::send_probe`].
655 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
656 payment_hash: PaymentHash,
657 /// The payment path that failed.
659 /// The channel responsible for the failed probe.
661 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
662 /// may not refer to a channel in the public network graph. These aliases may also collide
663 /// with channels in the public network graph.
664 short_channel_id: Option<u64>,
666 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
667 /// a time in the future.
669 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
670 PendingHTLCsForwardable {
671 /// The minimum amount of time that should be waited prior to calling
672 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
673 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
674 /// now + 5*time_forwardable).
675 time_forwardable: Duration,
677 /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
678 /// you've encoded an intercept scid in the receiver's invoice route hints using
679 /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
681 /// [`ChannelManager::forward_intercepted_htlc`] or
682 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
683 /// their docs for more information.
685 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
686 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
687 /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
688 /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
690 /// An id to help LDK identify which HTLC is being forwarded or failed.
691 intercept_id: InterceptId,
692 /// The fake scid that was programmed as the next hop's scid, generated using
693 /// [`ChannelManager::get_intercept_scid`].
695 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
696 requested_next_hop_scid: u64,
697 /// The payment hash used for this HTLC.
698 payment_hash: PaymentHash,
699 /// How many msats were received on the inbound edge of this HTLC.
700 inbound_amount_msat: u64,
701 /// How many msats the payer intended to route to the next node. Depending on the reason you are
702 /// intercepting this payment, you might take a fee by forwarding less than this amount.
703 /// Forwarding less than this amount may break compatibility with LDK versions prior to 0.0.116.
705 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
706 /// check that whatever fee you want has been included here or subtract it as required. Further,
707 /// LDK will not stop you from forwarding more than you received.
708 expected_outbound_amount_msat: u64,
710 /// Used to indicate that an output which you should know how to spend was confirmed on chain
711 /// and is now spendable.
712 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
713 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
714 /// somewhere and spend them when you create on-chain transactions.
716 /// The outputs which you should store as spendable by you.
717 outputs: Vec<SpendableOutputDescriptor>,
719 /// This event is generated when a payment has been successfully forwarded through us and a
720 /// forwarding fee earned.
722 /// The incoming channel between the previous node and us. This is only `None` for events
723 /// generated or serialized by versions prior to 0.0.107.
724 prev_channel_id: Option<[u8; 32]>,
725 /// The outgoing channel between the next node and us. This is only `None` for events
726 /// generated or serialized by versions prior to 0.0.107.
727 next_channel_id: Option<[u8; 32]>,
728 /// The fee, in milli-satoshis, which was earned as a result of the payment.
730 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
731 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
732 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
733 /// claimed the full value in millisatoshis from the source. In this case,
734 /// `claim_from_onchain_tx` will be set.
736 /// If the channel which sent us the payment has been force-closed, we will claim the funds
737 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
738 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
739 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
741 fee_earned_msat: Option<u64>,
742 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
744 claim_from_onchain_tx: bool,
745 /// The final amount forwarded, in milli-satoshis, after the fee is deducted.
747 /// The caveat described above the `fee_earned_msat` field applies here as well.
748 outbound_amount_forwarded_msat: Option<u64>,
750 /// Used to indicate that a channel with the given `channel_id` is being opened and pending
751 /// confirmation on-chain.
753 /// This event is emitted when the funding transaction has been signed and is broadcast to the
754 /// network. For 0conf channels it will be immediately followed by the corresponding
755 /// [`Event::ChannelReady`] event.
757 /// The `channel_id` of the channel that is pending confirmation.
758 channel_id: [u8; 32],
759 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
760 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
761 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
762 /// `user_channel_id` will be randomized for an inbound channel.
764 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
765 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
766 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
767 user_channel_id: u128,
768 /// The `temporary_channel_id` this channel used to be known by during channel establishment.
770 /// Will be `None` for channels created prior to LDK version 0.0.115.
771 former_temporary_channel_id: Option<[u8; 32]>,
772 /// The `node_id` of the channel counterparty.
773 counterparty_node_id: PublicKey,
774 /// The outpoint of the channel's funding transaction.
775 funding_txo: OutPoint,
777 /// Used to indicate that a channel with the given `channel_id` is ready to
778 /// be used. This event is emitted either when the funding transaction has been confirmed
779 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
782 /// The `channel_id` of the channel that is ready.
783 channel_id: [u8; 32],
784 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
785 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
786 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
787 /// `user_channel_id` will be randomized for an inbound channel.
789 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
790 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
791 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
792 user_channel_id: u128,
793 /// The `node_id` of the channel counterparty.
794 counterparty_node_id: PublicKey,
795 /// The features that this channel will operate with.
796 channel_type: ChannelTypeFeatures,
798 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
799 /// process of closure.
801 /// Note that this event is only triggered for accepted channels: if the
802 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true and the channel is
803 /// rejected, no `ChannelClosed` event will be sent.
805 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
806 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
808 /// The `channel_id` of the channel which has been closed. Note that on-chain transactions
809 /// resolving the channel are likely still awaiting confirmation.
810 channel_id: [u8; 32],
811 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
812 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
813 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
814 /// `user_channel_id` will be randomized for inbound channels.
815 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
816 /// zero for objects serialized with LDK versions prior to 0.0.102.
818 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
819 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
820 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
821 user_channel_id: u128,
822 /// The reason the channel was closed.
823 reason: ClosureReason,
824 /// Counterparty in the closed channel.
826 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
827 counterparty_node_id: Option<PublicKey>,
828 /// Channel capacity of the closing channel (sats).
830 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
831 channel_capacity_sats: Option<u64>,
833 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
834 /// inputs for another purpose.
836 /// The channel_id of the channel which has been closed.
837 channel_id: [u8; 32],
838 /// The full transaction received from the user
839 transaction: Transaction
841 /// Indicates a request to open a new channel by a peer.
843 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the request,
844 /// call [`ChannelManager::force_close_without_broadcasting_txn`]. Note that a ['ChannelClosed`]
845 /// event will _not_ be triggered if the channel is rejected.
847 /// The event is only triggered when a new open channel request is received and the
848 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
850 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
851 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
852 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
854 /// The temporary channel ID of the channel requested to be opened.
856 /// When responding to the request, the `temporary_channel_id` should be passed
857 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
858 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
860 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
861 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
862 temporary_channel_id: [u8; 32],
863 /// The node_id of the counterparty requesting to open the channel.
865 /// When responding to the request, the `counterparty_node_id` should be passed
866 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
867 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
870 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
871 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
872 counterparty_node_id: PublicKey,
873 /// The channel value of the requested channel.
874 funding_satoshis: u64,
875 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
877 /// The features that this channel will operate with. If you reject the channel, a
878 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
881 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
882 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
885 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
886 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
887 /// 0.0.107. Channels setting this type also need to get manually accepted via
888 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
889 /// or will be rejected otherwise.
891 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
892 channel_type: ChannelTypeFeatures,
894 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
897 /// Some scenarios where this event may be sent include:
898 /// * Insufficient capacity in the outbound channel
899 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
900 /// * When an unknown SCID is requested for forwarding a payment.
901 /// * Expected MPP amount has already been reached
902 /// * The HTLC has timed out
904 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
905 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
907 /// The channel over which the HTLC was received.
908 prev_channel_id: [u8; 32],
909 /// Destination of the HTLC that failed to be processed.
910 failed_next_destination: HTLCDestination,
912 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
913 /// requires confirmed external funds to be readily available to spend.
915 /// LDK does not currently generate this event unless the
916 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`] config flag is set to true.
917 /// It is limited to the scope of channels with anchor outputs.
919 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`]: crate::util::config::ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx
920 BumpTransaction(BumpTransactionEvent),
923 impl Writeable for Event {
924 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
926 &Event::FundingGenerationReady { .. } => {
928 // We never write out FundingGenerationReady events as, upon disconnection, peers
929 // drop any channels which have not yet exchanged funding_signed.
931 &Event::PaymentClaimable { ref payment_hash, ref amount_msat, counterparty_skimmed_fee_msat,
932 ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id,
933 ref claim_deadline, ref onion_fields
936 let mut payment_secret = None;
937 let payment_preimage;
939 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
940 payment_secret = Some(secret);
941 payment_preimage = *preimage;
943 PaymentPurpose::SpontaneousPayment(preimage) => {
944 payment_preimage = Some(*preimage);
947 let skimmed_fee_opt = if counterparty_skimmed_fee_msat == 0 { None }
948 else { Some(counterparty_skimmed_fee_msat) };
949 write_tlv_fields!(writer, {
950 (0, payment_hash, required),
951 (1, receiver_node_id, option),
952 (2, payment_secret, option),
953 (3, via_channel_id, option),
954 (4, amount_msat, required),
955 (5, via_user_channel_id, option),
956 // Type 6 was `user_payment_id` on 0.0.103 and earlier
957 (7, claim_deadline, option),
958 (8, payment_preimage, option),
959 (9, onion_fields, option),
960 (10, skimmed_fee_opt, option),
963 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
965 write_tlv_fields!(writer, {
966 (0, payment_preimage, required),
967 (1, payment_hash, required),
968 (3, payment_id, option),
969 (5, fee_paid_msat, option),
972 &Event::PaymentPathFailed {
973 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
974 ref path, ref short_channel_id,
982 error_code.write(writer)?;
984 error_data.write(writer)?;
985 write_tlv_fields!(writer, {
986 (0, payment_hash, required),
987 (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
988 (2, payment_failed_permanently, required),
989 (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
990 (4, path.blinded_tail, option),
991 (5, path.hops, required_vec),
992 (7, short_channel_id, option),
993 (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
994 (11, payment_id, option),
995 (13, failure, required),
998 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
1000 // Note that we now ignore these on the read end as we'll re-generate them in
1001 // ChannelManager, we write them here only for backwards compatibility.
1003 &Event::SpendableOutputs { ref outputs } => {
1005 write_tlv_fields!(writer, {
1006 (0, WithoutLength(outputs), required),
1009 &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1011 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1012 write_tlv_fields!(writer, {
1013 (0, intercept_id, required),
1014 (2, intercept_scid, required),
1015 (4, payment_hash, required),
1016 (6, inbound_amount_msat, required),
1017 (8, expected_outbound_amount_msat, required),
1020 &Event::PaymentForwarded {
1021 fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
1022 next_channel_id, outbound_amount_forwarded_msat
1025 write_tlv_fields!(writer, {
1026 (0, fee_earned_msat, option),
1027 (1, prev_channel_id, option),
1028 (2, claim_from_onchain_tx, required),
1029 (3, next_channel_id, option),
1030 (5, outbound_amount_forwarded_msat, option),
1033 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason,
1034 ref counterparty_node_id, ref channel_capacity_sats
1037 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1038 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1039 // separate u64 values.
1040 let user_channel_id_low = *user_channel_id as u64;
1041 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1042 write_tlv_fields!(writer, {
1043 (0, channel_id, required),
1044 (1, user_channel_id_low, required),
1045 (2, reason, required),
1046 (3, user_channel_id_high, required),
1047 (5, counterparty_node_id, option),
1048 (7, channel_capacity_sats, option),
1051 &Event::DiscardFunding { ref channel_id, ref transaction } => {
1052 11u8.write(writer)?;
1053 write_tlv_fields!(writer, {
1054 (0, channel_id, required),
1055 (2, transaction, required)
1058 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1059 13u8.write(writer)?;
1060 write_tlv_fields!(writer, {
1061 (0, payment_id, required),
1062 (2, payment_hash, option),
1063 (4, path.hops, required_vec),
1064 (6, path.blinded_tail, option),
1067 &Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
1068 15u8.write(writer)?;
1069 write_tlv_fields!(writer, {
1070 (0, payment_id, required),
1071 (1, reason, option),
1072 (2, payment_hash, required),
1075 &Event::OpenChannelRequest { .. } => {
1076 17u8.write(writer)?;
1077 // We never write the OpenChannelRequest events as, upon disconnection, peers
1078 // drop any channels which have not yet exchanged funding_signed.
1080 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref htlcs, ref sender_intended_total_msat } => {
1081 19u8.write(writer)?;
1082 write_tlv_fields!(writer, {
1083 (0, payment_hash, required),
1084 (1, receiver_node_id, option),
1085 (2, purpose, required),
1086 (4, amount_msat, required),
1087 (5, *htlcs, optional_vec),
1088 (7, sender_intended_total_msat, option),
1091 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1092 21u8.write(writer)?;
1093 write_tlv_fields!(writer, {
1094 (0, payment_id, required),
1095 (2, payment_hash, required),
1096 (4, path.hops, required_vec),
1097 (6, path.blinded_tail, option),
1100 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1101 23u8.write(writer)?;
1102 write_tlv_fields!(writer, {
1103 (0, payment_id, required),
1104 (2, payment_hash, required),
1105 (4, path.hops, required_vec),
1106 (6, short_channel_id, option),
1107 (8, path.blinded_tail, option),
1110 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1111 25u8.write(writer)?;
1112 write_tlv_fields!(writer, {
1113 (0, prev_channel_id, required),
1114 (2, failed_next_destination, required),
1117 &Event::BumpTransaction(ref event)=> {
1118 27u8.write(writer)?;
1120 // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1121 // upon restarting anyway if they remain unresolved.
1122 BumpTransactionEvent::ChannelClose { .. } => {}
1123 BumpTransactionEvent::HTLCResolution { .. } => {}
1125 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1127 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1128 29u8.write(writer)?;
1129 write_tlv_fields!(writer, {
1130 (0, channel_id, required),
1131 (2, user_channel_id, required),
1132 (4, counterparty_node_id, required),
1133 (6, channel_type, required),
1136 &Event::ChannelPending { ref channel_id, ref user_channel_id, ref former_temporary_channel_id, ref counterparty_node_id, ref funding_txo } => {
1137 31u8.write(writer)?;
1138 write_tlv_fields!(writer, {
1139 (0, channel_id, required),
1140 (2, user_channel_id, required),
1141 (4, former_temporary_channel_id, required),
1142 (6, counterparty_node_id, required),
1143 (8, funding_txo, required),
1146 // Note that, going forward, all new events must only write data inside of
1147 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1148 // data via `write_tlv_fields`.
1153 impl MaybeReadable for Event {
1154 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1155 match Readable::read(reader)? {
1156 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
1157 // unlike all other events, thus we return immediately here.
1161 let mut payment_hash = PaymentHash([0; 32]);
1162 let mut payment_preimage = None;
1163 let mut payment_secret = None;
1164 let mut amount_msat = 0;
1165 let mut counterparty_skimmed_fee_msat_opt = None;
1166 let mut receiver_node_id = None;
1167 let mut _user_payment_id = None::<u64>; // Used in 0.0.103 and earlier, no longer written in 0.0.116+.
1168 let mut via_channel_id = None;
1169 let mut claim_deadline = None;
1170 let mut via_user_channel_id = None;
1171 let mut onion_fields = None;
1172 read_tlv_fields!(reader, {
1173 (0, payment_hash, required),
1174 (1, receiver_node_id, option),
1175 (2, payment_secret, option),
1176 (3, via_channel_id, option),
1177 (4, amount_msat, required),
1178 (5, via_user_channel_id, option),
1179 (6, _user_payment_id, option),
1180 (7, claim_deadline, option),
1181 (8, payment_preimage, option),
1182 (9, onion_fields, option),
1183 (10, counterparty_skimmed_fee_msat_opt, option),
1185 let purpose = match payment_secret {
1186 Some(secret) => PaymentPurpose::InvoicePayment {
1188 payment_secret: secret
1190 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1191 None => return Err(msgs::DecodeError::InvalidValue),
1193 Ok(Some(Event::PaymentClaimable {
1197 counterparty_skimmed_fee_msat: counterparty_skimmed_fee_msat_opt.unwrap_or(0),
1200 via_user_channel_id,
1209 let mut payment_preimage = PaymentPreimage([0; 32]);
1210 let mut payment_hash = None;
1211 let mut payment_id = None;
1212 let mut fee_paid_msat = None;
1213 read_tlv_fields!(reader, {
1214 (0, payment_preimage, required),
1215 (1, payment_hash, option),
1216 (3, payment_id, option),
1217 (5, fee_paid_msat, option),
1219 if payment_hash.is_none() {
1220 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
1222 Ok(Some(Event::PaymentSent {
1225 payment_hash: payment_hash.unwrap(),
1234 let error_code = Readable::read(reader)?;
1236 let error_data = Readable::read(reader)?;
1237 let mut payment_hash = PaymentHash([0; 32]);
1238 let mut payment_failed_permanently = false;
1239 let mut network_update = None;
1240 let mut blinded_tail: Option<BlindedTail> = None;
1241 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1242 let mut short_channel_id = None;
1243 let mut payment_id = None;
1244 let mut failure_opt = None;
1245 read_tlv_fields!(reader, {
1246 (0, payment_hash, required),
1247 (1, network_update, upgradable_option),
1248 (2, payment_failed_permanently, required),
1249 (4, blinded_tail, option),
1250 // Added as a part of LDK 0.0.101 and always filled in since.
1251 // Defaults to an empty Vec, though likely should have been `Option`al.
1252 (5, path, optional_vec),
1253 (7, short_channel_id, option),
1254 (11, payment_id, option),
1255 (13, failure_opt, upgradable_option),
1257 let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1258 Ok(Some(Event::PaymentPathFailed {
1261 payment_failed_permanently,
1263 path: Path { hops: path.unwrap(), blinded_tail },
1276 let mut outputs = WithoutLength(Vec::new());
1277 read_tlv_fields!(reader, {
1278 (0, outputs, required),
1280 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
1285 let mut payment_hash = PaymentHash([0; 32]);
1286 let mut intercept_id = InterceptId([0; 32]);
1287 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1288 let mut inbound_amount_msat = 0;
1289 let mut expected_outbound_amount_msat = 0;
1290 read_tlv_fields!(reader, {
1291 (0, intercept_id, required),
1292 (2, requested_next_hop_scid, required),
1293 (4, payment_hash, required),
1294 (6, inbound_amount_msat, required),
1295 (8, expected_outbound_amount_msat, required),
1297 let next_scid = match requested_next_hop_scid {
1298 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1300 Ok(Some(Event::HTLCIntercepted {
1302 requested_next_hop_scid: next_scid,
1303 inbound_amount_msat,
1304 expected_outbound_amount_msat,
1310 let mut fee_earned_msat = None;
1311 let mut prev_channel_id = None;
1312 let mut claim_from_onchain_tx = false;
1313 let mut next_channel_id = None;
1314 let mut outbound_amount_forwarded_msat = None;
1315 read_tlv_fields!(reader, {
1316 (0, fee_earned_msat, option),
1317 (1, prev_channel_id, option),
1318 (2, claim_from_onchain_tx, required),
1319 (3, next_channel_id, option),
1320 (5, outbound_amount_forwarded_msat, option),
1322 Ok(Some(Event::PaymentForwarded {
1323 fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id,
1324 outbound_amount_forwarded_msat
1331 let mut channel_id = [0; 32];
1332 let mut reason = UpgradableRequired(None);
1333 let mut user_channel_id_low_opt: Option<u64> = None;
1334 let mut user_channel_id_high_opt: Option<u64> = None;
1335 let mut counterparty_node_id = None;
1336 let mut channel_capacity_sats = None;
1337 read_tlv_fields!(reader, {
1338 (0, channel_id, required),
1339 (1, user_channel_id_low_opt, option),
1340 (2, reason, upgradable_required),
1341 (3, user_channel_id_high_opt, option),
1342 (5, counterparty_node_id, option),
1343 (7, channel_capacity_sats, option),
1346 // `user_channel_id` used to be a single u64 value. In order to remain
1347 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1348 // as two separate u64 values.
1349 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1350 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1352 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required),
1353 counterparty_node_id, channel_capacity_sats }))
1359 let mut channel_id = [0; 32];
1360 let mut transaction = Transaction{ version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
1361 read_tlv_fields!(reader, {
1362 (0, channel_id, required),
1363 (2, transaction, required),
1365 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1371 _init_and_read_len_prefixed_tlv_fields!(reader, {
1372 (0, payment_id, required),
1373 (2, payment_hash, option),
1374 (4, path, required_vec),
1375 (6, blinded_tail, option),
1377 Ok(Some(Event::PaymentPathSuccessful {
1378 payment_id: payment_id.0.unwrap(),
1380 path: Path { hops: path, blinded_tail },
1387 let mut payment_hash = PaymentHash([0; 32]);
1388 let mut payment_id = PaymentId([0; 32]);
1389 let mut reason = None;
1390 read_tlv_fields!(reader, {
1391 (0, payment_id, required),
1392 (1, reason, upgradable_option),
1393 (2, payment_hash, required),
1395 Ok(Some(Event::PaymentFailed {
1404 // Value 17 is used for `Event::OpenChannelRequest`.
1409 let mut payment_hash = PaymentHash([0; 32]);
1410 let mut purpose = UpgradableRequired(None);
1411 let mut amount_msat = 0;
1412 let mut receiver_node_id = None;
1413 let mut htlcs: Option<Vec<ClaimedHTLC>> = Some(vec![]);
1414 let mut sender_intended_total_msat: Option<u64> = None;
1415 read_tlv_fields!(reader, {
1416 (0, payment_hash, required),
1417 (1, receiver_node_id, option),
1418 (2, purpose, upgradable_required),
1419 (4, amount_msat, required),
1420 (5, htlcs, optional_vec),
1421 (7, sender_intended_total_msat, option),
1423 Ok(Some(Event::PaymentClaimed {
1426 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1428 htlcs: htlcs.unwrap_or(vec![]),
1429 sender_intended_total_msat,
1436 _init_and_read_len_prefixed_tlv_fields!(reader, {
1437 (0, payment_id, required),
1438 (2, payment_hash, required),
1439 (4, path, required_vec),
1440 (6, blinded_tail, option),
1442 Ok(Some(Event::ProbeSuccessful {
1443 payment_id: payment_id.0.unwrap(),
1444 payment_hash: payment_hash.0.unwrap(),
1445 path: Path { hops: path, blinded_tail },
1452 _init_and_read_len_prefixed_tlv_fields!(reader, {
1453 (0, payment_id, required),
1454 (2, payment_hash, required),
1455 (4, path, required_vec),
1456 (6, short_channel_id, option),
1457 (8, blinded_tail, option),
1459 Ok(Some(Event::ProbeFailed {
1460 payment_id: payment_id.0.unwrap(),
1461 payment_hash: payment_hash.0.unwrap(),
1462 path: Path { hops: path, blinded_tail },
1470 let mut prev_channel_id = [0; 32];
1471 let mut failed_next_destination_opt = UpgradableRequired(None);
1472 read_tlv_fields!(reader, {
1473 (0, prev_channel_id, required),
1474 (2, failed_next_destination_opt, upgradable_required),
1476 Ok(Some(Event::HTLCHandlingFailed {
1478 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1486 let mut channel_id = [0; 32];
1487 let mut user_channel_id: u128 = 0;
1488 let mut counterparty_node_id = RequiredWrapper(None);
1489 let mut channel_type = RequiredWrapper(None);
1490 read_tlv_fields!(reader, {
1491 (0, channel_id, required),
1492 (2, user_channel_id, required),
1493 (4, counterparty_node_id, required),
1494 (6, channel_type, required),
1497 Ok(Some(Event::ChannelReady {
1500 counterparty_node_id: counterparty_node_id.0.unwrap(),
1501 channel_type: channel_type.0.unwrap()
1508 let mut channel_id = [0; 32];
1509 let mut user_channel_id: u128 = 0;
1510 let mut former_temporary_channel_id = None;
1511 let mut counterparty_node_id = RequiredWrapper(None);
1512 let mut funding_txo = RequiredWrapper(None);
1513 read_tlv_fields!(reader, {
1514 (0, channel_id, required),
1515 (2, user_channel_id, required),
1516 (4, former_temporary_channel_id, required),
1517 (6, counterparty_node_id, required),
1518 (8, funding_txo, required),
1521 Ok(Some(Event::ChannelPending {
1524 former_temporary_channel_id,
1525 counterparty_node_id: counterparty_node_id.0.unwrap(),
1526 funding_txo: funding_txo.0.unwrap()
1531 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1532 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1534 x if x % 2 == 1 => {
1535 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1536 // which prefixes the whole thing with a length BigSize. Because the event is
1537 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1538 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1539 // exactly the number of bytes specified, ignoring them entirely.
1540 let tlv_len: BigSize = Readable::read(reader)?;
1541 FixedLengthReader::new(reader, tlv_len.0)
1542 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1545 _ => Err(msgs::DecodeError::InvalidValue)
1550 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1551 /// broadcast to most peers).
1552 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1553 #[derive(Clone, Debug)]
1554 #[cfg_attr(test, derive(PartialEq))]
1555 pub enum MessageSendEvent {
1556 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1557 /// message provided to the given peer.
1559 /// The node_id of the node which should receive this message
1561 /// The message which should be sent.
1562 msg: msgs::AcceptChannel,
1564 /// Used to indicate that we've accepted a V2 channel open and should send the accept_channel2
1565 /// message provided to the given peer.
1566 SendAcceptChannelV2 {
1567 /// The node_id of the node which should receive this message
1569 /// The message which should be sent.
1570 msg: msgs::AcceptChannelV2,
1572 /// Used to indicate that we've initiated a channel open and should send the open_channel
1573 /// message provided to the given peer.
1575 /// The node_id of the node which should receive this message
1577 /// The message which should be sent.
1578 msg: msgs::OpenChannel,
1580 /// Used to indicate that we've initiated a V2 channel open and should send the open_channel2
1581 /// message provided to the given peer.
1583 /// The node_id of the node which should receive this message
1585 /// The message which should be sent.
1586 msg: msgs::OpenChannelV2,
1588 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1589 SendFundingCreated {
1590 /// The node_id of the node which should receive this message
1592 /// The message which should be sent.
1593 msg: msgs::FundingCreated,
1595 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1597 /// The node_id of the node which should receive this message
1599 /// The message which should be sent.
1600 msg: msgs::FundingSigned,
1602 /// Used to indicate that a tx_add_input message should be sent to the peer with the given node_id.
1604 /// The node_id of the node which should receive this message
1606 /// The message which should be sent.
1607 msg: msgs::TxAddInput,
1609 /// Used to indicate that a tx_add_output message should be sent to the peer with the given node_id.
1611 /// The node_id of the node which should receive this message
1613 /// The message which should be sent.
1614 msg: msgs::TxAddOutput,
1616 /// Used to indicate that a tx_remove_input message should be sent to the peer with the given node_id.
1618 /// The node_id of the node which should receive this message
1620 /// The message which should be sent.
1621 msg: msgs::TxRemoveInput,
1623 /// Used to indicate that a tx_remove_output message should be sent to the peer with the given node_id.
1624 SendTxRemoveOutput {
1625 /// The node_id of the node which should receive this message
1627 /// The message which should be sent.
1628 msg: msgs::TxRemoveOutput,
1630 /// Used to indicate that a tx_complete message should be sent to the peer with the given node_id.
1632 /// The node_id of the node which should receive this message
1634 /// The message which should be sent.
1635 msg: msgs::TxComplete,
1637 /// Used to indicate that a tx_signatures message should be sent to the peer with the given node_id.
1639 /// The node_id of the node which should receive this message
1641 /// The message which should be sent.
1642 msg: msgs::TxSignatures,
1644 /// Used to indicate that a tx_init_rbf message should be sent to the peer with the given node_id.
1646 /// The node_id of the node which should receive this message
1648 /// The message which should be sent.
1649 msg: msgs::TxInitRbf,
1651 /// Used to indicate that a tx_ack_rbf message should be sent to the peer with the given node_id.
1653 /// The node_id of the node which should receive this message
1655 /// The message which should be sent.
1656 msg: msgs::TxAckRbf,
1658 /// Used to indicate that a tx_abort message should be sent to the peer with the given node_id.
1660 /// The node_id of the node which should receive this message
1662 /// The message which should be sent.
1663 msg: msgs::TxAddInput,
1665 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1667 /// The node_id of the node which should receive these message(s)
1669 /// The channel_ready message which should be sent.
1670 msg: msgs::ChannelReady,
1672 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1673 SendAnnouncementSignatures {
1674 /// The node_id of the node which should receive these message(s)
1676 /// The announcement_signatures message which should be sent.
1677 msg: msgs::AnnouncementSignatures,
1679 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1680 /// message should be sent to the peer with the given node_id.
1682 /// The node_id of the node which should receive these message(s)
1684 /// The update messages which should be sent. ALL messages in the struct should be sent!
1685 updates: msgs::CommitmentUpdate,
1687 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1689 /// The node_id of the node which should receive this message
1691 /// The message which should be sent.
1692 msg: msgs::RevokeAndACK,
1694 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1696 /// The node_id of the node which should receive this message
1698 /// The message which should be sent.
1699 msg: msgs::ClosingSigned,
1701 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1703 /// The node_id of the node which should receive this message
1705 /// The message which should be sent.
1706 msg: msgs::Shutdown,
1708 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1709 SendChannelReestablish {
1710 /// The node_id of the node which should receive this message
1712 /// The message which should be sent.
1713 msg: msgs::ChannelReestablish,
1715 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1716 /// initial connection to ensure our peers know about our channels.
1717 SendChannelAnnouncement {
1718 /// The node_id of the node which should receive this message
1720 /// The channel_announcement which should be sent.
1721 msg: msgs::ChannelAnnouncement,
1722 /// The followup channel_update which should be sent.
1723 update_msg: msgs::ChannelUpdate,
1725 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1726 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1728 /// Note that after doing so, you very likely (unless you did so very recently) want to
1729 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1730 /// ensures that any nodes which see our channel_announcement also have a relevant
1731 /// node_announcement, including relevant feature flags which may be important for routing
1732 /// through or to us.
1734 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1735 BroadcastChannelAnnouncement {
1736 /// The channel_announcement which should be sent.
1737 msg: msgs::ChannelAnnouncement,
1738 /// The followup channel_update which should be sent.
1739 update_msg: Option<msgs::ChannelUpdate>,
1741 /// Used to indicate that a channel_update should be broadcast to all peers.
1742 BroadcastChannelUpdate {
1743 /// The channel_update which should be sent.
1744 msg: msgs::ChannelUpdate,
1746 /// Used to indicate that a node_announcement should be broadcast to all peers.
1747 BroadcastNodeAnnouncement {
1748 /// The node_announcement which should be sent.
1749 msg: msgs::NodeAnnouncement,
1751 /// Used to indicate that a channel_update should be sent to a single peer.
1752 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1753 /// private channel and we shouldn't be informing all of our peers of channel parameters.
1755 /// The node_id of the node which should receive this message
1757 /// The channel_update which should be sent.
1758 msg: msgs::ChannelUpdate,
1760 /// Broadcast an error downstream to be handled
1762 /// The node_id of the node which should receive this message
1764 /// The action which should be taken.
1765 action: msgs::ErrorAction
1767 /// Query a peer for channels with funding transaction UTXOs in a block range.
1768 SendChannelRangeQuery {
1769 /// The node_id of this message recipient
1771 /// The query_channel_range which should be sent.
1772 msg: msgs::QueryChannelRange,
1774 /// Request routing gossip messages from a peer for a list of channels identified by
1775 /// their short_channel_ids.
1777 /// The node_id of this message recipient
1779 /// The query_short_channel_ids which should be sent.
1780 msg: msgs::QueryShortChannelIds,
1782 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1783 /// emitted during processing of the query.
1784 SendReplyChannelRange {
1785 /// The node_id of this message recipient
1787 /// The reply_channel_range which should be sent.
1788 msg: msgs::ReplyChannelRange,
1790 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1791 /// enable receiving gossip messages from the peer.
1792 SendGossipTimestampFilter {
1793 /// The node_id of this message recipient
1795 /// The gossip_timestamp_filter which should be sent.
1796 msg: msgs::GossipTimestampFilter,
1800 /// A trait indicating an object may generate message send events
1801 pub trait MessageSendEventsProvider {
1802 /// Gets the list of pending events which were generated by previous actions, clearing the list
1804 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1807 /// A trait indicating an object may generate onion messages to send
1808 pub trait OnionMessageProvider {
1809 /// Gets the next pending onion message for the peer with the given node id.
1810 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<msgs::OnionMessage>;
1813 /// A trait indicating an object may generate events.
1815 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1817 /// Implementations of this trait may also feature an async version of event handling, as shown with
1818 /// [`ChannelManager::process_pending_events_async`] and
1819 /// [`ChainMonitor::process_pending_events_async`].
1823 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1824 /// event since the last invocation.
1826 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1827 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1828 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1829 /// relevant changes to disk *before* returning.
1831 /// Further, because an application may crash between an [`Event`] being handled and the
1832 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1833 /// effect, [`Event`]s may be replayed.
1835 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1836 /// consult the provider's documentation on the implication of processing events and how a handler
1837 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1838 /// [`ChainMonitor::process_pending_events`]).
1840 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1843 /// [`process_pending_events`]: Self::process_pending_events
1844 /// [`handle_event`]: EventHandler::handle_event
1845 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1846 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1847 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
1848 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
1849 pub trait EventsProvider {
1850 /// Processes any events generated since the last call using the given event handler.
1852 /// See the trait-level documentation for requirements.
1853 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1856 /// A trait implemented for objects handling events from [`EventsProvider`].
1858 /// An async variation also exists for implementations of [`EventsProvider`] that support async
1859 /// event handling. The async event handler should satisfy the generic bounds: `F:
1860 /// core::future::Future, H: Fn(Event) -> F`.
1861 pub trait EventHandler {
1862 /// Handles the given [`Event`].
1864 /// See [`EventsProvider`] for details that must be considered when implementing this method.
1865 fn handle_event(&self, event: Event);
1868 impl<F> EventHandler for F where F: Fn(Event) {
1869 fn handle_event(&self, event: Event) {
1874 impl<T: EventHandler> EventHandler for Arc<T> {
1875 fn handle_event(&self, event: Event) {
1876 self.deref().handle_event(event)