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::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: ChannelId,
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: ChannelId,
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: ChannelId,
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<ChannelId>,
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>,
718 /// The `channel_id` indicating which channel the spendable outputs belong to.
720 /// This will always be `Some` for events generated by LDK versions 0.0.117 and above.
721 channel_id: Option<ChannelId>,
723 /// This event is generated when a payment has been successfully forwarded through us and a
724 /// forwarding fee earned.
726 /// The incoming channel between the previous node and us. This is only `None` for events
727 /// generated or serialized by versions prior to 0.0.107.
728 prev_channel_id: Option<ChannelId>,
729 /// The outgoing channel between the next node and us. This is only `None` for events
730 /// generated or serialized by versions prior to 0.0.107.
731 next_channel_id: Option<ChannelId>,
732 /// The fee, in milli-satoshis, which was earned as a result of the payment.
734 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
735 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
736 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
737 /// claimed the full value in millisatoshis from the source. In this case,
738 /// `claim_from_onchain_tx` will be set.
740 /// If the channel which sent us the payment has been force-closed, we will claim the funds
741 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
742 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
743 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
745 fee_earned_msat: Option<u64>,
746 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
748 claim_from_onchain_tx: bool,
749 /// The final amount forwarded, in milli-satoshis, after the fee is deducted.
751 /// The caveat described above the `fee_earned_msat` field applies here as well.
752 outbound_amount_forwarded_msat: Option<u64>,
754 /// Used to indicate that a channel with the given `channel_id` is being opened and pending
755 /// confirmation on-chain.
757 /// This event is emitted when the funding transaction has been signed and is broadcast to the
758 /// network. For 0conf channels it will be immediately followed by the corresponding
759 /// [`Event::ChannelReady`] event.
761 /// The `channel_id` of the channel that is pending confirmation.
762 channel_id: ChannelId,
763 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
764 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
765 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
766 /// `user_channel_id` will be randomized for an inbound channel.
768 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
769 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
770 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
771 user_channel_id: u128,
772 /// The `temporary_channel_id` this channel used to be known by during channel establishment.
774 /// Will be `None` for channels created prior to LDK version 0.0.115.
775 former_temporary_channel_id: Option<ChannelId>,
776 /// The `node_id` of the channel counterparty.
777 counterparty_node_id: PublicKey,
778 /// The outpoint of the channel's funding transaction.
779 funding_txo: OutPoint,
781 /// Used to indicate that a channel with the given `channel_id` is ready to
782 /// be used. This event is emitted either when the funding transaction has been confirmed
783 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
786 /// The `channel_id` of the channel that is ready.
787 channel_id: ChannelId,
788 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
789 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
790 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
791 /// `user_channel_id` will be randomized for an inbound channel.
793 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
794 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
795 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
796 user_channel_id: u128,
797 /// The `node_id` of the channel counterparty.
798 counterparty_node_id: PublicKey,
799 /// The features that this channel will operate with.
800 channel_type: ChannelTypeFeatures,
802 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
803 /// process of closure.
805 /// Note that this event is only triggered for accepted channels: if the
806 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true and the channel is
807 /// rejected, no `ChannelClosed` event will be sent.
809 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
810 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
812 /// The `channel_id` of the channel which has been closed. Note that on-chain transactions
813 /// resolving the channel are likely still awaiting confirmation.
814 channel_id: ChannelId,
815 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
816 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
817 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
818 /// `user_channel_id` will be randomized for inbound channels.
819 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
820 /// zero for objects serialized with LDK versions prior to 0.0.102.
822 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
823 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
824 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
825 user_channel_id: u128,
826 /// The reason the channel was closed.
827 reason: ClosureReason,
828 /// Counterparty in the closed channel.
830 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
831 counterparty_node_id: Option<PublicKey>,
832 /// Channel capacity of the closing channel (sats).
834 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
835 channel_capacity_sats: Option<u64>,
837 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
838 /// inputs for another purpose.
840 /// The channel_id of the channel which has been closed.
841 channel_id: ChannelId,
842 /// The full transaction received from the user
843 transaction: Transaction
845 /// Indicates a request to open a new channel by a peer.
847 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the request,
848 /// call [`ChannelManager::force_close_without_broadcasting_txn`]. Note that a ['ChannelClosed`]
849 /// event will _not_ be triggered if the channel is rejected.
851 /// The event is only triggered when a new open channel request is received and the
852 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
854 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
855 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
856 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
858 /// The temporary channel ID of the channel requested to be opened.
860 /// When responding to the request, the `temporary_channel_id` should be passed
861 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
862 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
864 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
865 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
866 temporary_channel_id: ChannelId,
867 /// The node_id of the counterparty requesting to open the channel.
869 /// When responding to the request, the `counterparty_node_id` should be passed
870 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
871 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
874 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
875 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
876 counterparty_node_id: PublicKey,
877 /// The channel value of the requested channel.
878 funding_satoshis: u64,
879 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
881 /// The features that this channel will operate with. If you reject the channel, a
882 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
885 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
886 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
889 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
890 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
891 /// 0.0.107. Channels setting this type also need to get manually accepted via
892 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
893 /// or will be rejected otherwise.
895 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
896 channel_type: ChannelTypeFeatures,
898 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
901 /// Some scenarios where this event may be sent include:
902 /// * Insufficient capacity in the outbound channel
903 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
904 /// * When an unknown SCID is requested for forwarding a payment.
905 /// * Expected MPP amount has already been reached
906 /// * The HTLC has timed out
908 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
909 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
911 /// The channel over which the HTLC was received.
912 prev_channel_id: ChannelId,
913 /// Destination of the HTLC that failed to be processed.
914 failed_next_destination: HTLCDestination,
916 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
917 /// requires confirmed external funds to be readily available to spend.
919 /// LDK does not currently generate this event unless the
920 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`] config flag is set to true.
921 /// It is limited to the scope of channels with anchor outputs.
923 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`]: crate::util::config::ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx
924 BumpTransaction(BumpTransactionEvent),
927 impl Writeable for Event {
928 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
930 &Event::FundingGenerationReady { .. } => {
932 // We never write out FundingGenerationReady events as, upon disconnection, peers
933 // drop any channels which have not yet exchanged funding_signed.
935 &Event::PaymentClaimable { ref payment_hash, ref amount_msat, counterparty_skimmed_fee_msat,
936 ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id,
937 ref claim_deadline, ref onion_fields
940 let mut payment_secret = None;
941 let payment_preimage;
943 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
944 payment_secret = Some(secret);
945 payment_preimage = *preimage;
947 PaymentPurpose::SpontaneousPayment(preimage) => {
948 payment_preimage = Some(*preimage);
951 let skimmed_fee_opt = if counterparty_skimmed_fee_msat == 0 { None }
952 else { Some(counterparty_skimmed_fee_msat) };
953 write_tlv_fields!(writer, {
954 (0, payment_hash, required),
955 (1, receiver_node_id, option),
956 (2, payment_secret, option),
957 (3, via_channel_id, option),
958 (4, amount_msat, required),
959 (5, via_user_channel_id, option),
960 // Type 6 was `user_payment_id` on 0.0.103 and earlier
961 (7, claim_deadline, option),
962 (8, payment_preimage, option),
963 (9, onion_fields, option),
964 (10, skimmed_fee_opt, option),
967 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
969 write_tlv_fields!(writer, {
970 (0, payment_preimage, required),
971 (1, payment_hash, required),
972 (3, payment_id, option),
973 (5, fee_paid_msat, option),
976 &Event::PaymentPathFailed {
977 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
978 ref path, ref short_channel_id,
986 error_code.write(writer)?;
988 error_data.write(writer)?;
989 write_tlv_fields!(writer, {
990 (0, payment_hash, required),
991 (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
992 (2, payment_failed_permanently, required),
993 (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
994 (4, path.blinded_tail, option),
995 (5, path.hops, required_vec),
996 (7, short_channel_id, option),
997 (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
998 (11, payment_id, option),
999 (13, failure, required),
1002 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
1004 // Note that we now ignore these on the read end as we'll re-generate them in
1005 // ChannelManager, we write them here only for backwards compatibility.
1007 &Event::SpendableOutputs { ref outputs, channel_id } => {
1009 write_tlv_fields!(writer, {
1010 (0, WithoutLength(outputs), required),
1011 (1, channel_id, option),
1014 &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1016 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1017 write_tlv_fields!(writer, {
1018 (0, intercept_id, required),
1019 (2, intercept_scid, required),
1020 (4, payment_hash, required),
1021 (6, inbound_amount_msat, required),
1022 (8, expected_outbound_amount_msat, required),
1025 &Event::PaymentForwarded {
1026 fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
1027 next_channel_id, outbound_amount_forwarded_msat
1030 write_tlv_fields!(writer, {
1031 (0, fee_earned_msat, option),
1032 (1, prev_channel_id, option),
1033 (2, claim_from_onchain_tx, required),
1034 (3, next_channel_id, option),
1035 (5, outbound_amount_forwarded_msat, option),
1038 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason,
1039 ref counterparty_node_id, ref channel_capacity_sats
1042 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1043 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1044 // separate u64 values.
1045 let user_channel_id_low = *user_channel_id as u64;
1046 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1047 write_tlv_fields!(writer, {
1048 (0, channel_id, required),
1049 (1, user_channel_id_low, required),
1050 (2, reason, required),
1051 (3, user_channel_id_high, required),
1052 (5, counterparty_node_id, option),
1053 (7, channel_capacity_sats, option),
1056 &Event::DiscardFunding { ref channel_id, ref transaction } => {
1057 11u8.write(writer)?;
1058 write_tlv_fields!(writer, {
1059 (0, channel_id, required),
1060 (2, transaction, required)
1063 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1064 13u8.write(writer)?;
1065 write_tlv_fields!(writer, {
1066 (0, payment_id, required),
1067 (2, payment_hash, option),
1068 (4, path.hops, required_vec),
1069 (6, path.blinded_tail, option),
1072 &Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
1073 15u8.write(writer)?;
1074 write_tlv_fields!(writer, {
1075 (0, payment_id, required),
1076 (1, reason, option),
1077 (2, payment_hash, required),
1080 &Event::OpenChannelRequest { .. } => {
1081 17u8.write(writer)?;
1082 // We never write the OpenChannelRequest events as, upon disconnection, peers
1083 // drop any channels which have not yet exchanged funding_signed.
1085 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref htlcs, ref sender_intended_total_msat } => {
1086 19u8.write(writer)?;
1087 write_tlv_fields!(writer, {
1088 (0, payment_hash, required),
1089 (1, receiver_node_id, option),
1090 (2, purpose, required),
1091 (4, amount_msat, required),
1092 (5, *htlcs, optional_vec),
1093 (7, sender_intended_total_msat, option),
1096 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1097 21u8.write(writer)?;
1098 write_tlv_fields!(writer, {
1099 (0, payment_id, required),
1100 (2, payment_hash, required),
1101 (4, path.hops, required_vec),
1102 (6, path.blinded_tail, option),
1105 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1106 23u8.write(writer)?;
1107 write_tlv_fields!(writer, {
1108 (0, payment_id, required),
1109 (2, payment_hash, required),
1110 (4, path.hops, required_vec),
1111 (6, short_channel_id, option),
1112 (8, path.blinded_tail, option),
1115 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1116 25u8.write(writer)?;
1117 write_tlv_fields!(writer, {
1118 (0, prev_channel_id, required),
1119 (2, failed_next_destination, required),
1122 &Event::BumpTransaction(ref event)=> {
1123 27u8.write(writer)?;
1125 // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1126 // upon restarting anyway if they remain unresolved.
1127 BumpTransactionEvent::ChannelClose { .. } => {}
1128 BumpTransactionEvent::HTLCResolution { .. } => {}
1130 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1132 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1133 29u8.write(writer)?;
1134 write_tlv_fields!(writer, {
1135 (0, channel_id, required),
1136 (2, user_channel_id, required),
1137 (4, counterparty_node_id, required),
1138 (6, channel_type, required),
1141 &Event::ChannelPending { ref channel_id, ref user_channel_id, ref former_temporary_channel_id, ref counterparty_node_id, ref funding_txo } => {
1142 31u8.write(writer)?;
1143 write_tlv_fields!(writer, {
1144 (0, channel_id, required),
1145 (2, user_channel_id, required),
1146 (4, former_temporary_channel_id, required),
1147 (6, counterparty_node_id, required),
1148 (8, funding_txo, required),
1151 // Note that, going forward, all new events must only write data inside of
1152 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1153 // data via `write_tlv_fields`.
1158 impl MaybeReadable for Event {
1159 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1160 match Readable::read(reader)? {
1161 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
1162 // unlike all other events, thus we return immediately here.
1166 let mut payment_hash = PaymentHash([0; 32]);
1167 let mut payment_preimage = None;
1168 let mut payment_secret = None;
1169 let mut amount_msat = 0;
1170 let mut counterparty_skimmed_fee_msat_opt = None;
1171 let mut receiver_node_id = None;
1172 let mut _user_payment_id = None::<u64>; // Used in 0.0.103 and earlier, no longer written in 0.0.116+.
1173 let mut via_channel_id = None;
1174 let mut claim_deadline = None;
1175 let mut via_user_channel_id = None;
1176 let mut onion_fields = None;
1177 read_tlv_fields!(reader, {
1178 (0, payment_hash, required),
1179 (1, receiver_node_id, option),
1180 (2, payment_secret, option),
1181 (3, via_channel_id, option),
1182 (4, amount_msat, required),
1183 (5, via_user_channel_id, option),
1184 (6, _user_payment_id, option),
1185 (7, claim_deadline, option),
1186 (8, payment_preimage, option),
1187 (9, onion_fields, option),
1188 (10, counterparty_skimmed_fee_msat_opt, option),
1190 let purpose = match payment_secret {
1191 Some(secret) => PaymentPurpose::InvoicePayment {
1193 payment_secret: secret
1195 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1196 None => return Err(msgs::DecodeError::InvalidValue),
1198 Ok(Some(Event::PaymentClaimable {
1202 counterparty_skimmed_fee_msat: counterparty_skimmed_fee_msat_opt.unwrap_or(0),
1205 via_user_channel_id,
1214 let mut payment_preimage = PaymentPreimage([0; 32]);
1215 let mut payment_hash = None;
1216 let mut payment_id = None;
1217 let mut fee_paid_msat = None;
1218 read_tlv_fields!(reader, {
1219 (0, payment_preimage, required),
1220 (1, payment_hash, option),
1221 (3, payment_id, option),
1222 (5, fee_paid_msat, option),
1224 if payment_hash.is_none() {
1225 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
1227 Ok(Some(Event::PaymentSent {
1230 payment_hash: payment_hash.unwrap(),
1239 let error_code = Readable::read(reader)?;
1241 let error_data = Readable::read(reader)?;
1242 let mut payment_hash = PaymentHash([0; 32]);
1243 let mut payment_failed_permanently = false;
1244 let mut network_update = None;
1245 let mut blinded_tail: Option<BlindedTail> = None;
1246 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1247 let mut short_channel_id = None;
1248 let mut payment_id = None;
1249 let mut failure_opt = None;
1250 read_tlv_fields!(reader, {
1251 (0, payment_hash, required),
1252 (1, network_update, upgradable_option),
1253 (2, payment_failed_permanently, required),
1254 (4, blinded_tail, option),
1255 // Added as a part of LDK 0.0.101 and always filled in since.
1256 // Defaults to an empty Vec, though likely should have been `Option`al.
1257 (5, path, optional_vec),
1258 (7, short_channel_id, option),
1259 (11, payment_id, option),
1260 (13, failure_opt, upgradable_option),
1262 let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1263 Ok(Some(Event::PaymentPathFailed {
1266 payment_failed_permanently,
1268 path: Path { hops: path.unwrap(), blinded_tail },
1281 let mut outputs = WithoutLength(Vec::new());
1282 let mut channel_id: Option<ChannelId> = None;
1283 read_tlv_fields!(reader, {
1284 (0, outputs, required),
1285 (1, channel_id, option),
1287 Ok(Some(Event::SpendableOutputs { outputs: outputs.0, channel_id }))
1292 let mut payment_hash = PaymentHash([0; 32]);
1293 let mut intercept_id = InterceptId([0; 32]);
1294 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1295 let mut inbound_amount_msat = 0;
1296 let mut expected_outbound_amount_msat = 0;
1297 read_tlv_fields!(reader, {
1298 (0, intercept_id, required),
1299 (2, requested_next_hop_scid, required),
1300 (4, payment_hash, required),
1301 (6, inbound_amount_msat, required),
1302 (8, expected_outbound_amount_msat, required),
1304 let next_scid = match requested_next_hop_scid {
1305 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1307 Ok(Some(Event::HTLCIntercepted {
1309 requested_next_hop_scid: next_scid,
1310 inbound_amount_msat,
1311 expected_outbound_amount_msat,
1317 let mut fee_earned_msat = None;
1318 let mut prev_channel_id = None;
1319 let mut claim_from_onchain_tx = false;
1320 let mut next_channel_id = None;
1321 let mut outbound_amount_forwarded_msat = None;
1322 read_tlv_fields!(reader, {
1323 (0, fee_earned_msat, option),
1324 (1, prev_channel_id, option),
1325 (2, claim_from_onchain_tx, required),
1326 (3, next_channel_id, option),
1327 (5, outbound_amount_forwarded_msat, option),
1329 Ok(Some(Event::PaymentForwarded {
1330 fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id,
1331 outbound_amount_forwarded_msat
1338 let mut channel_id = ChannelId::new_zero();
1339 let mut reason = UpgradableRequired(None);
1340 let mut user_channel_id_low_opt: Option<u64> = None;
1341 let mut user_channel_id_high_opt: Option<u64> = None;
1342 let mut counterparty_node_id = None;
1343 let mut channel_capacity_sats = None;
1344 read_tlv_fields!(reader, {
1345 (0, channel_id, required),
1346 (1, user_channel_id_low_opt, option),
1347 (2, reason, upgradable_required),
1348 (3, user_channel_id_high_opt, option),
1349 (5, counterparty_node_id, option),
1350 (7, channel_capacity_sats, option),
1353 // `user_channel_id` used to be a single u64 value. In order to remain
1354 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1355 // as two separate u64 values.
1356 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1357 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1359 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required),
1360 counterparty_node_id, channel_capacity_sats }))
1366 let mut channel_id = ChannelId::new_zero();
1367 let mut transaction = Transaction{ version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
1368 read_tlv_fields!(reader, {
1369 (0, channel_id, required),
1370 (2, transaction, required),
1372 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1378 _init_and_read_len_prefixed_tlv_fields!(reader, {
1379 (0, payment_id, required),
1380 (2, payment_hash, option),
1381 (4, path, required_vec),
1382 (6, blinded_tail, option),
1384 Ok(Some(Event::PaymentPathSuccessful {
1385 payment_id: payment_id.0.unwrap(),
1387 path: Path { hops: path, blinded_tail },
1394 let mut payment_hash = PaymentHash([0; 32]);
1395 let mut payment_id = PaymentId([0; 32]);
1396 let mut reason = None;
1397 read_tlv_fields!(reader, {
1398 (0, payment_id, required),
1399 (1, reason, upgradable_option),
1400 (2, payment_hash, required),
1402 Ok(Some(Event::PaymentFailed {
1411 // Value 17 is used for `Event::OpenChannelRequest`.
1416 let mut payment_hash = PaymentHash([0; 32]);
1417 let mut purpose = UpgradableRequired(None);
1418 let mut amount_msat = 0;
1419 let mut receiver_node_id = None;
1420 let mut htlcs: Option<Vec<ClaimedHTLC>> = Some(vec![]);
1421 let mut sender_intended_total_msat: Option<u64> = None;
1422 read_tlv_fields!(reader, {
1423 (0, payment_hash, required),
1424 (1, receiver_node_id, option),
1425 (2, purpose, upgradable_required),
1426 (4, amount_msat, required),
1427 (5, htlcs, optional_vec),
1428 (7, sender_intended_total_msat, option),
1430 Ok(Some(Event::PaymentClaimed {
1433 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1435 htlcs: htlcs.unwrap_or(vec![]),
1436 sender_intended_total_msat,
1443 _init_and_read_len_prefixed_tlv_fields!(reader, {
1444 (0, payment_id, required),
1445 (2, payment_hash, required),
1446 (4, path, required_vec),
1447 (6, blinded_tail, option),
1449 Ok(Some(Event::ProbeSuccessful {
1450 payment_id: payment_id.0.unwrap(),
1451 payment_hash: payment_hash.0.unwrap(),
1452 path: Path { hops: path, blinded_tail },
1459 _init_and_read_len_prefixed_tlv_fields!(reader, {
1460 (0, payment_id, required),
1461 (2, payment_hash, required),
1462 (4, path, required_vec),
1463 (6, short_channel_id, option),
1464 (8, blinded_tail, option),
1466 Ok(Some(Event::ProbeFailed {
1467 payment_id: payment_id.0.unwrap(),
1468 payment_hash: payment_hash.0.unwrap(),
1469 path: Path { hops: path, blinded_tail },
1477 let mut prev_channel_id = ChannelId::new_zero();
1478 let mut failed_next_destination_opt = UpgradableRequired(None);
1479 read_tlv_fields!(reader, {
1480 (0, prev_channel_id, required),
1481 (2, failed_next_destination_opt, upgradable_required),
1483 Ok(Some(Event::HTLCHandlingFailed {
1485 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1493 let mut channel_id = ChannelId::new_zero();
1494 let mut user_channel_id: u128 = 0;
1495 let mut counterparty_node_id = RequiredWrapper(None);
1496 let mut channel_type = RequiredWrapper(None);
1497 read_tlv_fields!(reader, {
1498 (0, channel_id, required),
1499 (2, user_channel_id, required),
1500 (4, counterparty_node_id, required),
1501 (6, channel_type, required),
1504 Ok(Some(Event::ChannelReady {
1507 counterparty_node_id: counterparty_node_id.0.unwrap(),
1508 channel_type: channel_type.0.unwrap()
1515 let mut channel_id = ChannelId::new_zero();
1516 let mut user_channel_id: u128 = 0;
1517 let mut former_temporary_channel_id = None;
1518 let mut counterparty_node_id = RequiredWrapper(None);
1519 let mut funding_txo = RequiredWrapper(None);
1520 read_tlv_fields!(reader, {
1521 (0, channel_id, required),
1522 (2, user_channel_id, required),
1523 (4, former_temporary_channel_id, required),
1524 (6, counterparty_node_id, required),
1525 (8, funding_txo, required),
1528 Ok(Some(Event::ChannelPending {
1531 former_temporary_channel_id,
1532 counterparty_node_id: counterparty_node_id.0.unwrap(),
1533 funding_txo: funding_txo.0.unwrap()
1538 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1539 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1541 x if x % 2 == 1 => {
1542 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1543 // which prefixes the whole thing with a length BigSize. Because the event is
1544 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1545 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1546 // exactly the number of bytes specified, ignoring them entirely.
1547 let tlv_len: BigSize = Readable::read(reader)?;
1548 FixedLengthReader::new(reader, tlv_len.0)
1549 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1552 _ => Err(msgs::DecodeError::InvalidValue)
1557 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1558 /// broadcast to most peers).
1559 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1560 #[derive(Clone, Debug)]
1561 #[cfg_attr(test, derive(PartialEq))]
1562 pub enum MessageSendEvent {
1563 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1564 /// message provided to the given peer.
1566 /// The node_id of the node which should receive this message
1568 /// The message which should be sent.
1569 msg: msgs::AcceptChannel,
1571 /// Used to indicate that we've accepted a V2 channel open and should send the accept_channel2
1572 /// message provided to the given peer.
1573 SendAcceptChannelV2 {
1574 /// The node_id of the node which should receive this message
1576 /// The message which should be sent.
1577 msg: msgs::AcceptChannelV2,
1579 /// Used to indicate that we've initiated a channel open and should send the open_channel
1580 /// message provided to the given peer.
1582 /// The node_id of the node which should receive this message
1584 /// The message which should be sent.
1585 msg: msgs::OpenChannel,
1587 /// Used to indicate that we've initiated a V2 channel open and should send the open_channel2
1588 /// message provided to the given peer.
1590 /// The node_id of the node which should receive this message
1592 /// The message which should be sent.
1593 msg: msgs::OpenChannelV2,
1595 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1596 SendFundingCreated {
1597 /// The node_id of the node which should receive this message
1599 /// The message which should be sent.
1600 msg: msgs::FundingCreated,
1602 /// Used to indicate that a funding_signed 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::FundingSigned,
1609 /// Used to indicate that a tx_add_input 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::TxAddInput,
1616 /// Used to indicate that a tx_add_output 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::TxAddOutput,
1623 /// Used to indicate that a tx_remove_input message should be sent to the peer with the given node_id.
1625 /// The node_id of the node which should receive this message
1627 /// The message which should be sent.
1628 msg: msgs::TxRemoveInput,
1630 /// Used to indicate that a tx_remove_output message should be sent to the peer with the given node_id.
1631 SendTxRemoveOutput {
1632 /// The node_id of the node which should receive this message
1634 /// The message which should be sent.
1635 msg: msgs::TxRemoveOutput,
1637 /// Used to indicate that a tx_complete 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::TxComplete,
1644 /// Used to indicate that a tx_signatures 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::TxSignatures,
1651 /// Used to indicate that a tx_init_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::TxInitRbf,
1658 /// Used to indicate that a tx_ack_rbf 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::TxAckRbf,
1665 /// Used to indicate that a tx_abort message should be sent to the peer with the given node_id.
1667 /// The node_id of the node which should receive this message
1669 /// The message which should be sent.
1670 msg: msgs::TxAddInput,
1672 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1674 /// The node_id of the node which should receive these message(s)
1676 /// The channel_ready message which should be sent.
1677 msg: msgs::ChannelReady,
1679 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1680 SendAnnouncementSignatures {
1681 /// The node_id of the node which should receive these message(s)
1683 /// The announcement_signatures message which should be sent.
1684 msg: msgs::AnnouncementSignatures,
1686 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1687 /// message should be sent to the peer with the given node_id.
1689 /// The node_id of the node which should receive these message(s)
1691 /// The update messages which should be sent. ALL messages in the struct should be sent!
1692 updates: msgs::CommitmentUpdate,
1694 /// Used to indicate that a revoke_and_ack 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::RevokeAndACK,
1701 /// Used to indicate that a closing_signed 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::ClosingSigned,
1708 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1710 /// The node_id of the node which should receive this message
1712 /// The message which should be sent.
1713 msg: msgs::Shutdown,
1715 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1716 SendChannelReestablish {
1717 /// The node_id of the node which should receive this message
1719 /// The message which should be sent.
1720 msg: msgs::ChannelReestablish,
1722 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1723 /// initial connection to ensure our peers know about our channels.
1724 SendChannelAnnouncement {
1725 /// The node_id of the node which should receive this message
1727 /// The channel_announcement which should be sent.
1728 msg: msgs::ChannelAnnouncement,
1729 /// The followup channel_update which should be sent.
1730 update_msg: msgs::ChannelUpdate,
1732 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1733 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1735 /// Note that after doing so, you very likely (unless you did so very recently) want to
1736 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1737 /// ensures that any nodes which see our channel_announcement also have a relevant
1738 /// node_announcement, including relevant feature flags which may be important for routing
1739 /// through or to us.
1741 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1742 BroadcastChannelAnnouncement {
1743 /// The channel_announcement which should be sent.
1744 msg: msgs::ChannelAnnouncement,
1745 /// The followup channel_update which should be sent.
1746 update_msg: Option<msgs::ChannelUpdate>,
1748 /// Used to indicate that a channel_update should be broadcast to all peers.
1749 BroadcastChannelUpdate {
1750 /// The channel_update which should be sent.
1751 msg: msgs::ChannelUpdate,
1753 /// Used to indicate that a node_announcement should be broadcast to all peers.
1754 BroadcastNodeAnnouncement {
1755 /// The node_announcement which should be sent.
1756 msg: msgs::NodeAnnouncement,
1758 /// Used to indicate that a channel_update should be sent to a single peer.
1759 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1760 /// private channel and we shouldn't be informing all of our peers of channel parameters.
1762 /// The node_id of the node which should receive this message
1764 /// The channel_update which should be sent.
1765 msg: msgs::ChannelUpdate,
1767 /// Broadcast an error downstream to be handled
1769 /// The node_id of the node which should receive this message
1771 /// The action which should be taken.
1772 action: msgs::ErrorAction
1774 /// Query a peer for channels with funding transaction UTXOs in a block range.
1775 SendChannelRangeQuery {
1776 /// The node_id of this message recipient
1778 /// The query_channel_range which should be sent.
1779 msg: msgs::QueryChannelRange,
1781 /// Request routing gossip messages from a peer for a list of channels identified by
1782 /// their short_channel_ids.
1784 /// The node_id of this message recipient
1786 /// The query_short_channel_ids which should be sent.
1787 msg: msgs::QueryShortChannelIds,
1789 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1790 /// emitted during processing of the query.
1791 SendReplyChannelRange {
1792 /// The node_id of this message recipient
1794 /// The reply_channel_range which should be sent.
1795 msg: msgs::ReplyChannelRange,
1797 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1798 /// enable receiving gossip messages from the peer.
1799 SendGossipTimestampFilter {
1800 /// The node_id of this message recipient
1802 /// The gossip_timestamp_filter which should be sent.
1803 msg: msgs::GossipTimestampFilter,
1807 /// A trait indicating an object may generate message send events
1808 pub trait MessageSendEventsProvider {
1809 /// Gets the list of pending events which were generated by previous actions, clearing the list
1811 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1814 /// A trait indicating an object may generate onion messages to send
1815 pub trait OnionMessageProvider {
1816 /// Gets the next pending onion message for the peer with the given node id.
1817 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<msgs::OnionMessage>;
1820 /// A trait indicating an object may generate events.
1822 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1824 /// Implementations of this trait may also feature an async version of event handling, as shown with
1825 /// [`ChannelManager::process_pending_events_async`] and
1826 /// [`ChainMonitor::process_pending_events_async`].
1830 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1831 /// event since the last invocation.
1833 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1834 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1835 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1836 /// relevant changes to disk *before* returning.
1838 /// Further, because an application may crash between an [`Event`] being handled and the
1839 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1840 /// effect, [`Event`]s may be replayed.
1842 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1843 /// consult the provider's documentation on the implication of processing events and how a handler
1844 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1845 /// [`ChainMonitor::process_pending_events`]).
1847 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1850 /// [`process_pending_events`]: Self::process_pending_events
1851 /// [`handle_event`]: EventHandler::handle_event
1852 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1853 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1854 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
1855 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
1856 pub trait EventsProvider {
1857 /// Processes any events generated since the last call using the given event handler.
1859 /// See the trait-level documentation for requirements.
1860 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1863 /// A trait implemented for objects handling events from [`EventsProvider`].
1865 /// An async variation also exists for implementations of [`EventsProvider`] that support async
1866 /// event handling. The async event handler should satisfy the generic bounds: `F:
1867 /// core::future::Future, H: Fn(Event) -> F`.
1868 pub trait EventHandler {
1869 /// Handles the given [`Event`].
1871 /// See [`EventsProvider`] for details that must be considered when implementing this method.
1872 fn handle_event(&self, event: Event);
1875 impl<F> EventHandler for F where F: Fn(Event) {
1876 fn handle_event(&self, event: Event) {
1881 impl<T: EventHandler> EventHandler for Arc<T> {
1882 fn handle_event(&self, event: Event) {
1883 self.deref().handle_event(event)