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::{Transaction, OutPoint};
34 use bitcoin::blockdata::locktime::absolute::LockTime;
35 use bitcoin::blockdata::script::ScriptBuf;
36 use bitcoin::hashes::Hash;
37 use bitcoin::hashes::sha256::Hash as Sha256;
38 use bitcoin::secp256k1::PublicKey;
40 use crate::prelude::*;
41 use core::time::Duration;
45 /// Some information provided on receipt of payment depends on whether the payment received is a
46 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
47 #[derive(Clone, Debug, PartialEq, Eq)]
48 pub enum PaymentPurpose {
49 /// Information for receiving a payment that we generated an invoice for.
51 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
52 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
53 /// [`ChannelManager::claim_funds`].
55 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
56 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
57 payment_preimage: Option<PaymentPreimage>,
58 /// The "payment secret". This authenticates the sender to the recipient, preventing a
59 /// number of deanonymization attacks during the routing process.
60 /// It is provided here for your reference, however its accuracy is enforced directly by
61 /// [`ChannelManager`] using the values you previously provided to
62 /// [`ChannelManager::create_inbound_payment`] or
63 /// [`ChannelManager::create_inbound_payment_for_hash`].
65 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
66 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
67 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
68 payment_secret: PaymentSecret,
70 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
71 /// (the payee) providing a preimage.
72 SpontaneousPayment(PaymentPreimage),
75 impl_writeable_tlv_based_enum!(PaymentPurpose,
76 (0, InvoicePayment) => {
77 (0, payment_preimage, option),
78 (2, payment_secret, required),
80 (2, SpontaneousPayment)
83 /// Information about an HTLC that is part of a payment that can be claimed.
84 #[derive(Clone, Debug, PartialEq, Eq)]
85 pub struct ClaimedHTLC {
86 /// The `channel_id` of the channel over which the HTLC was received.
87 pub channel_id: ChannelId,
88 /// The `user_channel_id` of the channel over which the HTLC was received. This is the value
89 /// passed in to [`ChannelManager::create_channel`] for outbound channels, or to
90 /// [`ChannelManager::accept_inbound_channel`] for inbound channels if
91 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
92 /// `user_channel_id` will be randomized for an inbound channel.
94 /// This field will be zero for a payment that was serialized prior to LDK version 0.0.117. (This
95 /// should only happen in the case that a payment was claimable prior to LDK version 0.0.117, but
96 /// was not actually claimed until after upgrading.)
98 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
99 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
100 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
101 pub user_channel_id: u128,
102 /// The block height at which this HTLC expires.
103 pub cltv_expiry: u32,
104 /// The amount (in msats) of this part of an MPP.
106 /// The extra fee our counterparty skimmed off the top of this HTLC, if any.
108 /// This value will always be 0 for [`ClaimedHTLC`]s serialized with LDK versions prior to
110 pub counterparty_skimmed_fee_msat: u64,
112 impl_writeable_tlv_based!(ClaimedHTLC, {
113 (0, channel_id, required),
114 (1, counterparty_skimmed_fee_msat, (default_value, 0u64)),
115 (2, user_channel_id, required),
116 (4, cltv_expiry, required),
117 (6, value_msat, required),
120 /// When the payment path failure took place and extra details about it. [`PathFailure::OnPath`] may
121 /// contain a [`NetworkUpdate`] that needs to be applied to the [`NetworkGraph`].
123 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
124 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
125 #[derive(Clone, Debug, Eq, PartialEq)]
126 pub enum PathFailure {
127 /// We failed to initially send the payment and no HTLC was committed to. Contains the relevant
130 /// The error surfaced from initial send.
133 /// A hop on the path failed to forward our payment.
135 /// If present, this [`NetworkUpdate`] should be applied to the [`NetworkGraph`] so that routing
136 /// decisions can take into account the update.
138 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
139 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
140 network_update: Option<NetworkUpdate>,
144 impl_writeable_tlv_based_enum_upgradable!(PathFailure,
146 (0, network_update, upgradable_option),
148 (2, InitialSend) => {
149 (0, err, upgradable_required),
153 #[derive(Clone, Debug, PartialEq, Eq)]
154 /// The reason the channel was closed. See individual variants for more details.
155 pub enum ClosureReason {
156 /// Closure generated from receiving a peer error message.
158 /// Our counterparty may have broadcasted their latest commitment state, and we have
160 CounterpartyForceClosed {
161 /// The error which the peer sent us.
163 /// Be careful about printing the peer_msg, a well-crafted message could exploit
164 /// a security vulnerability in the terminal emulator or the logging subsystem.
165 /// To be safe, use `Display` on `UntrustedString`
167 /// [`UntrustedString`]: crate::util::string::UntrustedString
168 peer_msg: UntrustedString,
170 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
172 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
174 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
175 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
176 //TODO: split between CounterpartyInitiated/LocallyInitiated
178 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
179 /// commitment transaction came from our counterparty, but it may also have come from
180 /// a copy of our own `ChannelMonitor`.
181 CommitmentTxConfirmed,
182 /// The funding transaction failed to confirm in a timely manner on an inbound channel.
184 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
186 /// A developer-readable error message which we generated.
189 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
190 /// forget the channel entirely - we can attempt again if the peer reconnects.
192 /// This includes cases where we restarted prior to funding completion, including prior to the
193 /// initial [`ChannelMonitor`] persistence completing.
195 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
196 /// peer because of mutual incompatibility between us and our channel counterparty.
198 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
200 /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
201 /// the [`ChannelManager`] deserialized.
203 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
204 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
205 OutdatedChannelManager,
206 /// The counterparty requested a cooperative close of a channel that had not been funded yet.
207 /// The channel has been immediately closed.
208 CounterpartyCoopClosedUnfundedChannel,
209 /// Another channel in the same funding batch closed before the funding transaction
210 /// was ready to be broadcast.
214 impl core::fmt::Display for ClosureReason {
215 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
216 f.write_str("Channel closed because ")?;
218 ClosureReason::CounterpartyForceClosed { peer_msg } => {
219 f.write_fmt(format_args!("counterparty force-closed with message: {}", peer_msg))
221 ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
222 ClosureReason::CooperativeClosure => f.write_str("the channel was cooperatively closed"),
223 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
224 ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
225 ClosureReason::ProcessingError { err } => {
226 f.write_str("of an exception: ")?;
229 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
230 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
231 ClosureReason::CounterpartyCoopClosedUnfundedChannel => f.write_str("the peer requested the unfunded channel be closed"),
232 ClosureReason::FundingBatchClosure => f.write_str("another channel in the same funding batch closed"),
237 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
238 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
239 (1, FundingTimedOut) => {},
240 (2, HolderForceClosed) => {},
241 (6, CommitmentTxConfirmed) => {},
242 (4, CooperativeClosure) => {},
243 (8, ProcessingError) => { (1, err, required) },
244 (10, DisconnectedPeer) => {},
245 (12, OutdatedChannelManager) => {},
246 (13, CounterpartyCoopClosedUnfundedChannel) => {},
247 (15, FundingBatchClosure) => {}
250 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
251 #[derive(Clone, Debug, PartialEq, Eq)]
252 pub enum HTLCDestination {
253 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
254 /// there is insufficient capacity in our outbound channel.
256 /// The `node_id` of the next node. For backwards compatibility, this field is
257 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
258 /// counterparty node information.
259 node_id: Option<PublicKey>,
260 /// The outgoing `channel_id` between us and the next node.
261 channel_id: ChannelId,
263 /// Scenario where we are unsure of the next node to forward the HTLC to.
265 /// Short channel id we are requesting to forward an HTLC to.
266 requested_forward_scid: u64,
268 /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
271 /// Short channel id we are requesting to forward an HTLC to.
272 requested_forward_scid: u64
274 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
275 /// but is invalid for some reason, so we reject it.
277 /// Some of the reasons may include:
279 /// * Excess HTLCs for a payment that we have already fully received, over-paying for the
281 /// * The counterparty node modified the HTLC in transit,
282 /// * A probing attack where an intermediary node is trying to detect if we are the ultimate
283 /// recipient for a payment.
285 /// The payment hash of the payment we attempted to process.
286 payment_hash: PaymentHash
290 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
291 (0, NextHopChannel) => {
292 (0, node_id, required),
293 (2, channel_id, required),
295 (1, InvalidForward) => {
296 (0, requested_forward_scid, required),
298 (2, UnknownNextHop) => {
299 (0, requested_forward_scid, required),
301 (4, FailedPayment) => {
302 (0, payment_hash, required),
306 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
307 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
308 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
309 /// intercepts in upcoming work.
310 enum InterceptNextHop {
312 requested_next_hop_scid: u64,
316 impl_writeable_tlv_based_enum!(InterceptNextHop,
318 (0, requested_next_hop_scid, required),
322 /// The reason the payment failed. Used in [`Event::PaymentFailed`].
323 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
324 pub enum PaymentFailureReason {
325 /// The intended recipient rejected our payment.
327 /// The user chose to abandon this payment by calling [`ChannelManager::abandon_payment`].
329 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
331 /// We exhausted all of our retry attempts while trying to send the payment, or we
332 /// exhausted the [`Retry::Timeout`] if the user set one. If at any point a retry
333 /// attempt failed while being forwarded along the path, an [`Event::PaymentPathFailed`] will
334 /// have come before this.
336 /// [`Retry::Timeout`]: crate::ln::channelmanager::Retry::Timeout
338 /// The payment expired while retrying, based on the provided
339 /// [`PaymentParameters::expiry_time`].
341 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
343 /// We failed to find a route while retrying the payment.
345 /// This error should generally never happen. This likely means that there is a problem with
350 impl_writeable_tlv_based_enum!(PaymentFailureReason,
351 (0, RecipientRejected) => {},
352 (2, UserAbandoned) => {},
353 (4, RetriesExhausted) => {},
354 (6, PaymentExpired) => {},
355 (8, RouteNotFound) => {},
356 (10, UnexpectedError) => {}, ;
359 /// An Event which you should probably take some action in response to.
361 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
362 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
363 /// written as it makes no sense to respond to it after reconnecting to peers).
364 #[derive(Clone, Debug, PartialEq, Eq)]
366 /// Used to indicate that the client should generate a funding transaction with the given
367 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
368 /// Generated in [`ChannelManager`] message handling.
369 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
370 /// counterparty can steal your funds!
372 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
373 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
374 FundingGenerationReady {
375 /// The random channel_id we picked which you'll need to pass into
376 /// [`ChannelManager::funding_transaction_generated`].
378 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
379 temporary_channel_id: ChannelId,
380 /// The counterparty's node_id, which you'll need to pass back into
381 /// [`ChannelManager::funding_transaction_generated`].
383 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
384 counterparty_node_id: PublicKey,
385 /// The value, in satoshis, that the output should have.
386 channel_value_satoshis: u64,
387 /// The script which should be used in the transaction output.
388 output_script: ScriptBuf,
389 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
390 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
391 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
392 /// `user_channel_id` will be randomized for an inbound channel. This may be zero for objects
393 /// serialized with LDK versions prior to 0.0.113.
395 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
396 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
397 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
398 user_channel_id: u128,
400 /// Indicates that we've been offered a payment and it needs to be claimed via calling
401 /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
403 /// Note that if the preimage is not known, you should call
404 /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
405 /// to free up resources for this HTLC and avoid network congestion.
407 /// If [`Event::PaymentClaimable::onion_fields`] is `Some`, and includes custom TLVs with even type
408 /// numbers, you should use [`ChannelManager::fail_htlc_backwards_with_reason`] with
409 /// [`FailureCode::InvalidOnionPayload`] if you fail to understand and handle the contents, or
410 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`] upon successful handling.
411 /// If you don't intend to check for custom TLVs, you can simply use
412 /// [`ChannelManager::claim_funds`], which will automatically fail back even custom TLVs.
414 /// If you fail to call [`ChannelManager::claim_funds`],
415 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`],
416 /// [`ChannelManager::fail_htlc_backwards`], or
417 /// [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will
418 /// be automatically failed.
421 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
422 /// `PaymentClaimable` events may be generated for the same payment. In such a case it is
423 /// polite (and required in the lightning specification) to fail the payment the second time
424 /// and give the sender their money back rather than accepting double payment.
427 /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
429 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
430 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`]: crate::ln::channelmanager::ChannelManager::claim_funds_with_known_custom_tlvs
431 /// [`FailureCode::InvalidOnionPayload`]: crate::ln::channelmanager::FailureCode::InvalidOnionPayload
432 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
433 /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
435 /// The node that will receive the payment after it has been claimed.
436 /// This is useful to identify payments received via [phantom nodes].
437 /// This field will always be filled in when the event was generated by LDK versions
438 /// 0.0.113 and above.
440 /// [phantom nodes]: crate::sign::PhantomKeysManager
441 receiver_node_id: Option<PublicKey>,
442 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
443 /// not stop you from registering duplicate payment hashes for inbound payments.
444 payment_hash: PaymentHash,
445 /// The fields in the onion which were received with each HTLC. Only fields which were
446 /// identical in each HTLC involved in the payment will be included here.
448 /// Payments received on LDK versions prior to 0.0.115 will have this field unset.
449 onion_fields: Option<RecipientOnionFields>,
450 /// The value, in thousandths of a satoshi, that this payment is claimable for. May be greater
451 /// than the invoice amount.
453 /// May be less than the invoice amount if [`ChannelConfig::accept_underpaying_htlcs`] is set
454 /// and the previous hop took an extra fee.
457 /// If [`ChannelConfig::accept_underpaying_htlcs`] is set and you claim without verifying this
458 /// field, you may lose money!
460 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
462 /// The value, in thousands of a satoshi, that was skimmed off of this payment as an extra fee
463 /// taken by our channel counterparty.
465 /// Will always be 0 unless [`ChannelConfig::accept_underpaying_htlcs`] is set.
467 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
468 counterparty_skimmed_fee_msat: u64,
469 /// Information for claiming this received payment, based on whether the purpose of the
470 /// payment is to pay an invoice or to send a spontaneous payment.
471 purpose: PaymentPurpose,
472 /// The `channel_id` indicating over which channel we received the payment.
473 via_channel_id: Option<ChannelId>,
474 /// The `user_channel_id` indicating over which channel we received the payment.
475 via_user_channel_id: Option<u128>,
476 /// The block height at which this payment will be failed back and will no longer be
477 /// eligible for claiming.
479 /// Prior to this height, a call to [`ChannelManager::claim_funds`] is guaranteed to
480 /// succeed, however you should wait for [`Event::PaymentClaimed`] to be sure.
482 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
483 claim_deadline: Option<u32>,
485 /// Indicates a payment has been claimed and we've received money!
487 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
488 /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
489 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
490 /// [`Event::PaymentClaimable`] event.
493 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
494 /// `PaymentClaimable` events may be generated for the same payment. If you then call
495 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
496 /// multiple `PaymentClaimed` events.
498 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
500 /// The node that received the payment.
501 /// This is useful to identify payments which were received via [phantom nodes].
502 /// This field will always be filled in when the event was generated by LDK versions
503 /// 0.0.113 and above.
505 /// [phantom nodes]: crate::sign::PhantomKeysManager
506 receiver_node_id: Option<PublicKey>,
507 /// The payment hash of the claimed payment. Note that LDK will not stop you from
508 /// registering duplicate payment hashes for inbound payments.
509 payment_hash: PaymentHash,
510 /// The value, in thousandths of a satoshi, that this payment is for. May be greater than the
513 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
514 /// spontaneous payment.
515 purpose: PaymentPurpose,
516 /// The HTLCs that comprise the claimed payment. This will be empty for events serialized prior
517 /// to LDK version 0.0.117.
518 htlcs: Vec<ClaimedHTLC>,
519 /// The sender-intended sum total of all the MPP parts. This will be `None` for events
520 /// serialized prior to LDK version 0.0.117.
521 sender_intended_total_msat: Option<u64>,
523 /// Indicates a request for an invoice failed to yield a response in a reasonable amount of time
524 /// or was explicitly abandoned by [`ChannelManager::abandon_payment`]. This may be for an
525 /// [`InvoiceRequest`] sent for an [`Offer`] or for a [`Refund`] that hasn't been redeemed.
527 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
528 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
529 /// [`Offer`]: crate::offers::offer::Offer
530 /// [`Refund`]: crate::offers::refund::Refund
531 InvoiceRequestFailed {
532 /// The `payment_id` to have been associated with payment for the requested invoice.
533 payment_id: PaymentId,
535 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
536 /// and we got back the payment preimage for it).
538 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
539 /// event. In this situation, you SHOULD treat this payment as having succeeded.
541 /// The `payment_id` passed to [`ChannelManager::send_payment`].
543 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
544 payment_id: Option<PaymentId>,
545 /// The preimage to the hash given to ChannelManager::send_payment.
546 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
547 /// store it somehow!
548 payment_preimage: PaymentPreimage,
549 /// The hash that was given to [`ChannelManager::send_payment`].
551 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
552 payment_hash: PaymentHash,
553 /// The total fee which was spent at intermediate hops in this payment, across all paths.
555 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
556 /// overpayment to the recipient node.
558 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
559 /// overstate the amount paid, though this is unlikely.
561 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
562 fee_paid_msat: Option<u64>,
564 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
565 /// provide failure information for each path attempt in the payment, including retries.
567 /// This event is provided once there are no further pending HTLCs for the payment and the
568 /// payment is no longer retryable, due either to the [`Retry`] provided or
569 /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
571 /// In exceedingly rare cases, it is possible that an [`Event::PaymentFailed`] is generated for
572 /// a payment after an [`Event::PaymentSent`] event for this same payment has already been
573 /// received and processed. In this case, the [`Event::PaymentFailed`] event MUST be ignored,
574 /// and the payment MUST be treated as having succeeded.
576 /// [`Retry`]: crate::ln::channelmanager::Retry
577 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
579 /// The `payment_id` passed to [`ChannelManager::send_payment`].
581 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
582 payment_id: PaymentId,
583 /// The hash that was given to [`ChannelManager::send_payment`].
585 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
586 payment_hash: PaymentHash,
587 /// The reason the payment failed. This is only `None` for events generated or serialized
588 /// by versions prior to 0.0.115.
589 reason: Option<PaymentFailureReason>,
591 /// Indicates that a path for an outbound payment was successful.
593 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
594 /// [`Event::PaymentSent`] for obtaining the payment preimage.
595 PaymentPathSuccessful {
596 /// The `payment_id` passed to [`ChannelManager::send_payment`].
598 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
599 payment_id: PaymentId,
600 /// The hash that was given to [`ChannelManager::send_payment`].
602 /// This will be `Some` for all payments which completed on LDK 0.0.104 or later.
604 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
605 payment_hash: Option<PaymentHash>,
606 /// The payment path that was successful.
608 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
611 /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
614 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
615 /// [`Event::PaymentFailed`].
617 /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
620 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
622 /// The `payment_id` passed to [`ChannelManager::send_payment`].
624 /// This will be `Some` for all payment paths which failed on LDK 0.0.103 or later.
626 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
627 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
628 payment_id: Option<PaymentId>,
629 /// The hash that was given to [`ChannelManager::send_payment`].
631 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
632 payment_hash: PaymentHash,
633 /// Indicates the payment was rejected for some reason by the recipient. This implies that
634 /// the payment has failed, not just the route in question. If this is not set, the payment may
635 /// be retried via a different route.
636 payment_failed_permanently: bool,
637 /// Extra error details based on the failure type. May contain an update that needs to be
638 /// applied to the [`NetworkGraph`].
640 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
641 failure: PathFailure,
642 /// The payment path that failed.
644 /// The channel responsible for the failed payment path.
646 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
647 /// may not refer to a channel in the public network graph. These aliases may also collide
648 /// with channels in the public network graph.
650 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
651 /// retried. May be `None` for older [`Event`] serializations.
652 short_channel_id: Option<u64>,
654 error_code: Option<u16>,
656 error_data: Option<Vec<u8>>,
658 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
660 /// The id returned by [`ChannelManager::send_probe`].
662 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
663 payment_id: PaymentId,
664 /// The hash generated by [`ChannelManager::send_probe`].
666 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
667 payment_hash: PaymentHash,
668 /// The payment path that was successful.
671 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
673 /// The id returned by [`ChannelManager::send_probe`].
675 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
676 payment_id: PaymentId,
677 /// The hash generated by [`ChannelManager::send_probe`].
679 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
680 payment_hash: PaymentHash,
681 /// The payment path that failed.
683 /// The channel responsible for the failed probe.
685 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
686 /// may not refer to a channel in the public network graph. These aliases may also collide
687 /// with channels in the public network graph.
688 short_channel_id: Option<u64>,
690 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
691 /// a time in the future.
693 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
694 PendingHTLCsForwardable {
695 /// The minimum amount of time that should be waited prior to calling
696 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
697 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
698 /// now + 5*time_forwardable).
699 time_forwardable: Duration,
701 /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
702 /// you've encoded an intercept scid in the receiver's invoice route hints using
703 /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
705 /// [`ChannelManager::forward_intercepted_htlc`] or
706 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
707 /// their docs for more information.
709 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
710 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
711 /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
712 /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
714 /// An id to help LDK identify which HTLC is being forwarded or failed.
715 intercept_id: InterceptId,
716 /// The fake scid that was programmed as the next hop's scid, generated using
717 /// [`ChannelManager::get_intercept_scid`].
719 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
720 requested_next_hop_scid: u64,
721 /// The payment hash used for this HTLC.
722 payment_hash: PaymentHash,
723 /// How many msats were received on the inbound edge of this HTLC.
724 inbound_amount_msat: u64,
725 /// How many msats the payer intended to route to the next node. Depending on the reason you are
726 /// intercepting this payment, you might take a fee by forwarding less than this amount.
727 /// Forwarding less than this amount may break compatibility with LDK versions prior to 0.0.116.
729 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
730 /// check that whatever fee you want has been included here or subtract it as required. Further,
731 /// LDK will not stop you from forwarding more than you received.
732 expected_outbound_amount_msat: u64,
734 /// Used to indicate that an output which you should know how to spend was confirmed on chain
735 /// and is now spendable.
736 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
737 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
738 /// somewhere and spend them when you create on-chain transactions.
740 /// The outputs which you should store as spendable by you.
741 outputs: Vec<SpendableOutputDescriptor>,
742 /// The `channel_id` indicating which channel the spendable outputs belong to.
744 /// This will always be `Some` for events generated by LDK versions 0.0.117 and above.
745 channel_id: Option<ChannelId>,
747 /// This event is generated when a payment has been successfully forwarded through us and a
748 /// forwarding fee earned.
750 /// The incoming channel between the previous node and us. This is only `None` for events
751 /// generated or serialized by versions prior to 0.0.107.
752 prev_channel_id: Option<ChannelId>,
753 /// The outgoing channel between the next node and us. This is only `None` for events
754 /// generated or serialized by versions prior to 0.0.107.
755 next_channel_id: Option<ChannelId>,
756 /// The fee, in milli-satoshis, which was earned as a result of the payment.
758 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
759 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
760 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
761 /// claimed the full value in millisatoshis from the source. In this case,
762 /// `claim_from_onchain_tx` will be set.
764 /// If the channel which sent us the payment has been force-closed, we will claim the funds
765 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
766 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
767 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
769 fee_earned_msat: Option<u64>,
770 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
772 claim_from_onchain_tx: bool,
773 /// The final amount forwarded, in milli-satoshis, after the fee is deducted.
775 /// The caveat described above the `fee_earned_msat` field applies here as well.
776 outbound_amount_forwarded_msat: Option<u64>,
778 /// Used to indicate that a channel with the given `channel_id` is being opened and pending
779 /// confirmation on-chain.
781 /// This event is emitted when the funding transaction has been signed and is broadcast to the
782 /// network. For 0conf channels it will be immediately followed by the corresponding
783 /// [`Event::ChannelReady`] event.
785 /// The `channel_id` of the channel that is pending confirmation.
786 channel_id: ChannelId,
787 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
788 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
789 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
790 /// `user_channel_id` will be randomized for an inbound channel.
792 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
793 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
794 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
795 user_channel_id: u128,
796 /// The `temporary_channel_id` this channel used to be known by during channel establishment.
798 /// Will be `None` for channels created prior to LDK version 0.0.115.
799 former_temporary_channel_id: Option<ChannelId>,
800 /// The `node_id` of the channel counterparty.
801 counterparty_node_id: PublicKey,
802 /// The outpoint of the channel's funding transaction.
803 funding_txo: OutPoint,
805 /// Used to indicate that a channel with the given `channel_id` is ready to
806 /// be used. This event is emitted either when the funding transaction has been confirmed
807 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
810 /// The `channel_id` of the channel that is ready.
811 channel_id: ChannelId,
812 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
813 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
814 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
815 /// `user_channel_id` will be randomized for an inbound channel.
817 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
818 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
819 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
820 user_channel_id: u128,
821 /// The `node_id` of the channel counterparty.
822 counterparty_node_id: PublicKey,
823 /// The features that this channel will operate with.
824 channel_type: ChannelTypeFeatures,
826 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
827 /// process of closure.
829 /// Note that this event is only triggered for accepted channels: if the
830 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true and the channel is
831 /// rejected, no `ChannelClosed` event will be sent.
833 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
834 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
836 /// The `channel_id` of the channel which has been closed. Note that on-chain transactions
837 /// resolving the channel are likely still awaiting confirmation.
838 channel_id: ChannelId,
839 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
840 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
841 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
842 /// `user_channel_id` will be randomized for inbound channels.
843 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
844 /// zero for objects serialized with LDK versions prior to 0.0.102.
846 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
847 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
848 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
849 user_channel_id: u128,
850 /// The reason the channel was closed.
851 reason: ClosureReason,
852 /// Counterparty in the closed channel.
854 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
855 counterparty_node_id: Option<PublicKey>,
856 /// Channel capacity of the closing channel (sats).
858 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
859 channel_capacity_sats: Option<u64>,
861 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
862 /// inputs for another purpose.
864 /// This event is not guaranteed to be generated for channels that are closed due to a restart.
866 /// The channel_id of the channel which has been closed.
867 channel_id: ChannelId,
868 /// The full transaction received from the user
869 transaction: Transaction
871 /// Indicates a request to open a new channel by a peer.
873 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the request,
874 /// call [`ChannelManager::force_close_without_broadcasting_txn`]. Note that a ['ChannelClosed`]
875 /// event will _not_ be triggered if the channel is rejected.
877 /// The event is only triggered when a new open channel request is received and the
878 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
880 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
881 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
882 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
884 /// The temporary channel ID of the channel requested to be opened.
886 /// When responding to the request, the `temporary_channel_id` should be passed
887 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
888 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
890 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
891 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
892 temporary_channel_id: ChannelId,
893 /// The node_id of the counterparty requesting to open the channel.
895 /// When responding to the request, the `counterparty_node_id` should be passed
896 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
897 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
900 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
901 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
902 counterparty_node_id: PublicKey,
903 /// The channel value of the requested channel.
904 funding_satoshis: u64,
905 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
907 /// The features that this channel will operate with. If you reject the channel, a
908 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
911 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
912 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
915 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
916 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
917 /// 0.0.107. Channels setting this type also need to get manually accepted via
918 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
919 /// or will be rejected otherwise.
921 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
922 channel_type: ChannelTypeFeatures,
924 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
927 /// Some scenarios where this event may be sent include:
928 /// * Insufficient capacity in the outbound channel
929 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
930 /// * When an unknown SCID is requested for forwarding a payment.
931 /// * Expected MPP amount has already been reached
932 /// * The HTLC has timed out
934 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
935 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
937 /// The channel over which the HTLC was received.
938 prev_channel_id: ChannelId,
939 /// Destination of the HTLC that failed to be processed.
940 failed_next_destination: HTLCDestination,
942 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
943 /// requires confirmed external funds to be readily available to spend.
945 /// LDK does not currently generate this event unless the
946 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`] config flag is set to true.
947 /// It is limited to the scope of channels with anchor outputs.
949 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`]: crate::util::config::ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx
950 BumpTransaction(BumpTransactionEvent),
953 impl Writeable for Event {
954 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
956 &Event::FundingGenerationReady { .. } => {
958 // We never write out FundingGenerationReady events as, upon disconnection, peers
959 // drop any channels which have not yet exchanged funding_signed.
961 &Event::PaymentClaimable { ref payment_hash, ref amount_msat, counterparty_skimmed_fee_msat,
962 ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id,
963 ref claim_deadline, ref onion_fields
966 let mut payment_secret = None;
967 let payment_preimage;
969 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
970 payment_secret = Some(secret);
971 payment_preimage = *preimage;
973 PaymentPurpose::SpontaneousPayment(preimage) => {
974 payment_preimage = Some(*preimage);
977 let skimmed_fee_opt = if counterparty_skimmed_fee_msat == 0 { None }
978 else { Some(counterparty_skimmed_fee_msat) };
979 write_tlv_fields!(writer, {
980 (0, payment_hash, required),
981 (1, receiver_node_id, option),
982 (2, payment_secret, option),
983 (3, via_channel_id, option),
984 (4, amount_msat, required),
985 (5, via_user_channel_id, option),
986 // Type 6 was `user_payment_id` on 0.0.103 and earlier
987 (7, claim_deadline, option),
988 (8, payment_preimage, option),
989 (9, onion_fields, option),
990 (10, skimmed_fee_opt, option),
993 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
995 write_tlv_fields!(writer, {
996 (0, payment_preimage, required),
997 (1, payment_hash, required),
998 (3, payment_id, option),
999 (5, fee_paid_msat, option),
1002 &Event::PaymentPathFailed {
1003 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
1004 ref path, ref short_channel_id,
1012 error_code.write(writer)?;
1014 error_data.write(writer)?;
1015 write_tlv_fields!(writer, {
1016 (0, payment_hash, required),
1017 (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
1018 (2, payment_failed_permanently, required),
1019 (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
1020 (4, path.blinded_tail, option),
1021 (5, path.hops, required_vec),
1022 (7, short_channel_id, option),
1023 (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
1024 (11, payment_id, option),
1025 (13, failure, required),
1028 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
1030 // Note that we now ignore these on the read end as we'll re-generate them in
1031 // ChannelManager, we write them here only for backwards compatibility.
1033 &Event::SpendableOutputs { ref outputs, channel_id } => {
1035 write_tlv_fields!(writer, {
1036 (0, WithoutLength(outputs), required),
1037 (1, channel_id, option),
1040 &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1042 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1043 write_tlv_fields!(writer, {
1044 (0, intercept_id, required),
1045 (2, intercept_scid, required),
1046 (4, payment_hash, required),
1047 (6, inbound_amount_msat, required),
1048 (8, expected_outbound_amount_msat, required),
1051 &Event::PaymentForwarded {
1052 fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
1053 next_channel_id, outbound_amount_forwarded_msat
1056 write_tlv_fields!(writer, {
1057 (0, fee_earned_msat, option),
1058 (1, prev_channel_id, option),
1059 (2, claim_from_onchain_tx, required),
1060 (3, next_channel_id, option),
1061 (5, outbound_amount_forwarded_msat, option),
1064 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason,
1065 ref counterparty_node_id, ref channel_capacity_sats
1068 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1069 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1070 // separate u64 values.
1071 let user_channel_id_low = *user_channel_id as u64;
1072 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1073 write_tlv_fields!(writer, {
1074 (0, channel_id, required),
1075 (1, user_channel_id_low, required),
1076 (2, reason, required),
1077 (3, user_channel_id_high, required),
1078 (5, counterparty_node_id, option),
1079 (7, channel_capacity_sats, option),
1082 &Event::DiscardFunding { ref channel_id, ref transaction } => {
1083 11u8.write(writer)?;
1084 write_tlv_fields!(writer, {
1085 (0, channel_id, required),
1086 (2, transaction, required)
1089 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1090 13u8.write(writer)?;
1091 write_tlv_fields!(writer, {
1092 (0, payment_id, required),
1093 (2, payment_hash, option),
1094 (4, path.hops, required_vec),
1095 (6, path.blinded_tail, option),
1098 &Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
1099 15u8.write(writer)?;
1100 write_tlv_fields!(writer, {
1101 (0, payment_id, required),
1102 (1, reason, option),
1103 (2, payment_hash, required),
1106 &Event::OpenChannelRequest { .. } => {
1107 17u8.write(writer)?;
1108 // We never write the OpenChannelRequest events as, upon disconnection, peers
1109 // drop any channels which have not yet exchanged funding_signed.
1111 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref htlcs, ref sender_intended_total_msat } => {
1112 19u8.write(writer)?;
1113 write_tlv_fields!(writer, {
1114 (0, payment_hash, required),
1115 (1, receiver_node_id, option),
1116 (2, purpose, required),
1117 (4, amount_msat, required),
1118 (5, *htlcs, optional_vec),
1119 (7, sender_intended_total_msat, option),
1122 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1123 21u8.write(writer)?;
1124 write_tlv_fields!(writer, {
1125 (0, payment_id, required),
1126 (2, payment_hash, required),
1127 (4, path.hops, required_vec),
1128 (6, path.blinded_tail, option),
1131 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1132 23u8.write(writer)?;
1133 write_tlv_fields!(writer, {
1134 (0, payment_id, required),
1135 (2, payment_hash, required),
1136 (4, path.hops, required_vec),
1137 (6, short_channel_id, option),
1138 (8, path.blinded_tail, option),
1141 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1142 25u8.write(writer)?;
1143 write_tlv_fields!(writer, {
1144 (0, prev_channel_id, required),
1145 (2, failed_next_destination, required),
1148 &Event::BumpTransaction(ref event)=> {
1149 27u8.write(writer)?;
1151 // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1152 // upon restarting anyway if they remain unresolved.
1153 BumpTransactionEvent::ChannelClose { .. } => {}
1154 BumpTransactionEvent::HTLCResolution { .. } => {}
1156 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1158 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1159 29u8.write(writer)?;
1160 write_tlv_fields!(writer, {
1161 (0, channel_id, required),
1162 (2, user_channel_id, required),
1163 (4, counterparty_node_id, required),
1164 (6, channel_type, required),
1167 &Event::ChannelPending { ref channel_id, ref user_channel_id, ref former_temporary_channel_id, ref counterparty_node_id, ref funding_txo } => {
1168 31u8.write(writer)?;
1169 write_tlv_fields!(writer, {
1170 (0, channel_id, required),
1171 (2, user_channel_id, required),
1172 (4, former_temporary_channel_id, required),
1173 (6, counterparty_node_id, required),
1174 (8, funding_txo, required),
1177 &Event::InvoiceRequestFailed { ref payment_id } => {
1178 33u8.write(writer)?;
1179 write_tlv_fields!(writer, {
1180 (0, payment_id, required),
1183 // Note that, going forward, all new events must only write data inside of
1184 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1185 // data via `write_tlv_fields`.
1190 impl MaybeReadable for Event {
1191 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1192 match Readable::read(reader)? {
1193 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
1194 // unlike all other events, thus we return immediately here.
1198 let mut payment_hash = PaymentHash([0; 32]);
1199 let mut payment_preimage = None;
1200 let mut payment_secret = None;
1201 let mut amount_msat = 0;
1202 let mut counterparty_skimmed_fee_msat_opt = None;
1203 let mut receiver_node_id = None;
1204 let mut _user_payment_id = None::<u64>; // Used in 0.0.103 and earlier, no longer written in 0.0.116+.
1205 let mut via_channel_id = None;
1206 let mut claim_deadline = None;
1207 let mut via_user_channel_id = None;
1208 let mut onion_fields = None;
1209 read_tlv_fields!(reader, {
1210 (0, payment_hash, required),
1211 (1, receiver_node_id, option),
1212 (2, payment_secret, option),
1213 (3, via_channel_id, option),
1214 (4, amount_msat, required),
1215 (5, via_user_channel_id, option),
1216 (6, _user_payment_id, option),
1217 (7, claim_deadline, option),
1218 (8, payment_preimage, option),
1219 (9, onion_fields, option),
1220 (10, counterparty_skimmed_fee_msat_opt, option),
1222 let purpose = match payment_secret {
1223 Some(secret) => PaymentPurpose::InvoicePayment {
1225 payment_secret: secret
1227 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1228 None => return Err(msgs::DecodeError::InvalidValue),
1230 Ok(Some(Event::PaymentClaimable {
1234 counterparty_skimmed_fee_msat: counterparty_skimmed_fee_msat_opt.unwrap_or(0),
1237 via_user_channel_id,
1246 let mut payment_preimage = PaymentPreimage([0; 32]);
1247 let mut payment_hash = None;
1248 let mut payment_id = None;
1249 let mut fee_paid_msat = None;
1250 read_tlv_fields!(reader, {
1251 (0, payment_preimage, required),
1252 (1, payment_hash, option),
1253 (3, payment_id, option),
1254 (5, fee_paid_msat, option),
1256 if payment_hash.is_none() {
1257 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()));
1259 Ok(Some(Event::PaymentSent {
1262 payment_hash: payment_hash.unwrap(),
1271 let error_code = Readable::read(reader)?;
1273 let error_data = Readable::read(reader)?;
1274 let mut payment_hash = PaymentHash([0; 32]);
1275 let mut payment_failed_permanently = false;
1276 let mut network_update = None;
1277 let mut blinded_tail: Option<BlindedTail> = None;
1278 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1279 let mut short_channel_id = None;
1280 let mut payment_id = None;
1281 let mut failure_opt = None;
1282 read_tlv_fields!(reader, {
1283 (0, payment_hash, required),
1284 (1, network_update, upgradable_option),
1285 (2, payment_failed_permanently, required),
1286 (4, blinded_tail, option),
1287 // Added as a part of LDK 0.0.101 and always filled in since.
1288 // Defaults to an empty Vec, though likely should have been `Option`al.
1289 (5, path, optional_vec),
1290 (7, short_channel_id, option),
1291 (11, payment_id, option),
1292 (13, failure_opt, upgradable_option),
1294 let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1295 Ok(Some(Event::PaymentPathFailed {
1298 payment_failed_permanently,
1300 path: Path { hops: path.unwrap(), blinded_tail },
1313 let mut outputs = WithoutLength(Vec::new());
1314 let mut channel_id: Option<ChannelId> = None;
1315 read_tlv_fields!(reader, {
1316 (0, outputs, required),
1317 (1, channel_id, option),
1319 Ok(Some(Event::SpendableOutputs { outputs: outputs.0, channel_id }))
1324 let mut payment_hash = PaymentHash([0; 32]);
1325 let mut intercept_id = InterceptId([0; 32]);
1326 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1327 let mut inbound_amount_msat = 0;
1328 let mut expected_outbound_amount_msat = 0;
1329 read_tlv_fields!(reader, {
1330 (0, intercept_id, required),
1331 (2, requested_next_hop_scid, required),
1332 (4, payment_hash, required),
1333 (6, inbound_amount_msat, required),
1334 (8, expected_outbound_amount_msat, required),
1336 let next_scid = match requested_next_hop_scid {
1337 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1339 Ok(Some(Event::HTLCIntercepted {
1341 requested_next_hop_scid: next_scid,
1342 inbound_amount_msat,
1343 expected_outbound_amount_msat,
1349 let mut fee_earned_msat = None;
1350 let mut prev_channel_id = None;
1351 let mut claim_from_onchain_tx = false;
1352 let mut next_channel_id = None;
1353 let mut outbound_amount_forwarded_msat = None;
1354 read_tlv_fields!(reader, {
1355 (0, fee_earned_msat, option),
1356 (1, prev_channel_id, option),
1357 (2, claim_from_onchain_tx, required),
1358 (3, next_channel_id, option),
1359 (5, outbound_amount_forwarded_msat, option),
1361 Ok(Some(Event::PaymentForwarded {
1362 fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id,
1363 outbound_amount_forwarded_msat
1370 let mut channel_id = ChannelId::new_zero();
1371 let mut reason = UpgradableRequired(None);
1372 let mut user_channel_id_low_opt: Option<u64> = None;
1373 let mut user_channel_id_high_opt: Option<u64> = None;
1374 let mut counterparty_node_id = None;
1375 let mut channel_capacity_sats = None;
1376 read_tlv_fields!(reader, {
1377 (0, channel_id, required),
1378 (1, user_channel_id_low_opt, option),
1379 (2, reason, upgradable_required),
1380 (3, user_channel_id_high_opt, option),
1381 (5, counterparty_node_id, option),
1382 (7, channel_capacity_sats, option),
1385 // `user_channel_id` used to be a single u64 value. In order to remain
1386 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1387 // as two separate u64 values.
1388 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1389 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1391 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required),
1392 counterparty_node_id, channel_capacity_sats }))
1398 let mut channel_id = ChannelId::new_zero();
1399 let mut transaction = Transaction{ version: 2, lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
1400 read_tlv_fields!(reader, {
1401 (0, channel_id, required),
1402 (2, transaction, required),
1404 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1410 _init_and_read_len_prefixed_tlv_fields!(reader, {
1411 (0, payment_id, required),
1412 (2, payment_hash, option),
1413 (4, path, required_vec),
1414 (6, blinded_tail, option),
1416 Ok(Some(Event::PaymentPathSuccessful {
1417 payment_id: payment_id.0.unwrap(),
1419 path: Path { hops: path, blinded_tail },
1426 let mut payment_hash = PaymentHash([0; 32]);
1427 let mut payment_id = PaymentId([0; 32]);
1428 let mut reason = None;
1429 read_tlv_fields!(reader, {
1430 (0, payment_id, required),
1431 (1, reason, upgradable_option),
1432 (2, payment_hash, required),
1434 Ok(Some(Event::PaymentFailed {
1443 // Value 17 is used for `Event::OpenChannelRequest`.
1448 let mut payment_hash = PaymentHash([0; 32]);
1449 let mut purpose = UpgradableRequired(None);
1450 let mut amount_msat = 0;
1451 let mut receiver_node_id = None;
1452 let mut htlcs: Option<Vec<ClaimedHTLC>> = Some(vec![]);
1453 let mut sender_intended_total_msat: Option<u64> = None;
1454 read_tlv_fields!(reader, {
1455 (0, payment_hash, required),
1456 (1, receiver_node_id, option),
1457 (2, purpose, upgradable_required),
1458 (4, amount_msat, required),
1459 (5, htlcs, optional_vec),
1460 (7, sender_intended_total_msat, option),
1462 Ok(Some(Event::PaymentClaimed {
1465 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1467 htlcs: htlcs.unwrap_or(vec![]),
1468 sender_intended_total_msat,
1475 _init_and_read_len_prefixed_tlv_fields!(reader, {
1476 (0, payment_id, required),
1477 (2, payment_hash, required),
1478 (4, path, required_vec),
1479 (6, blinded_tail, option),
1481 Ok(Some(Event::ProbeSuccessful {
1482 payment_id: payment_id.0.unwrap(),
1483 payment_hash: payment_hash.0.unwrap(),
1484 path: Path { hops: path, blinded_tail },
1491 _init_and_read_len_prefixed_tlv_fields!(reader, {
1492 (0, payment_id, required),
1493 (2, payment_hash, required),
1494 (4, path, required_vec),
1495 (6, short_channel_id, option),
1496 (8, blinded_tail, option),
1498 Ok(Some(Event::ProbeFailed {
1499 payment_id: payment_id.0.unwrap(),
1500 payment_hash: payment_hash.0.unwrap(),
1501 path: Path { hops: path, blinded_tail },
1509 let mut prev_channel_id = ChannelId::new_zero();
1510 let mut failed_next_destination_opt = UpgradableRequired(None);
1511 read_tlv_fields!(reader, {
1512 (0, prev_channel_id, required),
1513 (2, failed_next_destination_opt, upgradable_required),
1515 Ok(Some(Event::HTLCHandlingFailed {
1517 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1525 let mut channel_id = ChannelId::new_zero();
1526 let mut user_channel_id: u128 = 0;
1527 let mut counterparty_node_id = RequiredWrapper(None);
1528 let mut channel_type = RequiredWrapper(None);
1529 read_tlv_fields!(reader, {
1530 (0, channel_id, required),
1531 (2, user_channel_id, required),
1532 (4, counterparty_node_id, required),
1533 (6, channel_type, required),
1536 Ok(Some(Event::ChannelReady {
1539 counterparty_node_id: counterparty_node_id.0.unwrap(),
1540 channel_type: channel_type.0.unwrap()
1547 let mut channel_id = ChannelId::new_zero();
1548 let mut user_channel_id: u128 = 0;
1549 let mut former_temporary_channel_id = None;
1550 let mut counterparty_node_id = RequiredWrapper(None);
1551 let mut funding_txo = RequiredWrapper(None);
1552 read_tlv_fields!(reader, {
1553 (0, channel_id, required),
1554 (2, user_channel_id, required),
1555 (4, former_temporary_channel_id, required),
1556 (6, counterparty_node_id, required),
1557 (8, funding_txo, required),
1560 Ok(Some(Event::ChannelPending {
1563 former_temporary_channel_id,
1564 counterparty_node_id: counterparty_node_id.0.unwrap(),
1565 funding_txo: funding_txo.0.unwrap()
1572 _init_and_read_len_prefixed_tlv_fields!(reader, {
1573 (0, payment_id, required),
1575 Ok(Some(Event::InvoiceRequestFailed {
1576 payment_id: payment_id.0.unwrap(),
1581 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1582 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1584 x if x % 2 == 1 => {
1585 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1586 // which prefixes the whole thing with a length BigSize. Because the event is
1587 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1588 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1589 // exactly the number of bytes specified, ignoring them entirely.
1590 let tlv_len: BigSize = Readable::read(reader)?;
1591 FixedLengthReader::new(reader, tlv_len.0)
1592 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1595 _ => Err(msgs::DecodeError::InvalidValue)
1600 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1601 /// broadcast to most peers).
1602 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1603 #[derive(Clone, Debug)]
1604 #[cfg_attr(test, derive(PartialEq))]
1605 pub enum MessageSendEvent {
1606 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1607 /// message provided to the given peer.
1609 /// The node_id of the node which should receive this message
1611 /// The message which should be sent.
1612 msg: msgs::AcceptChannel,
1614 /// Used to indicate that we've accepted a V2 channel open and should send the accept_channel2
1615 /// message provided to the given peer.
1616 SendAcceptChannelV2 {
1617 /// The node_id of the node which should receive this message
1619 /// The message which should be sent.
1620 msg: msgs::AcceptChannelV2,
1622 /// Used to indicate that we've initiated a channel open and should send the open_channel
1623 /// message provided to the given peer.
1625 /// The node_id of the node which should receive this message
1627 /// The message which should be sent.
1628 msg: msgs::OpenChannel,
1630 /// Used to indicate that we've initiated a V2 channel open and should send the open_channel2
1631 /// message provided to the given peer.
1633 /// The node_id of the node which should receive this message
1635 /// The message which should be sent.
1636 msg: msgs::OpenChannelV2,
1638 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1639 SendFundingCreated {
1640 /// The node_id of the node which should receive this message
1642 /// The message which should be sent.
1643 msg: msgs::FundingCreated,
1645 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1647 /// The node_id of the node which should receive this message
1649 /// The message which should be sent.
1650 msg: msgs::FundingSigned,
1652 /// Used to indicate that a stfu message should be sent to the peer with the given node id.
1654 /// The node_id of the node which should receive this message
1656 /// The message which should be sent.
1659 /// Used to indicate that a splice message should be sent to the peer with the given node id.
1661 /// The node_id of the node which should receive this message
1663 /// The message which should be sent.
1666 /// Used to indicate that a splice_ack message should be sent to the peer with the given node id.
1668 /// The node_id of the node which should receive this message
1670 /// The message which should be sent.
1671 msg: msgs::SpliceAck,
1673 /// Used to indicate that a splice_locked message should be sent to the peer with the given node id.
1675 /// The node_id of the node which should receive this message
1677 /// The message which should be sent.
1678 msg: msgs::SpliceLocked,
1680 /// Used to indicate that a tx_add_input message should be sent to the peer with the given node_id.
1682 /// The node_id of the node which should receive this message
1684 /// The message which should be sent.
1685 msg: msgs::TxAddInput,
1687 /// Used to indicate that a tx_add_output 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::TxAddOutput,
1694 /// Used to indicate that a tx_remove_input 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::TxRemoveInput,
1701 /// Used to indicate that a tx_remove_output message should be sent to the peer with the given node_id.
1702 SendTxRemoveOutput {
1703 /// The node_id of the node which should receive this message
1705 /// The message which should be sent.
1706 msg: msgs::TxRemoveOutput,
1708 /// Used to indicate that a tx_complete 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::TxComplete,
1715 /// Used to indicate that a tx_signatures message should be sent to the peer with the given node_id.
1717 /// The node_id of the node which should receive this message
1719 /// The message which should be sent.
1720 msg: msgs::TxSignatures,
1722 /// Used to indicate that a tx_init_rbf message should be sent to the peer with the given node_id.
1724 /// The node_id of the node which should receive this message
1726 /// The message which should be sent.
1727 msg: msgs::TxInitRbf,
1729 /// Used to indicate that a tx_ack_rbf message should be sent to the peer with the given node_id.
1731 /// The node_id of the node which should receive this message
1733 /// The message which should be sent.
1734 msg: msgs::TxAckRbf,
1736 /// Used to indicate that a tx_abort message should be sent to the peer with the given node_id.
1738 /// The node_id of the node which should receive this message
1740 /// The message which should be sent.
1743 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1745 /// The node_id of the node which should receive these message(s)
1747 /// The channel_ready message which should be sent.
1748 msg: msgs::ChannelReady,
1750 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1751 SendAnnouncementSignatures {
1752 /// The node_id of the node which should receive these message(s)
1754 /// The announcement_signatures message which should be sent.
1755 msg: msgs::AnnouncementSignatures,
1757 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1758 /// message should be sent to the peer with the given node_id.
1760 /// The node_id of the node which should receive these message(s)
1762 /// The update messages which should be sent. ALL messages in the struct should be sent!
1763 updates: msgs::CommitmentUpdate,
1765 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1767 /// The node_id of the node which should receive this message
1769 /// The message which should be sent.
1770 msg: msgs::RevokeAndACK,
1772 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1774 /// The node_id of the node which should receive this message
1776 /// The message which should be sent.
1777 msg: msgs::ClosingSigned,
1779 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1781 /// The node_id of the node which should receive this message
1783 /// The message which should be sent.
1784 msg: msgs::Shutdown,
1786 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1787 SendChannelReestablish {
1788 /// The node_id of the node which should receive this message
1790 /// The message which should be sent.
1791 msg: msgs::ChannelReestablish,
1793 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1794 /// initial connection to ensure our peers know about our channels.
1795 SendChannelAnnouncement {
1796 /// The node_id of the node which should receive this message
1798 /// The channel_announcement which should be sent.
1799 msg: msgs::ChannelAnnouncement,
1800 /// The followup channel_update which should be sent.
1801 update_msg: msgs::ChannelUpdate,
1803 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1804 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1806 /// Note that after doing so, you very likely (unless you did so very recently) want to
1807 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1808 /// ensures that any nodes which see our channel_announcement also have a relevant
1809 /// node_announcement, including relevant feature flags which may be important for routing
1810 /// through or to us.
1812 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1813 BroadcastChannelAnnouncement {
1814 /// The channel_announcement which should be sent.
1815 msg: msgs::ChannelAnnouncement,
1816 /// The followup channel_update which should be sent.
1817 update_msg: Option<msgs::ChannelUpdate>,
1819 /// Used to indicate that a channel_update should be broadcast to all peers.
1820 BroadcastChannelUpdate {
1821 /// The channel_update which should be sent.
1822 msg: msgs::ChannelUpdate,
1824 /// Used to indicate that a node_announcement should be broadcast to all peers.
1825 BroadcastNodeAnnouncement {
1826 /// The node_announcement which should be sent.
1827 msg: msgs::NodeAnnouncement,
1829 /// Used to indicate that a channel_update should be sent to a single peer.
1830 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1831 /// private channel and we shouldn't be informing all of our peers of channel parameters.
1833 /// The node_id of the node which should receive this message
1835 /// The channel_update which should be sent.
1836 msg: msgs::ChannelUpdate,
1838 /// Broadcast an error downstream to be handled
1840 /// The node_id of the node which should receive this message
1842 /// The action which should be taken.
1843 action: msgs::ErrorAction
1845 /// Query a peer for channels with funding transaction UTXOs in a block range.
1846 SendChannelRangeQuery {
1847 /// The node_id of this message recipient
1849 /// The query_channel_range which should be sent.
1850 msg: msgs::QueryChannelRange,
1852 /// Request routing gossip messages from a peer for a list of channels identified by
1853 /// their short_channel_ids.
1855 /// The node_id of this message recipient
1857 /// The query_short_channel_ids which should be sent.
1858 msg: msgs::QueryShortChannelIds,
1860 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1861 /// emitted during processing of the query.
1862 SendReplyChannelRange {
1863 /// The node_id of this message recipient
1865 /// The reply_channel_range which should be sent.
1866 msg: msgs::ReplyChannelRange,
1868 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1869 /// enable receiving gossip messages from the peer.
1870 SendGossipTimestampFilter {
1871 /// The node_id of this message recipient
1873 /// The gossip_timestamp_filter which should be sent.
1874 msg: msgs::GossipTimestampFilter,
1878 /// A trait indicating an object may generate message send events
1879 pub trait MessageSendEventsProvider {
1880 /// Gets the list of pending events which were generated by previous actions, clearing the list
1882 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1885 /// A trait indicating an object may generate events.
1887 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1889 /// Implementations of this trait may also feature an async version of event handling, as shown with
1890 /// [`ChannelManager::process_pending_events_async`] and
1891 /// [`ChainMonitor::process_pending_events_async`].
1895 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1896 /// event since the last invocation.
1898 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1899 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1900 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1901 /// relevant changes to disk *before* returning.
1903 /// Further, because an application may crash between an [`Event`] being handled and the
1904 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1905 /// effect, [`Event`]s may be replayed.
1907 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1908 /// consult the provider's documentation on the implication of processing events and how a handler
1909 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1910 /// [`ChainMonitor::process_pending_events`]).
1912 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1915 /// [`process_pending_events`]: Self::process_pending_events
1916 /// [`handle_event`]: EventHandler::handle_event
1917 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1918 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1919 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
1920 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
1921 pub trait EventsProvider {
1922 /// Processes any events generated since the last call using the given event handler.
1924 /// See the trait-level documentation for requirements.
1925 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1928 /// A trait implemented for objects handling events from [`EventsProvider`].
1930 /// An async variation also exists for implementations of [`EventsProvider`] that support async
1931 /// event handling. The async event handler should satisfy the generic bounds: `F:
1932 /// core::future::Future, H: Fn(Event) -> F`.
1933 pub trait EventHandler {
1934 /// Handles the given [`Event`].
1936 /// See [`EventsProvider`] for details that must be considered when implementing this method.
1937 fn handle_event(&self, event: Event);
1940 impl<F> EventHandler for F where F: Fn(Event) {
1941 fn handle_event(&self, event: Event) {
1946 impl<T: EventHandler> EventHandler for Arc<T> {
1947 fn handle_event(&self, event: Event) {
1948 self.deref().handle_event(event)