lightning/events/mod.rs
1// This file is Copyright its original authors, visible in version control
2// history.
3//
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
8// licenses.
9
10//! Events are returned from various bits in the library which indicate some action must be taken
11//! by the client.
12//!
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
15//! few other things.
16
17pub mod bump_transaction;
18
19pub use bump_transaction::BumpTransactionEvent;
20
21use crate::blinded_path::message::{BlindedMessagePath, OffersContext};
22use crate::blinded_path::payment::{
23 Bolt12OfferContext, Bolt12RefundContext, PaymentContext, PaymentContextRef,
24};
25use crate::chain::transaction;
26use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
27use crate::ln::channelmanager::{InterceptId, PaymentId, RecipientOnionFields};
28use crate::ln::types::ChannelId;
29use crate::ln::{msgs, LocalHTLCFailureReason};
30use crate::offers::invoice::Bolt12Invoice;
31use crate::offers::invoice_request::InvoiceRequest;
32use crate::offers::static_invoice::StaticInvoice;
33use crate::onion_message::messenger::Responder;
34use crate::routing::gossip::NetworkUpdate;
35use crate::routing::router::{BlindedTail, Path, RouteHop, RouteParameters};
36use crate::sign::SpendableOutputDescriptor;
37use crate::types::features::ChannelTypeFeatures;
38use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
39use crate::types::string::UntrustedString;
40use crate::util::errors::APIError;
41use crate::util::ser::{
42 BigSize, FixedLengthReader, MaybeReadable, Readable, RequiredWrapper, UpgradableRequired,
43 WithoutLength, Writeable, Writer,
44};
45
46use crate::io;
47use crate::sync::Arc;
48use bitcoin::hashes::sha256::Hash as Sha256;
49use bitcoin::hashes::Hash;
50use bitcoin::script::ScriptBuf;
51use bitcoin::secp256k1::PublicKey;
52use bitcoin::{OutPoint, Transaction, TxOut};
53use core::ops::Deref;
54
55#[allow(unused_imports)]
56use crate::prelude::*;
57
58/// `FundingInfo` holds information about a channel's funding transaction.
59///
60/// When LDK is set to manual propagation of the funding transaction
61/// (via [`ChannelManager::unsafe_manual_funding_transaction_generated`),
62/// LDK does not have the full transaction data. Instead, the `OutPoint`
63/// for the funding is provided here.
64///
65/// [`ChannelManager::unsafe_manual_funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::unsafe_manual_funding_transaction_generated
66#[derive(Debug, PartialEq, Eq, Clone)]
67pub enum FundingInfo {
68 /// The full funding `Transaction`.
69 Tx {
70 /// The funding transaction
71 transaction: Transaction,
72 },
73 /// The `OutPoint` of the funding.
74 OutPoint {
75 /// The outpoint of the funding
76 outpoint: transaction::OutPoint,
77 },
78}
79
80impl_writeable_tlv_based_enum!(FundingInfo,
81 (0, Tx) => {
82 (0, transaction, required)
83 },
84 (1, OutPoint) => {
85 (1, outpoint, required)
86 }
87);
88
89/// Some information provided on receipt of payment depends on whether the payment received is a
90/// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
91#[derive(Clone, Debug, PartialEq, Eq)]
92pub enum PaymentPurpose {
93 /// A payment for a BOLT 11 invoice.
94 Bolt11InvoicePayment {
95 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
96 /// [`ChannelManager::create_inbound_payment`]. When handling [`Event::PaymentClaimable`],
97 /// this can be passed directly to [`ChannelManager::claim_funds`] to claim the payment. No
98 /// action is needed when seen in [`Event::PaymentClaimed`].
99 ///
100 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
101 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
102 payment_preimage: Option<PaymentPreimage>,
103 /// The "payment secret". This authenticates the sender to the recipient, preventing a
104 /// number of deanonymization attacks during the routing process.
105 /// It is provided here for your reference, however its accuracy is enforced directly by
106 /// [`ChannelManager`] using the values you previously provided to
107 /// [`ChannelManager::create_inbound_payment`] or
108 /// [`ChannelManager::create_inbound_payment_for_hash`].
109 ///
110 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
111 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
112 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
113 payment_secret: PaymentSecret,
114 },
115 /// A payment for a BOLT 12 [`Offer`].
116 ///
117 /// [`Offer`]: crate::offers::offer::Offer
118 Bolt12OfferPayment {
119 /// The preimage to the payment hash. When handling [`Event::PaymentClaimable`], this can be
120 /// passed directly to [`ChannelManager::claim_funds`], if provided. No action is needed
121 /// when seen in [`Event::PaymentClaimed`].
122 ///
123 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
124 payment_preimage: Option<PaymentPreimage>,
125 /// The secret used to authenticate the sender to the recipient, preventing a number of
126 /// de-anonymization attacks while routing a payment.
127 ///
128 /// See [`PaymentPurpose::Bolt11InvoicePayment::payment_secret`] for further details.
129 payment_secret: PaymentSecret,
130 /// The context of the payment such as information about the corresponding [`Offer`] and
131 /// [`InvoiceRequest`].
132 ///
133 /// This includes the Human Readable Name which the sender indicated they were paying to,
134 /// for possible recipient disambiguation if you're using a single wildcard DNS entry to
135 /// resolve to many recipients.
136 ///
137 /// [`Offer`]: crate::offers::offer::Offer
138 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
139 payment_context: Bolt12OfferContext,
140 },
141 /// A payment for a BOLT 12 [`Refund`].
142 ///
143 /// [`Refund`]: crate::offers::refund::Refund
144 Bolt12RefundPayment {
145 /// The preimage to the payment hash. When handling [`Event::PaymentClaimable`], this can be
146 /// passed directly to [`ChannelManager::claim_funds`], if provided. No action is needed
147 /// when seen in [`Event::PaymentClaimed`].
148 ///
149 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
150 payment_preimage: Option<PaymentPreimage>,
151 /// The secret used to authenticate the sender to the recipient, preventing a number of
152 /// de-anonymization attacks while routing a payment.
153 ///
154 /// See [`PaymentPurpose::Bolt11InvoicePayment::payment_secret`] for further details.
155 payment_secret: PaymentSecret,
156 /// The context of the payment such as information about the corresponding [`Refund`].
157 ///
158 /// [`Refund`]: crate::offers::refund::Refund
159 payment_context: Bolt12RefundContext,
160 },
161 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
162 /// (the payee) providing a preimage.
163 SpontaneousPayment(PaymentPreimage),
164}
165
166impl PaymentPurpose {
167 /// Returns the preimage for this payment, if it is known.
168 pub fn preimage(&self) -> Option<PaymentPreimage> {
169 match self {
170 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, .. } => *payment_preimage,
171 PaymentPurpose::Bolt12OfferPayment { payment_preimage, .. } => *payment_preimage,
172 PaymentPurpose::Bolt12RefundPayment { payment_preimage, .. } => *payment_preimage,
173 PaymentPurpose::SpontaneousPayment(preimage) => Some(*preimage),
174 }
175 }
176
177 pub(crate) fn is_keysend(&self) -> bool {
178 match self {
179 PaymentPurpose::Bolt11InvoicePayment { .. } => false,
180 PaymentPurpose::Bolt12OfferPayment { .. } => false,
181 PaymentPurpose::Bolt12RefundPayment { .. } => false,
182 PaymentPurpose::SpontaneousPayment(..) => true,
183 }
184 }
185
186 /// Errors when provided an `AsyncBolt12OfferContext`, see below.
187 pub(crate) fn from_parts(
188 payment_preimage: Option<PaymentPreimage>, payment_secret: PaymentSecret,
189 payment_context: Option<PaymentContext>,
190 ) -> Result<Self, ()> {
191 match payment_context {
192 None => Ok(PaymentPurpose::Bolt11InvoicePayment { payment_preimage, payment_secret }),
193 Some(PaymentContext::Bolt12Offer(context)) => Ok(PaymentPurpose::Bolt12OfferPayment {
194 payment_preimage,
195 payment_secret,
196 payment_context: context,
197 }),
198 Some(PaymentContext::Bolt12Refund(context)) => {
199 Ok(PaymentPurpose::Bolt12RefundPayment {
200 payment_preimage,
201 payment_secret,
202 payment_context: context,
203 })
204 },
205 Some(PaymentContext::AsyncBolt12Offer(_)) => {
206 // Callers are expected to convert from `AsyncBolt12OfferContext` to `Bolt12OfferContext`
207 // using the invoice request provided in the payment onion prior to calling this method.
208 debug_assert!(false);
209 Err(())
210 },
211 }
212 }
213}
214
215impl_writeable_tlv_based_enum_legacy!(PaymentPurpose,
216 (0, Bolt11InvoicePayment) => {
217 (0, payment_preimage, option),
218 (2, payment_secret, required),
219 },
220 (4, Bolt12OfferPayment) => {
221 (0, payment_preimage, option),
222 (2, payment_secret, required),
223 (4, payment_context, required),
224 },
225 (6, Bolt12RefundPayment) => {
226 (0, payment_preimage, option),
227 (2, payment_secret, required),
228 (4, payment_context, required),
229 },
230 ;
231 (2, SpontaneousPayment)
232);
233
234/// Information about an HTLC that is part of a payment that can be claimed.
235#[derive(Clone, Debug, PartialEq, Eq)]
236pub struct ClaimedHTLC {
237 /// The counterparty of the channel.
238 ///
239 /// This value will always be `None` for objects serialized with LDK versions prior to 0.2 and
240 /// `Some` otherwise.
241 pub counterparty_node_id: Option<PublicKey>,
242 /// The `channel_id` of the channel over which the HTLC was received.
243 pub channel_id: ChannelId,
244 /// The `user_channel_id` of the channel over which the HTLC was received. This is the value
245 /// passed in to [`ChannelManager::create_channel`] for outbound channels, or to
246 /// [`ChannelManager::accept_inbound_channel`] for inbound channels if
247 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
248 /// `user_channel_id` will be randomized for an inbound channel.
249 ///
250 /// This field will be zero for a payment that was serialized prior to LDK version 0.0.117. (This
251 /// should only happen in the case that a payment was claimable prior to LDK version 0.0.117, but
252 /// was not actually claimed until after upgrading.)
253 ///
254 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
255 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
256 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
257 pub user_channel_id: u128,
258 /// The block height at which this HTLC expires.
259 pub cltv_expiry: u32,
260 /// The amount (in msats) of this part of an MPP.
261 pub value_msat: u64,
262 /// The extra fee our counterparty skimmed off the top of this HTLC, if any.
263 ///
264 /// This value will always be 0 for [`ClaimedHTLC`]s serialized with LDK versions prior to
265 /// 0.0.119.
266 pub counterparty_skimmed_fee_msat: u64,
267}
268impl_writeable_tlv_based!(ClaimedHTLC, {
269 (0, channel_id, required),
270 (1, counterparty_skimmed_fee_msat, (default_value, 0u64)),
271 (2, user_channel_id, required),
272 (3, counterparty_node_id, option),
273 (4, cltv_expiry, required),
274 (6, value_msat, required),
275});
276
277/// When the payment path failure took place and extra details about it. [`PathFailure::OnPath`] may
278/// contain a [`NetworkUpdate`] that needs to be applied to the [`NetworkGraph`].
279///
280/// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
281/// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
282#[derive(Clone, Debug, Eq, PartialEq)]
283pub enum PathFailure {
284 /// We failed to initially send the payment and no HTLC was committed to. Contains the relevant
285 /// error.
286 InitialSend {
287 /// The error surfaced from initial send.
288 err: APIError,
289 },
290 /// A hop on the path failed to forward our payment.
291 OnPath {
292 /// If present, this [`NetworkUpdate`] should be applied to the [`NetworkGraph`] so that routing
293 /// decisions can take into account the update.
294 ///
295 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
296 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
297 network_update: Option<NetworkUpdate>,
298 },
299}
300
301impl_writeable_tlv_based_enum_upgradable!(PathFailure,
302 (0, OnPath) => {
303 (0, network_update, upgradable_option),
304 },
305 (2, InitialSend) => {
306 (0, err, upgradable_required),
307 },
308);
309
310#[derive(Clone, Debug, PartialEq, Eq)]
311/// The reason the channel was closed. See individual variants for more details.
312pub enum ClosureReason {
313 /// Closure generated from receiving a peer error message.
314 ///
315 /// Our counterparty may have broadcasted their latest commitment state, and we have
316 /// as well.
317 CounterpartyForceClosed {
318 /// The error which the peer sent us.
319 ///
320 /// Be careful about printing the peer_msg, a well-crafted message could exploit
321 /// a security vulnerability in the terminal emulator or the logging subsystem.
322 /// To be safe, use `Display` on `UntrustedString`
323 ///
324 /// [`UntrustedString`]: crate::types::string::UntrustedString
325 peer_msg: UntrustedString,
326 },
327 /// Closure generated from [`ChannelManager::force_close_broadcasting_latest_txn`] or
328 /// [`ChannelManager::force_close_all_channels_broadcasting_latest_txn`], called by the user.
329 ///
330 /// [`ChannelManager::force_close_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_broadcasting_latest_txn
331 /// [`ChannelManager::force_close_all_channels_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_all_channels_broadcasting_latest_txn
332 HolderForceClosed {
333 /// Whether or not the latest transaction was broadcasted when the channel was force
334 /// closed.
335 ///
336 /// This will be set to `Some(true)` for any channels closed after their funding
337 /// transaction was (or might have been) broadcasted, and `Some(false)` for any channels
338 /// closed prior to their funding transaction being broadcasted.
339 ///
340 /// This will be `None` for objects generated or written by LDK 0.0.123 and
341 /// earlier.
342 broadcasted_latest_txn: Option<bool>,
343 /// The error message provided to [`ChannelManager::force_close_broadcasting_latest_txn`] or
344 /// [`ChannelManager::force_close_all_channels_broadcasting_latest_txn`].
345 ///
346 /// This will be the empty string for objects generated or written by LDK 0.1 and earlier.
347 ///
348 /// [`ChannelManager::force_close_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_broadcasting_latest_txn
349 /// [`ChannelManager::force_close_all_channels_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_all_channels_broadcasting_latest_txn
350 message: String,
351 },
352 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
353 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
354 ///
355 /// This was only set in versions of LDK prior to 0.0.122.
356 // Can be removed once we disallow downgrading to 0.0.121
357 LegacyCooperativeClosure,
358 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
359 /// the cooperative close transaction. This indicates that the shutdown was initiated by our
360 /// counterparty.
361 ///
362 /// In rare cases where we initiated closure immediately prior to shutting down without
363 /// persisting, this value may be provided for channels we initiated closure for.
364 CounterpartyInitiatedCooperativeClosure,
365 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
366 /// the cooperative close transaction. This indicates that the shutdown was initiated by us.
367 LocallyInitiatedCooperativeClosure,
368 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
369 /// commitment transaction came from our counterparty, but it may also have come from
370 /// a copy of our own `ChannelMonitor`.
371 CommitmentTxConfirmed,
372 /// The funding transaction failed to confirm in a timely manner on an inbound channel or the
373 /// counterparty failed to fund the channel in a timely manner.
374 FundingTimedOut,
375 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
376 ProcessingError {
377 /// A developer-readable error message which we generated.
378 err: String,
379 },
380 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
381 /// forget the channel entirely - we can attempt again if the peer reconnects.
382 ///
383 /// This includes cases where we restarted prior to funding completion, including prior to the
384 /// initial [`ChannelMonitor`] persistence completing.
385 ///
386 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
387 /// peer because of mutual incompatibility between us and our channel counterparty.
388 ///
389 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
390 DisconnectedPeer,
391 /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
392 /// the [`ChannelManager`] deserialized.
393 ///
394 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
395 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
396 OutdatedChannelManager,
397 /// The counterparty requested a cooperative close of a channel that had not been funded yet.
398 /// The channel has been immediately closed.
399 CounterpartyCoopClosedUnfundedChannel,
400 /// We requested a cooperative close of a channel that had not been funded yet.
401 /// The channel has been immediately closed.
402 ///
403 /// Note that events containing this variant will be lost on downgrade to a version of LDK
404 /// prior to 0.2.
405 LocallyCoopClosedUnfundedChannel,
406 /// Another channel in the same funding batch closed before the funding transaction
407 /// was ready to be broadcast.
408 FundingBatchClosure,
409 /// One of our HTLCs timed out in a channel, causing us to force close the channel.
410 HTLCsTimedOut {
411 /// The payment hash of an HTLC that timed out.
412 ///
413 /// Will be `None` for any event serialized by LDK prior to 0.2.
414 payment_hash: Option<PaymentHash>,
415 },
416 /// Our peer provided a feerate which violated our required minimum (fetched from our
417 /// [`FeeEstimator`] either as [`ConfirmationTarget::MinAllowedAnchorChannelRemoteFee`] or
418 /// [`ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee`]).
419 ///
420 /// [`FeeEstimator`]: crate::chain::chaininterface::FeeEstimator
421 /// [`ConfirmationTarget::MinAllowedAnchorChannelRemoteFee`]: crate::chain::chaininterface::ConfirmationTarget::MinAllowedAnchorChannelRemoteFee
422 /// [`ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee`]: crate::chain::chaininterface::ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee
423 PeerFeerateTooLow {
424 /// The feerate on our channel set by our peer.
425 peer_feerate_sat_per_kw: u32,
426 /// The required feerate we enforce, from our [`FeeEstimator`].
427 ///
428 /// [`FeeEstimator`]: crate::chain::chaininterface::FeeEstimator
429 required_feerate_sat_per_kw: u32,
430 },
431}
432
433impl core::fmt::Display for ClosureReason {
434 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
435 f.write_str("Channel closed because ")?;
436 match self {
437 ClosureReason::CounterpartyForceClosed { peer_msg } => {
438 f.write_fmt(format_args!("counterparty force-closed with message: {}", peer_msg))
439 },
440 ClosureReason::HolderForceClosed { broadcasted_latest_txn, message } => {
441 f.write_str("user force-closed the channel with the message \"")?;
442 f.write_str(message)?;
443 if let Some(brodcasted) = broadcasted_latest_txn {
444 write!(
445 f,
446 "\" and {} the latest transaction",
447 if *brodcasted { "broadcasted" } else { "elected not to broadcast" }
448 )
449 } else {
450 Ok(())
451 }
452 },
453 ClosureReason::LegacyCooperativeClosure => {
454 f.write_str("the channel was cooperatively closed")
455 },
456 ClosureReason::CounterpartyInitiatedCooperativeClosure => {
457 f.write_str("the channel was cooperatively closed by our peer")
458 },
459 ClosureReason::LocallyInitiatedCooperativeClosure => {
460 f.write_str("the channel was cooperatively closed by us")
461 },
462 ClosureReason::CommitmentTxConfirmed => {
463 f.write_str("commitment or closing transaction was confirmed on chain.")
464 },
465 ClosureReason::FundingTimedOut => write!(
466 f,
467 "funding transaction failed to confirm within {} blocks",
468 FUNDING_CONF_DEADLINE_BLOCKS
469 ),
470 ClosureReason::ProcessingError { err } => {
471 f.write_str("of an exception: ")?;
472 f.write_str(&err)
473 },
474 ClosureReason::DisconnectedPeer => {
475 f.write_str("the peer disconnected prior to the channel being funded")
476 },
477 ClosureReason::OutdatedChannelManager => f.write_str(
478 "the ChannelManager read from disk was stale compared to ChannelMonitor(s)",
479 ),
480 ClosureReason::CounterpartyCoopClosedUnfundedChannel => {
481 f.write_str("the peer requested the unfunded channel be closed")
482 },
483 ClosureReason::LocallyCoopClosedUnfundedChannel => {
484 f.write_str("we requested the unfunded channel be closed")
485 },
486 ClosureReason::FundingBatchClosure => {
487 f.write_str("another channel in the same funding batch closed")
488 },
489 ClosureReason::HTLCsTimedOut { payment_hash: Some(hash) } => f.write_fmt(format_args!(
490 "HTLC(s) on the channel timed out (including the HTLC with payment hash {hash})",
491 )),
492 ClosureReason::HTLCsTimedOut { payment_hash: None } => {
493 f.write_fmt(format_args!("HTLC(s) on the channel timed out"))
494 },
495 ClosureReason::PeerFeerateTooLow {
496 peer_feerate_sat_per_kw,
497 required_feerate_sat_per_kw,
498 } => f.write_fmt(format_args!(
499 "peer provided a feerate ({} sat/kw) which was below our lower bound ({} sat/kw)",
500 peer_feerate_sat_per_kw, required_feerate_sat_per_kw,
501 )),
502 }
503 }
504}
505
506impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
507 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
508 (1, FundingTimedOut) => {},
509 (2, HolderForceClosed) => {
510 (1, broadcasted_latest_txn, option),
511 (3, message, (default_value, String::new())),
512 },
513 (6, CommitmentTxConfirmed) => {},
514 (4, LegacyCooperativeClosure) => {},
515 (8, ProcessingError) => { (1, err, required) },
516 (10, DisconnectedPeer) => {},
517 (12, OutdatedChannelManager) => {},
518 (13, CounterpartyCoopClosedUnfundedChannel) => {},
519 (15, FundingBatchClosure) => {},
520 (17, CounterpartyInitiatedCooperativeClosure) => {},
521 (19, LocallyInitiatedCooperativeClosure) => {},
522 (21, HTLCsTimedOut) => {
523 (1, payment_hash, option),
524 },
525 (23, PeerFeerateTooLow) => {
526 (0, peer_feerate_sat_per_kw, required),
527 (2, required_feerate_sat_per_kw, required),
528 },
529 (25, LocallyCoopClosedUnfundedChannel) => {},
530);
531
532/// The type of HTLC handling performed in [`Event::HTLCHandlingFailed`].
533#[derive(Clone, Debug, PartialEq, Eq)]
534pub enum HTLCHandlingFailureType {
535 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
536 /// there is insufficient capacity in our outbound channel.
537 Forward {
538 /// The `node_id` of the next node. For backwards compatibility, this field is
539 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
540 /// counterparty node information.
541 node_id: Option<PublicKey>,
542 /// The outgoing `channel_id` between us and the next node.
543 channel_id: ChannelId,
544 },
545 /// Scenario where we are unsure of the next node to forward the HTLC to.
546 ///
547 /// Deprecated: will only be used in versions before LDK v0.2.0. Downgrades will result in
548 /// this type being represented as [`Self::InvalidForward`].
549 UnknownNextHop {
550 /// Short channel id we are requesting to forward an HTLC to.
551 requested_forward_scid: u64,
552 },
553 /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
554 /// intercept HTLC.
555 ///
556 /// In LDK v0.2.0 and greater, this variant replaces [`Self::UnknownNextHop`].
557 InvalidForward {
558 /// Short channel id we are requesting to forward an HTLC to.
559 requested_forward_scid: u64,
560 },
561 /// We couldn't decode the incoming onion to obtain the forwarding details.
562 InvalidOnion,
563 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
564 /// but is invalid for some reason, so we reject it.
565 ///
566 /// Some of the reasons may include:
567 /// * HTLC Timeouts
568 /// * Excess HTLCs for a payment that we have already fully received, over-paying for the
569 /// payment,
570 /// * The counterparty node modified the HTLC in transit,
571 /// * A probing attack where an intermediary node is trying to detect if we are the ultimate
572 /// recipient for a payment.
573 Receive {
574 /// The payment hash of the payment we attempted to process.
575 payment_hash: PaymentHash,
576 },
577}
578
579impl_writeable_tlv_based_enum_upgradable!(HTLCHandlingFailureType,
580 (0, Forward) => {
581 (0, node_id, required),
582 (2, channel_id, required),
583 },
584 (1, InvalidForward) => {
585 (0, requested_forward_scid, required),
586 },
587 (2, UnknownNextHop) => {
588 (0, requested_forward_scid, required),
589 },
590 (3, InvalidOnion) => {},
591 (4, Receive) => {
592 (0, payment_hash, required),
593 },
594);
595
596/// The reason for HTLC failures in [`Event::HTLCHandlingFailed`].
597#[derive(Clone, Debug, PartialEq, Eq)]
598pub enum HTLCHandlingFailureReason {
599 /// The forwarded HTLC was failed back by the downstream node with an encrypted error reason.
600 Downstream,
601 /// The HTLC was failed locally by our node.
602 Local {
603 /// The reason that our node chose to fail the HTLC.
604 reason: LocalHTLCFailureReason,
605 },
606}
607
608impl_writeable_tlv_based_enum!(HTLCHandlingFailureReason,
609 (1, Downstream) => {},
610 (3, Local) => {
611 (0, reason, required),
612 },
613);
614
615impl From<LocalHTLCFailureReason> for HTLCHandlingFailureReason {
616 fn from(value: LocalHTLCFailureReason) -> Self {
617 HTLCHandlingFailureReason::Local { reason: value }
618 }
619}
620
621/// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
622/// Currently only used in serialization for the sake of maintaining compatibility. More variants
623/// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
624/// intercepts in upcoming work.
625enum InterceptNextHop {
626 FakeScid { requested_next_hop_scid: u64 },
627}
628
629impl_writeable_tlv_based_enum!(InterceptNextHop,
630 (0, FakeScid) => {
631 (0, requested_next_hop_scid, required),
632 },
633);
634
635/// The reason the payment failed. Used in [`Event::PaymentFailed`].
636#[derive(Clone, Copy, Debug, PartialEq, Eq)]
637pub enum PaymentFailureReason {
638 /// The intended recipient rejected our payment.
639 ///
640 /// Also used for [`UnknownRequiredFeatures`] and [`InvoiceRequestRejected`] when downgrading to
641 /// version prior to 0.0.124.
642 ///
643 /// [`UnknownRequiredFeatures`]: Self::UnknownRequiredFeatures
644 /// [`InvoiceRequestRejected`]: Self::InvoiceRequestRejected
645 RecipientRejected,
646 /// The user chose to abandon this payment by calling [`ChannelManager::abandon_payment`].
647 ///
648 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
649 UserAbandoned,
650 #[cfg_attr(
651 feature = "std",
652 doc = "We exhausted all of our retry attempts while trying to send the payment, or we"
653 )]
654 #[cfg_attr(feature = "std", doc = "exhausted the [`Retry::Timeout`] if the user set one.")]
655 #[cfg_attr(
656 not(feature = "std"),
657 doc = "We exhausted all of our retry attempts while trying to send the payment."
658 )]
659 /// If at any point a retry attempt failed while being forwarded along the path, an [`Event::PaymentPathFailed`] will
660 /// have come before this.
661 #[cfg_attr(feature = "std", doc = "")]
662 #[cfg_attr(
663 feature = "std",
664 doc = "[`Retry::Timeout`]: crate::ln::channelmanager::Retry::Timeout"
665 )]
666 RetriesExhausted,
667 /// Either the BOLT 12 invoice was expired by the time we received it or the payment expired while
668 /// retrying based on the provided [`PaymentParameters::expiry_time`].
669 ///
670 /// Also used for [`InvoiceRequestExpired`] when downgrading to version prior to 0.0.124.
671 ///
672 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
673 /// [`InvoiceRequestExpired`]: Self::InvoiceRequestExpired
674 PaymentExpired,
675 /// We failed to find a route while sending or retrying the payment.
676 ///
677 /// Note that this generally indicates that we've exhausted the available set of possible
678 /// routes - we tried the payment over a few routes but were not able to find any further
679 /// candidate routes beyond those.
680 ///
681 /// Also used for [`BlindedPathCreationFailed`] when downgrading to versions prior to 0.0.124.
682 ///
683 /// [`BlindedPathCreationFailed`]: Self::BlindedPathCreationFailed
684 RouteNotFound,
685 /// This error should generally never happen. This likely means that there is a problem with
686 /// your router.
687 UnexpectedError,
688 /// An invoice was received that required unknown features.
689 UnknownRequiredFeatures,
690 /// A [`Bolt12Invoice`] was not received in a reasonable amount of time.
691 InvoiceRequestExpired,
692 /// An [`InvoiceRequest`] for the payment was rejected by the recipient.
693 ///
694 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
695 InvoiceRequestRejected,
696 /// Failed to create a blinded path back to ourselves.
697 /// We attempted to initiate payment to a static invoice but failed to create a reply path for our
698 /// [`HeldHtlcAvailable`] message.
699 ///
700 /// [`HeldHtlcAvailable`]: crate::onion_message::async_payments::HeldHtlcAvailable
701 BlindedPathCreationFailed,
702}
703
704impl_writeable_tlv_based_enum_upgradable!(PaymentFailureReason,
705 (0, RecipientRejected) => {},
706 (1, UnknownRequiredFeatures) => {},
707 (2, UserAbandoned) => {},
708 (3, InvoiceRequestExpired) => {},
709 (4, RetriesExhausted) => {},
710 (5, InvoiceRequestRejected) => {},
711 (6, PaymentExpired) => {},
712 (7, BlindedPathCreationFailed) => {},
713 (8, RouteNotFound) => {},
714 (10, UnexpectedError) => {},
715);
716
717/// Used to indicate the kind of funding for this channel by the channel acceptor (us).
718///
719/// Allows the differentiation between a request for a dual-funded and non-dual-funded channel.
720#[derive(Clone, Debug, PartialEq, Eq)]
721pub enum InboundChannelFunds {
722 /// For a non-dual-funded channel, the `push_msat` value from the channel initiator to us.
723 PushMsat(u64),
724 /// Indicates the open request is for a dual funded channel.
725 ///
726 /// Note that these channels do not support starting with initial funds pushed from the counterparty,
727 /// who is the channel opener in this case.
728 DualFunded,
729}
730
731/// An Event which you should probably take some action in response to.
732///
733/// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
734/// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
735/// written as it makes no sense to respond to it after reconnecting to peers).
736#[derive(Clone, Debug, PartialEq, Eq)]
737pub enum Event {
738 /// Used to indicate that the client should generate a funding transaction with the given
739 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
740 /// Generated in [`ChannelManager`] message handling.
741 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
742 /// counterparty can steal your funds!
743 ///
744 /// # Failure Behavior and Persistence
745 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
746 /// returning `Err(ReplayEvent ())`), but won't be persisted across restarts.
747 ///
748 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
749 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
750 FundingGenerationReady {
751 /// The random channel_id we picked which you'll need to pass into
752 /// [`ChannelManager::funding_transaction_generated`].
753 ///
754 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
755 temporary_channel_id: ChannelId,
756 /// The counterparty's node_id, which you'll need to pass back into
757 /// [`ChannelManager::funding_transaction_generated`].
758 ///
759 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
760 counterparty_node_id: PublicKey,
761 /// The value, in satoshis, that the output should have.
762 channel_value_satoshis: u64,
763 /// The script which should be used in the transaction output.
764 output_script: ScriptBuf,
765 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
766 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
767 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
768 /// `user_channel_id` will be randomized for an inbound channel. This may be zero for objects
769 /// serialized with LDK versions prior to 0.0.113.
770 ///
771 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
772 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
773 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
774 user_channel_id: u128,
775 },
776 /// Used to indicate that the counterparty node has provided the signature(s) required to
777 /// recover our funds in case they go offline.
778 ///
779 /// It is safe (and your responsibility) to broadcast the funding transaction upon receiving this
780 /// event.
781 ///
782 /// This event is only emitted if you called
783 /// [`ChannelManager::unsafe_manual_funding_transaction_generated`] instead of
784 /// [`ChannelManager::funding_transaction_generated`].
785 ///
786 /// [`ChannelManager::unsafe_manual_funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::unsafe_manual_funding_transaction_generated
787 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
788 FundingTxBroadcastSafe {
789 /// The `channel_id` indicating which channel has reached this stage.
790 channel_id: ChannelId,
791 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`].
792 ///
793 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
794 user_channel_id: u128,
795 /// The outpoint of the channel's funding transaction.
796 funding_txo: OutPoint,
797 /// The `node_id` of the channel counterparty.
798 counterparty_node_id: PublicKey,
799 /// The `temporary_channel_id` this channel used to be known by during channel establishment.
800 former_temporary_channel_id: ChannelId,
801 },
802 /// Indicates that we've been offered a payment and it needs to be claimed via calling
803 /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
804 ///
805 /// Note that if the preimage is not known, you should call
806 /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
807 /// to free up resources for this HTLC and avoid network congestion.
808 ///
809 /// If [`Event::PaymentClaimable::onion_fields`] is `Some`, and includes custom TLVs with even type
810 /// numbers, you should use [`ChannelManager::fail_htlc_backwards_with_reason`] with
811 /// [`FailureCode::InvalidOnionPayload`] if you fail to understand and handle the contents, or
812 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`] upon successful handling.
813 /// If you don't intend to check for custom TLVs, you can simply use
814 /// [`ChannelManager::claim_funds`], which will automatically fail back even custom TLVs.
815 ///
816 /// If you fail to call [`ChannelManager::claim_funds`],
817 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`],
818 /// [`ChannelManager::fail_htlc_backwards`], or
819 /// [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will
820 /// be automatically failed.
821 ///
822 /// # Note
823 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
824 /// `PaymentClaimable` events may be generated for the same payment. In such a case it is
825 /// polite (and required in the lightning specification) to fail the payment the second time
826 /// and give the sender their money back rather than accepting double payment.
827 ///
828 /// # Note
829 /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
830 ///
831 /// # Failure Behavior and Persistence
832 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
833 /// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
834 ///
835 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
836 /// [`ChannelManager::claim_funds_with_known_custom_tlvs`]: crate::ln::channelmanager::ChannelManager::claim_funds_with_known_custom_tlvs
837 /// [`FailureCode::InvalidOnionPayload`]: crate::ln::channelmanager::FailureCode::InvalidOnionPayload
838 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
839 /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
840 PaymentClaimable {
841 /// The node that will receive the payment after it has been claimed.
842 /// This is useful to identify payments received via [phantom nodes].
843 /// This field will always be filled in when the event was generated by LDK versions
844 /// 0.0.113 and above.
845 ///
846 /// [phantom nodes]: crate::sign::PhantomKeysManager
847 receiver_node_id: Option<PublicKey>,
848 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
849 /// not stop you from registering duplicate payment hashes for inbound payments.
850 payment_hash: PaymentHash,
851 /// The fields in the onion which were received with each HTLC. Only fields which were
852 /// identical in each HTLC involved in the payment will be included here.
853 ///
854 /// Payments received on LDK versions prior to 0.0.115 will have this field unset.
855 onion_fields: Option<RecipientOnionFields>,
856 /// The value, in thousandths of a satoshi, that this payment is claimable for. May be greater
857 /// than the invoice amount.
858 ///
859 /// May be less than the invoice amount if [`ChannelConfig::accept_underpaying_htlcs`] is set
860 /// and the previous hop took an extra fee.
861 ///
862 /// # Note
863 /// If [`ChannelConfig::accept_underpaying_htlcs`] is set and you claim without verifying this
864 /// field, you may lose money!
865 ///
866 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
867 amount_msat: u64,
868 /// The value, in thousands of a satoshi, that was skimmed off of this payment as an extra fee
869 /// taken by our channel counterparty.
870 ///
871 /// Will always be 0 unless [`ChannelConfig::accept_underpaying_htlcs`] is set.
872 ///
873 /// [`ChannelConfig::accept_underpaying_htlcs`]: crate::util::config::ChannelConfig::accept_underpaying_htlcs
874 counterparty_skimmed_fee_msat: u64,
875 /// Information for claiming this received payment, based on whether the purpose of the
876 /// payment is to pay an invoice or to send a spontaneous payment.
877 purpose: PaymentPurpose,
878 /// The `(channel_id, user_channel_id)` pairs over which the payment was received.
879 ///
880 /// This will be an incomplete vector for MPP payment events created/serialized using LDK version 0.1.0 and prior.
881 receiving_channel_ids: Vec<(ChannelId, Option<u128>)>,
882 /// The block height at which this payment will be failed back and will no longer be
883 /// eligible for claiming.
884 ///
885 /// Prior to this height, a call to [`ChannelManager::claim_funds`] is guaranteed to
886 /// succeed, however you should wait for [`Event::PaymentClaimed`] to be sure.
887 ///
888 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
889 claim_deadline: Option<u32>,
890 /// A unique ID describing this payment (derived from the list of HTLCs in the payment).
891 ///
892 /// Payers may pay for the same [`PaymentHash`] multiple times (though this is unsafe and
893 /// an intermediary node may steal the funds). Thus, in order to accurately track when
894 /// payments are received and claimed, you should use this identifier.
895 ///
896 /// Only filled in for payments received on LDK versions 0.1 and higher.
897 payment_id: Option<PaymentId>,
898 },
899 /// Indicates a payment has been claimed and we've received money!
900 ///
901 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
902 /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
903 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
904 /// [`Event::PaymentClaimable`] event.
905 ///
906 /// # Note
907 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
908 /// `PaymentClaimable` events may be generated for the same payment. If you then call
909 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
910 /// multiple `PaymentClaimed` events.
911 ///
912 /// # Failure Behavior and Persistence
913 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
914 /// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
915 ///
916 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
917 PaymentClaimed {
918 /// The node that received the payment.
919 /// This is useful to identify payments which were received via [phantom nodes].
920 /// This field will always be filled in when the event was generated by LDK versions
921 /// 0.0.113 and above.
922 ///
923 /// [phantom nodes]: crate::sign::PhantomKeysManager
924 receiver_node_id: Option<PublicKey>,
925 /// The payment hash of the claimed payment. Note that LDK will not stop you from
926 /// registering duplicate payment hashes for inbound payments.
927 payment_hash: PaymentHash,
928 /// The value, in thousandths of a satoshi, that this payment is for. May be greater than the
929 /// invoice amount.
930 amount_msat: u64,
931 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
932 /// spontaneous payment.
933 purpose: PaymentPurpose,
934 /// The HTLCs that comprise the claimed payment. This will be empty for events serialized prior
935 /// to LDK version 0.0.117.
936 htlcs: Vec<ClaimedHTLC>,
937 /// The sender-intended sum total of all the MPP parts. This will be `None` for events
938 /// serialized prior to LDK version 0.0.117.
939 sender_intended_total_msat: Option<u64>,
940 /// The fields in the onion which were received with each HTLC. Only fields which were
941 /// identical in each HTLC involved in the payment will be included here.
942 ///
943 /// Payments received on LDK versions prior to 0.0.124 will have this field unset.
944 onion_fields: Option<RecipientOnionFields>,
945 /// A unique ID describing this payment (derived from the list of HTLCs in the payment).
946 ///
947 /// Payers may pay for the same [`PaymentHash`] multiple times (though this is unsafe and
948 /// an intermediary node may steal the funds). Thus, in order to accurately track when
949 /// payments are received and claimed, you should use this identifier.
950 ///
951 /// Only filled in for payments received on LDK versions 0.1 and higher.
952 payment_id: Option<PaymentId>,
953 },
954 /// Indicates that a peer connection with a node is needed in order to send an [`OnionMessage`].
955 ///
956 /// Typically, this happens when a [`MessageRouter`] is unable to find a complete path to a
957 /// [`Destination`]. Once a connection is established, any messages buffered by an
958 /// [`OnionMessageHandler`] may be sent.
959 ///
960 /// This event will not be generated for onion message forwards; only for sends including
961 /// replies. Handlers should connect to the node otherwise any buffered messages may be lost.
962 ///
963 /// # Failure Behavior and Persistence
964 /// This event won't be replayed after failures-to-handle
965 /// (i.e., the event handler returning `Err(ReplayEvent ())`), and also won't be persisted
966 /// across restarts.
967 ///
968 /// [`OnionMessage`]: msgs::OnionMessage
969 /// [`MessageRouter`]: crate::onion_message::messenger::MessageRouter
970 /// [`Destination`]: crate::onion_message::messenger::Destination
971 /// [`OnionMessageHandler`]: crate::ln::msgs::OnionMessageHandler
972 ConnectionNeeded {
973 /// The node id for the node needing a connection.
974 node_id: PublicKey,
975 /// Sockets for connecting to the node, if available. We don't require these addresses to be
976 /// present in case the node id corresponds to a known peer that is offline and can be awoken,
977 /// such as via the LSPS5 protocol.
978 addresses: Vec<msgs::SocketAddress>,
979 },
980 /// Indicates a [`Bolt12Invoice`] in response to an [`InvoiceRequest`] or a [`Refund`] was
981 /// received.
982 ///
983 /// This event will only be generated if [`UserConfig::manually_handle_bolt12_invoices`] is set.
984 /// Use [`ChannelManager::send_payment_for_bolt12_invoice`] to pay the invoice or
985 /// [`ChannelManager::abandon_payment`] to abandon the associated payment. See those docs for
986 /// further details.
987 ///
988 /// # Failure Behavior and Persistence
989 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
990 /// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
991 ///
992 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
993 /// [`Refund`]: crate::offers::refund::Refund
994 /// [`UserConfig::manually_handle_bolt12_invoices`]: crate::util::config::UserConfig::manually_handle_bolt12_invoices
995 /// [`ChannelManager::send_payment_for_bolt12_invoice`]: crate::ln::channelmanager::ChannelManager::send_payment_for_bolt12_invoice
996 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
997 InvoiceReceived {
998 /// The `payment_id` associated with payment for the invoice.
999 payment_id: PaymentId,
1000 /// The invoice to pay.
1001 invoice: Bolt12Invoice,
1002 /// The context of the [`BlindedMessagePath`] used to send the invoice.
1003 ///
1004 /// [`BlindedMessagePath`]: crate::blinded_path::message::BlindedMessagePath
1005 context: Option<OffersContext>,
1006 /// A responder for replying with an [`InvoiceError`] if needed.
1007 ///
1008 /// `None` if the invoice wasn't sent with a reply path.
1009 ///
1010 /// [`InvoiceError`]: crate::offers::invoice_error::InvoiceError
1011 responder: Option<Responder>,
1012 },
1013 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
1014 /// and we got back the payment preimage for it).
1015 ///
1016 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
1017 /// event. In this situation, you SHOULD treat this payment as having succeeded.
1018 ///
1019 /// # Failure Behavior and Persistence
1020 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1021 /// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1022 PaymentSent {
1023 /// The `payment_id` passed to [`ChannelManager::send_payment`].
1024 ///
1025 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1026 payment_id: Option<PaymentId>,
1027 /// The preimage to the hash given to ChannelManager::send_payment.
1028 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
1029 /// store it somehow!
1030 payment_preimage: PaymentPreimage,
1031 /// The hash that was given to [`ChannelManager::send_payment`].
1032 ///
1033 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1034 payment_hash: PaymentHash,
1035 /// The total amount that was paid, across all paths.
1036 ///
1037 /// Note that, like [`Route::get_total_amount`], this does *not* include the paid fees.
1038 ///
1039 /// This is only `None` for payments initiated on LDK versions prior to 0.2.
1040 ///
1041 /// [`Route::get_total_amount`]: crate::routing::router::Route::get_total_amount
1042 amount_msat: Option<u64>,
1043 /// The total fee which was spent at intermediate hops in this payment, across all paths.
1044 ///
1045 /// Note that, like [`Route::get_total_fees`], this does *not* include any potential
1046 /// overpayment to the recipient node.
1047 ///
1048 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
1049 /// overstate the amount paid, though this is unlikely.
1050 ///
1051 /// This is only `None` for payments initiated on LDK versions prior to 0.0.103.
1052 ///
1053 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
1054 fee_paid_msat: Option<u64>,
1055 /// The BOLT 12 invoice that was paid. `None` if the payment was a non BOLT 12 payment.
1056 ///
1057 /// The BOLT 12 invoice is useful for proof of payment because it contains the
1058 /// payment hash. A third party can verify that the payment was made by
1059 /// showing the invoice and confirming that the payment hash matches
1060 /// the hash of the payment preimage.
1061 ///
1062 /// However, the [`PaidBolt12Invoice`] can also be of type [`StaticInvoice`], which
1063 /// is a special [`Bolt12Invoice`] where proof of payment is not possible.
1064 ///
1065 /// [`StaticInvoice`]: crate::offers::static_invoice::StaticInvoice
1066 bolt12_invoice: Option<PaidBolt12Invoice>,
1067 },
1068 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
1069 /// provide failure information for each path attempt in the payment, including retries.
1070 ///
1071 /// This event is provided once there are no further pending HTLCs for the payment and the
1072 /// payment is no longer retryable, due either to the [`Retry`] provided or
1073 /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
1074 ///
1075 /// In exceedingly rare cases, it is possible that an [`Event::PaymentFailed`] is generated for
1076 /// a payment after an [`Event::PaymentSent`] event for this same payment has already been
1077 /// received and processed. In this case, the [`Event::PaymentFailed`] event MUST be ignored,
1078 /// and the payment MUST be treated as having succeeded.
1079 ///
1080 /// # Failure Behavior and Persistence
1081 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1082 /// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1083 ///
1084 /// [`Retry`]: crate::ln::channelmanager::Retry
1085 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
1086 PaymentFailed {
1087 /// The `payment_id` passed to [`ChannelManager::send_payment`].
1088 ///
1089 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1090 payment_id: PaymentId,
1091 /// The hash that was given to [`ChannelManager::send_payment`]. `None` if the payment failed
1092 /// before receiving an invoice when paying a BOLT12 [`Offer`].
1093 ///
1094 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1095 /// [`Offer`]: crate::offers::offer::Offer
1096 payment_hash: Option<PaymentHash>,
1097 /// The reason the payment failed. This is only `None` for events generated or serialized
1098 /// by versions prior to 0.0.115, or when downgrading to a version with a reason that was
1099 /// added after.
1100 reason: Option<PaymentFailureReason>,
1101 },
1102 /// Indicates that a path for an outbound payment was successful.
1103 ///
1104 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
1105 /// [`Event::PaymentSent`] for obtaining the payment preimage.
1106 ///
1107 /// # Failure Behavior and Persistence
1108 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1109 /// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1110 PaymentPathSuccessful {
1111 /// The `payment_id` passed to [`ChannelManager::send_payment`].
1112 ///
1113 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1114 payment_id: PaymentId,
1115 /// The hash that was given to [`ChannelManager::send_payment`].
1116 ///
1117 /// This will be `Some` for all payments which completed on LDK 0.0.104 or later.
1118 ///
1119 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1120 payment_hash: Option<PaymentHash>,
1121 /// The payment path that was successful.
1122 ///
1123 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
1124 path: Path,
1125 /// The time that each hop indicated it held the HTLC.
1126 ///
1127 /// The unit in which the hold times are expressed are 100's of milliseconds. So a hop
1128 /// reporting 2 is a hold time that corresponds to between 200 and 299 milliseconds.
1129 ///
1130 /// We expect that at each hop the actual hold time will be strictly greater than the hold
1131 /// time of the following hops, as a node along the path shouldn't have completed the HTLC
1132 /// until the next node has completed it. Note that because hold times are in 100's of ms,
1133 /// hold times as reported are likely to often be equal across hops.
1134 ///
1135 /// If our peer didn't provide attribution data or the HTLC resolved on chain, the list
1136 /// will be empty.
1137 ///
1138 /// Each entry will correspond with one entry in [`Path::hops`], or, thereafter, the
1139 /// [`BlindedTail::trampoline_hops`] in [`Path::blinded_tail`]. Because not all nodes
1140 /// support hold times, the list may be shorter than the number of hops in the path.
1141 hold_times: Vec<u32>,
1142 },
1143 /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
1144 /// handle the HTLC.
1145 ///
1146 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
1147 /// [`Event::PaymentFailed`].
1148 ///
1149 /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
1150 /// been exhausted.
1151 ///
1152 /// # Failure Behavior and Persistence
1153 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1154 /// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1155 ///
1156 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
1157 PaymentPathFailed {
1158 /// The `payment_id` passed to [`ChannelManager::send_payment`].
1159 ///
1160 /// This will be `Some` for all payment paths which failed on LDK 0.0.103 or later.
1161 ///
1162 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1163 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
1164 payment_id: Option<PaymentId>,
1165 /// The hash that was given to [`ChannelManager::send_payment`].
1166 ///
1167 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1168 payment_hash: PaymentHash,
1169 /// Indicates the payment was rejected for some reason by the recipient. This implies that
1170 /// the payment has failed, not just the route in question. If this is not set, the payment may
1171 /// be retried via a different route.
1172 payment_failed_permanently: bool,
1173 /// Extra error details based on the failure type. May contain an update that needs to be
1174 /// applied to the [`NetworkGraph`].
1175 ///
1176 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1177 failure: PathFailure,
1178 /// The payment path that failed.
1179 path: Path,
1180 /// The channel responsible for the failed payment path.
1181 ///
1182 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
1183 /// may not refer to a channel in the public network graph. These aliases may also collide
1184 /// with channels in the public network graph.
1185 ///
1186 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
1187 /// retried. May be `None` for older [`Event`] serializations.
1188 short_channel_id: Option<u64>,
1189 #[cfg(any(test, feature = "_test_utils"))]
1190 error_code: Option<u16>,
1191 #[cfg(any(test, feature = "_test_utils"))]
1192 error_data: Option<Vec<u8>>,
1193 /// The time that each hop indicated it held the HTLC.
1194 ///
1195 /// The unit in which the hold times are expressed are 100's of milliseconds. So a hop
1196 /// reporting 2 is a hold time that corresponds to between 200 and 299 milliseconds.
1197 ///
1198 /// We expect that at each hop the actual hold time will be strictly greater than the hold
1199 /// time of the following hops, as a node along the path shouldn't have completed the HTLC
1200 /// until the next node has completed it. Note that because hold times are in 100's of ms,
1201 /// hold times as reported are likely to often be equal across hops.
1202 ///
1203 /// If our peer didn't provide attribution data or the HTLC resolved on chain, the list
1204 /// will be empty.
1205 ///
1206 /// Each entry will correspond with one entry in [`Path::hops`], or, thereafter, the
1207 /// [`BlindedTail::trampoline_hops`] in [`Path::blinded_tail`]. Because not all nodes
1208 /// support hold times, the list may be shorter than the number of hops in the path.
1209 hold_times: Vec<u32>,
1210 },
1211 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
1212 ///
1213 /// # Failure Behavior and Persistence
1214 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1215 /// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1216 ProbeSuccessful {
1217 /// The id returned by [`ChannelManager::send_probe`].
1218 ///
1219 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
1220 payment_id: PaymentId,
1221 /// The hash generated by [`ChannelManager::send_probe`].
1222 ///
1223 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
1224 payment_hash: PaymentHash,
1225 /// The payment path that was successful.
1226 path: Path,
1227 },
1228 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
1229 ///
1230 /// # Failure Behavior and Persistence
1231 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1232 /// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1233 ProbeFailed {
1234 /// The id returned by [`ChannelManager::send_probe`].
1235 ///
1236 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
1237 payment_id: PaymentId,
1238 /// The hash generated by [`ChannelManager::send_probe`].
1239 ///
1240 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
1241 payment_hash: PaymentHash,
1242 /// The payment path that failed.
1243 path: Path,
1244 /// The channel responsible for the failed probe.
1245 ///
1246 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
1247 /// may not refer to a channel in the public network graph. These aliases may also collide
1248 /// with channels in the public network graph.
1249 short_channel_id: Option<u64>,
1250 },
1251 /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
1252 /// you've encoded an intercept scid in the receiver's invoice route hints using
1253 /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
1254 ///
1255 /// [`ChannelManager::forward_intercepted_htlc`] or
1256 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
1257 /// their docs for more information.
1258 ///
1259 /// # Failure Behavior and Persistence
1260 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1261 /// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1262 ///
1263 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
1264 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
1265 /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
1266 /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
1267 HTLCIntercepted {
1268 /// An id to help LDK identify which HTLC is being forwarded or failed.
1269 intercept_id: InterceptId,
1270 /// The fake scid that was programmed as the next hop's scid, generated using
1271 /// [`ChannelManager::get_intercept_scid`].
1272 ///
1273 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
1274 requested_next_hop_scid: u64,
1275 /// The payment hash used for this HTLC.
1276 payment_hash: PaymentHash,
1277 /// How many msats were received on the inbound edge of this HTLC.
1278 inbound_amount_msat: u64,
1279 /// How many msats the payer intended to route to the next node. Depending on the reason you are
1280 /// intercepting this payment, you might take a fee by forwarding less than this amount.
1281 /// Forwarding less than this amount may break compatibility with LDK versions prior to 0.0.116.
1282 ///
1283 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
1284 /// check that whatever fee you want has been included here or subtract it as required. Further,
1285 /// LDK will not stop you from forwarding more than you received.
1286 expected_outbound_amount_msat: u64,
1287 },
1288 /// Used to indicate that an output which you should know how to spend was confirmed on chain
1289 /// and is now spendable.
1290 ///
1291 /// Such an output will *never* be spent directly by LDK, and are not at risk of your
1292 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
1293 /// somewhere and spend them when you create on-chain transactions.
1294 ///
1295 /// You may hand them to the [`OutputSweeper`] utility which will store and (re-)generate spending
1296 /// transactions for you.
1297 ///
1298 /// # Failure Behavior and Persistence
1299 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1300 /// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1301 ///
1302 /// [`OutputSweeper`]: crate::util::sweep::OutputSweeper
1303 SpendableOutputs {
1304 /// The outputs which you should store as spendable by you.
1305 outputs: Vec<SpendableOutputDescriptor>,
1306 /// The `channel_id` indicating which channel the spendable outputs belong to.
1307 ///
1308 /// This will always be `Some` for events generated by LDK versions 0.0.117 and above.
1309 channel_id: Option<ChannelId>,
1310 },
1311 /// This event is generated when a payment has been successfully forwarded through us and a
1312 /// forwarding fee earned.
1313 ///
1314 /// # Failure Behavior and Persistence
1315 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1316 /// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1317 PaymentForwarded {
1318 /// The channel id of the incoming channel between the previous node and us.
1319 ///
1320 /// This is only `None` for events generated or serialized by versions prior to 0.0.107.
1321 prev_channel_id: Option<ChannelId>,
1322 /// The channel id of the outgoing channel between the next node and us.
1323 ///
1324 /// This is only `None` for events generated or serialized by versions prior to 0.0.107.
1325 next_channel_id: Option<ChannelId>,
1326 /// The `user_channel_id` of the incoming channel between the previous node and us.
1327 ///
1328 /// This is only `None` for events generated or serialized by versions prior to 0.0.122.
1329 prev_user_channel_id: Option<u128>,
1330 /// The `user_channel_id` of the outgoing channel between the next node and us.
1331 ///
1332 /// This will be `None` if the payment was settled via an on-chain transaction. See the
1333 /// caveat described for the `total_fee_earned_msat` field. Moreover it will be `None` for
1334 /// events generated or serialized by versions prior to 0.0.122.
1335 next_user_channel_id: Option<u128>,
1336 /// The node id of the previous node.
1337 ///
1338 /// This is only `None` for HTLCs received prior to 0.1 or for events serialized by
1339 /// versions prior to 0.1
1340 prev_node_id: Option<PublicKey>,
1341 /// The node id of the next node.
1342 ///
1343 /// This is only `None` for HTLCs received prior to 0.1 or for events serialized by
1344 /// versions prior to 0.1
1345 next_node_id: Option<PublicKey>,
1346 /// The total fee, in milli-satoshis, which was earned as a result of the payment.
1347 ///
1348 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
1349 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
1350 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
1351 /// claimed the full value in millisatoshis from the source. In this case,
1352 /// `claim_from_onchain_tx` will be set.
1353 ///
1354 /// If the channel which sent us the payment has been force-closed, we will claim the funds
1355 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
1356 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
1357 /// `PaymentForwarded` events are generated for the same payment iff `total_fee_earned_msat` is
1358 /// `None`.
1359 total_fee_earned_msat: Option<u64>,
1360 /// The share of the total fee, in milli-satoshis, which was withheld in addition to the
1361 /// forwarding fee.
1362 ///
1363 /// This will only be `Some` if we forwarded an intercepted HTLC with less than the
1364 /// expected amount. This means our counterparty accepted to receive less than the invoice
1365 /// amount, e.g., by claiming the payment featuring a corresponding
1366 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`].
1367 ///
1368 /// Will also always be `None` for events serialized with LDK prior to version 0.0.122.
1369 ///
1370 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
1371 ///
1372 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`]: Self::PaymentClaimable::counterparty_skimmed_fee_msat
1373 skimmed_fee_msat: Option<u64>,
1374 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
1375 /// transaction.
1376 claim_from_onchain_tx: bool,
1377 /// The final amount forwarded, in milli-satoshis, after the fee is deducted.
1378 ///
1379 /// The caveat described above the `total_fee_earned_msat` field applies here as well.
1380 outbound_amount_forwarded_msat: Option<u64>,
1381 },
1382 /// Used to indicate that a channel with the given `channel_id` is being opened and pending
1383 /// confirmation on-chain.
1384 ///
1385 /// This event is emitted when the funding transaction has been signed and is broadcast to the
1386 /// network. For 0conf channels it will be immediately followed by the corresponding
1387 /// [`Event::ChannelReady`] event.
1388 ///
1389 /// # Failure Behavior and Persistence
1390 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1391 /// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1392 ChannelPending {
1393 /// The `channel_id` of the channel that is pending confirmation.
1394 channel_id: ChannelId,
1395 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1396 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1397 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1398 /// `user_channel_id` will be randomized for an inbound channel.
1399 ///
1400 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1401 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1402 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1403 user_channel_id: u128,
1404 /// The `temporary_channel_id` this channel used to be known by during channel establishment.
1405 ///
1406 /// Will be `None` for channels created prior to LDK version 0.0.115.
1407 former_temporary_channel_id: Option<ChannelId>,
1408 /// The `node_id` of the channel counterparty.
1409 counterparty_node_id: PublicKey,
1410 /// The outpoint of the channel's funding transaction.
1411 funding_txo: OutPoint,
1412 /// The features that this channel will operate with.
1413 ///
1414 /// Will be `None` for channels created prior to LDK version 0.0.122.
1415 channel_type: Option<ChannelTypeFeatures>,
1416 /// The witness script that is used to lock the channel's funding output to commitment transactions.
1417 ///
1418 /// This field will be `None` for objects serialized with LDK versions prior to 0.2.0.
1419 funding_redeem_script: Option<ScriptBuf>,
1420 },
1421 /// Used to indicate that a channel with the given `channel_id` is ready to be used. This event
1422 /// is emitted when
1423 /// - the initial funding transaction has been confirmed on-chain to an acceptable depth
1424 /// according to both parties (i.e., `channel_ready` messages were exchanged),
1425 /// - a splice funding transaction has been confirmed on-chain to an acceptable depth according
1426 /// to both parties (i.e., `splice_locked` messages were exchanged), or,
1427 /// - in case of a 0conf channel, when both parties have confirmed the channel establishment.
1428 ///
1429 /// # Failure Behavior and Persistence
1430 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1431 /// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1432 ChannelReady {
1433 /// The `channel_id` of the channel that is ready.
1434 channel_id: ChannelId,
1435 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1436 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1437 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1438 /// `user_channel_id` will be randomized for an inbound channel.
1439 ///
1440 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1441 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1442 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1443 user_channel_id: u128,
1444 /// The `node_id` of the channel counterparty.
1445 counterparty_node_id: PublicKey,
1446 /// The outpoint of the channel's funding transaction.
1447 ///
1448 /// Will be `None` if the channel's funding transaction reached an acceptable depth prior to
1449 /// version 0.2.
1450 funding_txo: Option<OutPoint>,
1451 /// The features that this channel will operate with.
1452 channel_type: ChannelTypeFeatures,
1453 },
1454 /// Used to indicate that a channel that got past the initial handshake with the given `channel_id` is in the
1455 /// process of closure. This includes previously opened channels, and channels that time out from not being funded.
1456 ///
1457 /// Note that this event is only triggered for accepted channels: if the
1458 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true and the channel is
1459 /// rejected, no `ChannelClosed` event will be sent.
1460 ///
1461 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1462 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1463 ///
1464 /// # Failure Behavior and Persistence
1465 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1466 /// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1467 ChannelClosed {
1468 /// The `channel_id` of the channel which has been closed. Note that on-chain transactions
1469 /// resolving the channel are likely still awaiting confirmation.
1470 channel_id: ChannelId,
1471 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1472 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1473 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1474 /// `user_channel_id` will be randomized for inbound channels.
1475 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
1476 /// zero for objects serialized with LDK versions prior to 0.0.102.
1477 ///
1478 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1479 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1480 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1481 user_channel_id: u128,
1482 /// The reason the channel was closed.
1483 reason: ClosureReason,
1484 /// Counterparty in the closed channel.
1485 ///
1486 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
1487 counterparty_node_id: Option<PublicKey>,
1488 /// Channel capacity of the closing channel (sats).
1489 ///
1490 /// This field will be `None` for objects serialized prior to LDK 0.0.117.
1491 channel_capacity_sats: Option<u64>,
1492
1493 /// The original channel funding TXO; this helps checking for the existence and confirmation
1494 /// status of the closing tx.
1495 /// Note that for instances serialized in v0.0.119 or prior this will be missing (None).
1496 channel_funding_txo: Option<transaction::OutPoint>,
1497 /// An upper bound on the our last local balance in msats before the channel was closed.
1498 ///
1499 /// Will overstate our balance as it ignores pending outbound HTLCs and transaction fees.
1500 ///
1501 /// For more accurate balances including fee information see
1502 /// [`ChainMonitor::get_claimable_balances`].
1503 ///
1504 /// This field will be `None` only for objects serialized prior to LDK 0.1.
1505 ///
1506 /// [`ChainMonitor::get_claimable_balances`]: crate::chain::chainmonitor::ChainMonitor::get_claimable_balances
1507 last_local_balance_msat: Option<u64>,
1508 },
1509 /// Used to indicate that a splice for the given `channel_id` has been negotiated and its
1510 /// funding transaction has been broadcast.
1511 ///
1512 /// The splice is then considered pending until both parties have seen enough confirmations to
1513 /// consider the funding locked. Once this occurs, an [`Event::ChannelReady`] will be emitted.
1514 ///
1515 /// Any UTXOs spent by the splice cannot be reused except by an RBF attempt for the same channel.
1516 ///
1517 /// # Failure Behavior and Persistence
1518 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1519 /// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1520 SplicePending {
1521 /// The `channel_id` of the channel that has a pending splice funding transaction.
1522 channel_id: ChannelId,
1523 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1524 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1525 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1526 /// `user_channel_id` will be randomized for an inbound channel.
1527 ///
1528 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1529 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1530 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1531 user_channel_id: u128,
1532 /// The `node_id` of the channel counterparty.
1533 counterparty_node_id: PublicKey,
1534 /// The outpoint of the channel's splice funding transaction.
1535 new_funding_txo: OutPoint,
1536 /// The features that this channel will operate with. Currently, these will be the same
1537 /// features that the channel was opened with, but in the future splices may change them.
1538 channel_type: ChannelTypeFeatures,
1539 /// The witness script that is used to lock the channel's funding output to commitment transactions.
1540 new_funding_redeem_script: ScriptBuf,
1541 },
1542 /// Used to indicate that a splice for the given `channel_id` has failed.
1543 ///
1544 /// This event may be emitted if a splice fails after it has been initiated but prior to signing
1545 /// any negotiated funding transaction.
1546 ///
1547 /// Any UTXOs contributed to be spent by the funding transaction may be reused and will be
1548 /// given in `contributed_inputs`.
1549 ///
1550 /// # Failure Behavior and Persistence
1551 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1552 /// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1553 SpliceFailed {
1554 /// The `channel_id` of the channel for which the splice failed.
1555 channel_id: ChannelId,
1556 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1557 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1558 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1559 /// `user_channel_id` will be randomized for an inbound channel.
1560 ///
1561 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1562 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1563 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1564 user_channel_id: u128,
1565 /// The `node_id` of the channel counterparty.
1566 counterparty_node_id: PublicKey,
1567 /// The outpoint of the channel's splice funding transaction, if one was created.
1568 abandoned_funding_txo: Option<OutPoint>,
1569 /// The features that this channel will operate with, if available.
1570 channel_type: Option<ChannelTypeFeatures>,
1571 /// UTXOs spent as inputs contributed to the splice transaction.
1572 contributed_inputs: Vec<OutPoint>,
1573 /// Outputs contributed to the splice transaction.
1574 contributed_outputs: Vec<TxOut>,
1575 },
1576 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
1577 /// inputs for another purpose.
1578 ///
1579 /// When splicing, users can expect to receive an event for each negotiated splice transaction
1580 /// that did not become locked. The negotiated splice transaction that became locked can be
1581 /// obtained via [`Event::ChannelReady::funding_txo`].
1582 ///
1583 /// This event is not guaranteed to be generated for channels that are closed due to a restart.
1584 ///
1585 /// # Failure Behavior and Persistence
1586 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1587 /// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1588 DiscardFunding {
1589 /// The channel_id of the channel which has been closed.
1590 channel_id: ChannelId,
1591 /// The full transaction received from the user
1592 funding_info: FundingInfo,
1593 },
1594 /// Indicates a request to open a new channel by a peer.
1595 ///
1596 /// To accept the request (and in the case of a dual-funded channel, not contribute funds),
1597 /// call [`ChannelManager::accept_inbound_channel`].
1598 /// To reject the request, call [`ChannelManager::force_close_broadcasting_latest_txn`].
1599 /// Note that a [`ChannelClosed`] event will _not_ be triggered if the channel is rejected.
1600 ///
1601 /// The event is only triggered when a new open channel request is received and the
1602 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
1603 ///
1604 /// # Failure Behavior and Persistence
1605 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1606 /// returning `Err(ReplayEvent ())`) and won't be persisted across restarts.
1607 ///
1608 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1609 /// [`ChannelClosed`]: Event::ChannelClosed
1610 /// [`ChannelManager::force_close_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_broadcasting_latest_txn
1611 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1612 OpenChannelRequest {
1613 /// The temporary channel ID of the channel requested to be opened.
1614 ///
1615 /// When responding to the request, the `temporary_channel_id` should be passed
1616 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
1617 /// or through [`ChannelManager::force_close_broadcasting_latest_txn`] to reject.
1618 ///
1619 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1620 /// [`ChannelManager::force_close_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_broadcasting_latest_txn
1621 temporary_channel_id: ChannelId,
1622 /// The node_id of the counterparty requesting to open the channel.
1623 ///
1624 /// When responding to the request, the `counterparty_node_id` should be passed
1625 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
1626 /// accept the request, or through [`ChannelManager::force_close_broadcasting_latest_txn`]
1627 /// to reject the request.
1628 ///
1629 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1630 /// [`ChannelManager::force_close_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_broadcasting_latest_txn
1631 counterparty_node_id: PublicKey,
1632 /// The channel value of the requested channel.
1633 funding_satoshis: u64,
1634 /// If `channel_negotiation_type` is `InboundChannelFunds::DualFunded`, this indicates that the peer wishes to
1635 /// open a dual-funded channel. Otherwise, this field will be `InboundChannelFunds::PushMsats`,
1636 /// indicating the `push_msats` value our peer is pushing to us for a non-dual-funded channel.
1637 channel_negotiation_type: InboundChannelFunds,
1638 /// The features that this channel will operate with. If you reject the channel, a
1639 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
1640 /// feature flags.
1641 ///
1642 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
1643 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1644 /// 0.0.106.
1645 ///
1646 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
1647 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
1648 /// 0.0.107. Channels setting this type also need to get manually accepted via
1649 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
1650 /// or will be rejected otherwise.
1651 ///
1652 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1653 channel_type: ChannelTypeFeatures,
1654 /// True if this channel is (or will be) publicly-announced.
1655 is_announced: bool,
1656 /// Channel parameters given by the counterparty.
1657 params: msgs::ChannelParameters,
1658 },
1659 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
1660 /// forward it.
1661 ///
1662 /// # Failure Behavior and Persistence
1663 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1664 /// returning `Err(ReplayEvent ())`) and will be persisted across restarts.
1665 HTLCHandlingFailed {
1666 /// The channel over which the HTLC was received.
1667 prev_channel_id: ChannelId,
1668 /// The type of HTLC handling that failed.
1669 failure_type: HTLCHandlingFailureType,
1670 /// The reason that the HTLC failed.
1671 ///
1672 /// This field will be `None` only for objects serialized prior to LDK 0.2.0.
1673 failure_reason: Option<HTLCHandlingFailureReason>,
1674 },
1675 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
1676 /// requires confirmed external funds to be readily available to spend.
1677 ///
1678 /// LDK does not currently generate this event unless either the
1679 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`] or the
1680 /// [`ChannelHandshakeConfig::negotiate_anchor_zero_fee_commitments`] config flags are set to
1681 /// true.
1682 /// It is limited to the scope of channels with anchor outputs.
1683 ///
1684 /// # Failure Behavior and Persistence
1685 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1686 /// returning `Err(ReplayEvent ())`), but will only be regenerated as needed after restarts.
1687 ///
1688 /// [`ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx`]: crate::util::config::ChannelHandshakeConfig::negotiate_anchors_zero_fee_htlc_tx
1689 /// [`ChannelHandshakeConfig::negotiate_anchor_zero_fee_commitments`]: crate::util::config::ChannelHandshakeConfig::negotiate_anchor_zero_fee_commitments
1690 BumpTransaction(BumpTransactionEvent),
1691 /// We received an onion message that is intended to be forwarded to a peer
1692 /// that is currently offline. This event will only be generated if the
1693 /// `OnionMessenger` was initialized with
1694 /// [`OnionMessenger::new_with_offline_peer_interception`], see its docs.
1695 ///
1696 /// The offline peer should be awoken if possible on receipt of this event, such as via the LSPS5
1697 /// protocol.
1698 ///
1699 /// Once they connect, you should handle the generated [`Event::OnionMessagePeerConnected`] and
1700 /// provide the stored message.
1701 ///
1702 /// # Failure Behavior and Persistence
1703 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1704 /// returning `Err(ReplayEvent ())`), but won't be persisted across restarts.
1705 ///
1706 /// [`OnionMessenger::new_with_offline_peer_interception`]: crate::onion_message::messenger::OnionMessenger::new_with_offline_peer_interception
1707 OnionMessageIntercepted {
1708 /// The node id of the offline peer.
1709 peer_node_id: PublicKey,
1710 /// The onion message intended to be forwarded to `peer_node_id`.
1711 message: msgs::OnionMessage,
1712 },
1713 /// Indicates that an onion message supporting peer has come online and any messages previously
1714 /// stored for them (from [`Event::OnionMessageIntercepted`]s) should be forwarded to them by
1715 /// calling [`OnionMessenger::forward_onion_message`].
1716 ///
1717 /// This event will only be generated if the `OnionMessenger` was initialized with
1718 /// [`OnionMessenger::new_with_offline_peer_interception`], see its docs.
1719 ///
1720 /// # Failure Behavior and Persistence
1721 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1722 /// returning `Err(ReplayEvent ())`), but won't be persisted across restarts.
1723 ///
1724 /// [`OnionMessenger::forward_onion_message`]: crate::onion_message::messenger::OnionMessenger::forward_onion_message
1725 /// [`OnionMessenger::new_with_offline_peer_interception`]: crate::onion_message::messenger::OnionMessenger::new_with_offline_peer_interception
1726 OnionMessagePeerConnected {
1727 /// The node id of the peer we just connected to, who advertises support for
1728 /// onion messages.
1729 peer_node_id: PublicKey,
1730 },
1731 /// As a static invoice server, we received a [`StaticInvoice`] from an async recipient that wants
1732 /// us to serve the invoice to payers on their behalf when they are offline. This event will only
1733 /// be generated if we previously created paths using
1734 /// [`ChannelManager::blinded_paths_for_async_recipient`] and the recipient was configured with
1735 /// them via [`ChannelManager::set_paths_to_static_invoice_server`].
1736 ///
1737 /// [`ChannelManager::blinded_paths_for_async_recipient`]: crate::ln::channelmanager::ChannelManager::blinded_paths_for_async_recipient
1738 /// [`ChannelManager::set_paths_to_static_invoice_server`]: crate::ln::channelmanager::ChannelManager::set_paths_to_static_invoice_server
1739 PersistStaticInvoice {
1740 /// The invoice that should be persisted and later provided to payers when handling a future
1741 /// [`Event::StaticInvoiceRequested`].
1742 invoice: StaticInvoice,
1743 /// The path to where invoice requests will be forwarded. If we receive an invoice
1744 /// request, we'll forward it to the async recipient over this path in case the
1745 /// recipient is online to provide a new invoice. This path should be persisted and
1746 /// later provided to [`ChannelManager::respond_to_static_invoice_request`].
1747 ///
1748 /// This path's [`BlindedMessagePath::introduction_node`] MUST be set to our node or one of our
1749 /// peers. This is because, for DoS protection, invoice requests forwarded over this path are
1750 /// treated by our node like any other onion message forward and will not generate
1751 /// [`Event::ConnectionNeeded`] if the first hop in the path is not our peer.
1752 ///
1753 /// If the next-hop peer in the path is offline, if configured to do so we will generate an
1754 /// [`Event::OnionMessageIntercepted`] for the invoice request.
1755 ///
1756 /// [`ChannelManager::respond_to_static_invoice_request`]: crate::ln::channelmanager::ChannelManager::respond_to_static_invoice_request
1757 invoice_request_path: BlindedMessagePath,
1758 /// Useful for the recipient to replace a specific invoice stored by us as the static invoice
1759 /// server.
1760 ///
1761 /// When this invoice and its metadata are persisted, this slot number should be included so if
1762 /// we receive another [`Event::PersistStaticInvoice`] containing the same slot number we can
1763 /// swap the existing invoice out for the new one.
1764 invoice_slot: u16,
1765 /// An identifier for the recipient, originally provided to
1766 /// [`ChannelManager::blinded_paths_for_async_recipient`].
1767 ///
1768 /// When an [`Event::StaticInvoiceRequested`] comes in for the invoice, this id will be surfaced
1769 /// and can be used alongside the `invoice_slot` to retrieve the invoice from the database.
1770 ///
1771 ///[`ChannelManager::blinded_paths_for_async_recipient`]: crate::ln::channelmanager::ChannelManager::blinded_paths_for_async_recipient
1772 recipient_id: Vec<u8>,
1773 /// Once the [`StaticInvoice`] and `invoice_slot` are persisted,
1774 /// [`ChannelManager::static_invoice_persisted`] should be called with this responder to confirm
1775 /// to the recipient that their [`Offer`] is ready to be used for async payments.
1776 ///
1777 /// [`ChannelManager::static_invoice_persisted`]: crate::ln::channelmanager::ChannelManager::static_invoice_persisted
1778 /// [`Offer`]: crate::offers::offer::Offer
1779 invoice_persisted_path: Responder,
1780 },
1781 /// As a static invoice server, we received an [`InvoiceRequest`] on behalf of an often-offline
1782 /// recipient for whom we are serving [`StaticInvoice`]s.
1783 ///
1784 /// This event will only be generated if we previously created paths using
1785 /// [`ChannelManager::blinded_paths_for_async_recipient`] and the recipient was configured with
1786 /// them via [`ChannelManager::set_paths_to_static_invoice_server`].
1787 ///
1788 /// If we previously persisted a [`StaticInvoice`] from an [`Event::PersistStaticInvoice`] that
1789 /// matches the below `recipient_id` and `invoice_slot`, that invoice should be retrieved now
1790 /// and forwarded to the payer via [`ChannelManager::respond_to_static_invoice_request`].
1791 /// The invoice request path previously persisted from [`Event::PersistStaticInvoice`] should
1792 /// also be provided in [`ChannelManager::respond_to_static_invoice_request`].
1793 ///
1794 /// [`ChannelManager::blinded_paths_for_async_recipient`]: crate::ln::channelmanager::ChannelManager::blinded_paths_for_async_recipient
1795 /// [`ChannelManager::set_paths_to_static_invoice_server`]: crate::ln::channelmanager::ChannelManager::set_paths_to_static_invoice_server
1796 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
1797 /// [`ChannelManager::respond_to_static_invoice_request`]: crate::ln::channelmanager::ChannelManager::respond_to_static_invoice_request
1798 StaticInvoiceRequested {
1799 /// An identifier for the recipient previously surfaced in
1800 /// [`Event::PersistStaticInvoice::recipient_id`]. Useful when paired with the `invoice_slot` to
1801 /// retrieve the [`StaticInvoice`] requested by the payer.
1802 recipient_id: Vec<u8>,
1803 /// The slot number for the invoice being requested, previously surfaced in
1804 /// [`Event::PersistStaticInvoice::invoice_slot`]. Useful when paired with the `recipient_id` to
1805 /// retrieve the [`StaticInvoice`] requested by the payer.
1806 invoice_slot: u16,
1807 /// The path over which the [`StaticInvoice`] will be sent to the payer, which should be
1808 /// provided to [`ChannelManager::respond_to_static_invoice_request`] along with the invoice.
1809 ///
1810 /// [`ChannelManager::respond_to_static_invoice_request`]: crate::ln::channelmanager::ChannelManager::respond_to_static_invoice_request
1811 reply_path: Responder,
1812 /// The invoice request that will be forwarded to the async recipient to give the
1813 /// recipient a chance to provide an invoice in case it is online. It should be
1814 /// provided to [`ChannelManager::respond_to_static_invoice_request`].
1815 ///
1816 /// [`ChannelManager::respond_to_static_invoice_request`]: crate::ln::channelmanager::ChannelManager::respond_to_static_invoice_request
1817 invoice_request: InvoiceRequest,
1818 },
1819 /// Indicates that a channel funding transaction constructed interactively is ready to be
1820 /// signed. This event will only be triggered if at least one input was contributed.
1821 ///
1822 /// The transaction contains all inputs and outputs provided by both parties including the
1823 /// channel's funding output and a change output if applicable.
1824 ///
1825 /// No part of the transaction should be changed before signing as the content of the transaction
1826 /// has already been negotiated with the counterparty.
1827 ///
1828 /// Each signature MUST use the `SIGHASH_ALL` flag to avoid invalidation of the initial commitment and
1829 /// hence possible loss of funds.
1830 ///
1831 /// After signing, call [`ChannelManager::funding_transaction_signed`] with the (partially) signed
1832 /// funding transaction.
1833 ///
1834 /// Generated in [`ChannelManager`] message handling.
1835 ///
1836 /// # Failure Behavior and Persistence
1837 /// This event will eventually be replayed after failures-to-handle (i.e., the event handler
1838 /// returning `Err(ReplayEvent ())`), but will only be regenerated as needed after restarts.
1839 ///
1840 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1841 /// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1842 FundingTransactionReadyForSigning {
1843 /// The `channel_id` of the channel which you'll need to pass back into
1844 /// [`ChannelManager::funding_transaction_signed`].
1845 ///
1846 /// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1847 channel_id: ChannelId,
1848 /// The counterparty's `node_id`, which you'll need to pass back into
1849 /// [`ChannelManager::funding_transaction_signed`].
1850 ///
1851 /// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1852 counterparty_node_id: PublicKey,
1853 /// The `user_channel_id` value passed in for outbound channels, or for inbound channels if
1854 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1855 /// `user_channel_id` will be randomized for inbound channels.
1856 ///
1857 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1858 user_channel_id: u128,
1859 /// The unsigned transaction to be signed and passed back to
1860 /// [`ChannelManager::funding_transaction_signed`].
1861 ///
1862 /// [`ChannelManager::funding_transaction_signed`]: crate::ln::channelmanager::ChannelManager::funding_transaction_signed
1863 unsigned_transaction: Transaction,
1864 },
1865}
1866
1867impl Writeable for Event {
1868 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1869 match self {
1870 &Event::FundingGenerationReady { .. } => {
1871 0u8.write(writer)?;
1872 // We never write out FundingGenerationReady events as, upon disconnection, peers
1873 // drop any channels which have not yet exchanged funding_signed.
1874 },
1875 &Event::PaymentClaimable {
1876 ref payment_hash,
1877 ref amount_msat,
1878 counterparty_skimmed_fee_msat,
1879 ref purpose,
1880 ref receiver_node_id,
1881 ref receiving_channel_ids,
1882 ref claim_deadline,
1883 ref onion_fields,
1884 ref payment_id,
1885 } => {
1886 1u8.write(writer)?;
1887 let mut payment_secret = None;
1888 let payment_preimage;
1889 let mut payment_context = None;
1890 match &purpose {
1891 PaymentPurpose::Bolt11InvoicePayment {
1892 payment_preimage: preimage,
1893 payment_secret: secret,
1894 } => {
1895 payment_secret = Some(secret);
1896 payment_preimage = *preimage;
1897 },
1898 PaymentPurpose::Bolt12OfferPayment {
1899 payment_preimage: preimage,
1900 payment_secret: secret,
1901 payment_context: context,
1902 } => {
1903 payment_secret = Some(secret);
1904 payment_preimage = *preimage;
1905 payment_context = Some(PaymentContextRef::Bolt12Offer(context));
1906 },
1907 PaymentPurpose::Bolt12RefundPayment {
1908 payment_preimage: preimage,
1909 payment_secret: secret,
1910 payment_context: context,
1911 } => {
1912 payment_secret = Some(secret);
1913 payment_preimage = *preimage;
1914 payment_context = Some(PaymentContextRef::Bolt12Refund(context));
1915 },
1916 PaymentPurpose::SpontaneousPayment(preimage) => {
1917 payment_preimage = Some(*preimage);
1918 },
1919 }
1920 let skimmed_fee_opt = if counterparty_skimmed_fee_msat == 0 {
1921 None
1922 } else {
1923 Some(counterparty_skimmed_fee_msat)
1924 };
1925
1926 let (receiving_channel_id_legacy, receiving_user_channel_id_legacy) =
1927 match receiving_channel_ids.last() {
1928 Some((chan_id, user_chan_id)) => (Some(*chan_id), *user_chan_id),
1929 None => (None, None),
1930 };
1931 write_tlv_fields!(writer, {
1932 (0, payment_hash, required),
1933 (1, receiver_node_id, option),
1934 (2, payment_secret, option),
1935 // Marked as legacy in version 0.2.0; superseded by `receiving_channel_ids`,
1936 // which includes all channel IDs used in the payment instead of only the last
1937 // one.
1938 (3, receiving_channel_id_legacy, option),
1939 (4, amount_msat, required),
1940 // Marked as legacy in version 0.2.0 for the same reason as
1941 // `receiving_channel_id_legacy`; superseded by `receiving_channel_ids`.
1942 (5, receiving_user_channel_id_legacy, option),
1943 // Type 6 was `user_payment_id` on 0.0.103 and earlier
1944 (7, claim_deadline, option),
1945 (8, payment_preimage, option),
1946 (9, onion_fields, option),
1947 (10, skimmed_fee_opt, option),
1948 (11, payment_context, option),
1949 (13, payment_id, option),
1950 (15, *receiving_channel_ids, optional_vec),
1951 });
1952 },
1953 &Event::PaymentSent {
1954 ref payment_id,
1955 ref payment_preimage,
1956 ref payment_hash,
1957 ref amount_msat,
1958 ref fee_paid_msat,
1959 ref bolt12_invoice,
1960 } => {
1961 2u8.write(writer)?;
1962 write_tlv_fields!(writer, {
1963 (0, payment_preimage, required),
1964 (1, payment_hash, required),
1965 (3, payment_id, option),
1966 (5, fee_paid_msat, option),
1967 (7, amount_msat, option),
1968 (9, bolt12_invoice, option),
1969 });
1970 },
1971 &Event::PaymentPathFailed {
1972 ref payment_id,
1973 ref payment_hash,
1974 ref payment_failed_permanently,
1975 ref failure,
1976 ref path,
1977 ref short_channel_id,
1978 #[cfg(any(test, feature = "_test_utils"))]
1979 ref error_code,
1980 #[cfg(any(test, feature = "_test_utils"))]
1981 ref error_data,
1982 ref hold_times,
1983 } => {
1984 3u8.write(writer)?;
1985 #[cfg(any(test, feature = "_test_utils"))]
1986 error_code.write(writer)?;
1987 #[cfg(any(test, feature = "_test_utils"))]
1988 error_data.write(writer)?;
1989 write_tlv_fields!(writer, {
1990 (0, payment_hash, required),
1991 (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
1992 (2, payment_failed_permanently, required),
1993 (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
1994 (4, path.blinded_tail, option),
1995 (5, path.hops, required_vec),
1996 (7, short_channel_id, option),
1997 (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
1998 (11, payment_id, option),
1999 (13, failure, required),
2000 (15, *hold_times, optional_vec),
2001 });
2002 },
2003 // 4u8 used to be `PendingHTLCsForwardable`
2004 &Event::SpendableOutputs { ref outputs, channel_id } => {
2005 5u8.write(writer)?;
2006 write_tlv_fields!(writer, {
2007 (0, WithoutLength(outputs), required),
2008 (1, channel_id, option),
2009 });
2010 },
2011 &Event::HTLCIntercepted {
2012 requested_next_hop_scid,
2013 payment_hash,
2014 inbound_amount_msat,
2015 expected_outbound_amount_msat,
2016 intercept_id,
2017 } => {
2018 6u8.write(writer)?;
2019 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
2020 write_tlv_fields!(writer, {
2021 (0, intercept_id, required),
2022 (2, intercept_scid, required),
2023 (4, payment_hash, required),
2024 (6, inbound_amount_msat, required),
2025 (8, expected_outbound_amount_msat, required),
2026 });
2027 },
2028 &Event::PaymentForwarded {
2029 prev_channel_id,
2030 next_channel_id,
2031 prev_user_channel_id,
2032 next_user_channel_id,
2033 prev_node_id,
2034 next_node_id,
2035 total_fee_earned_msat,
2036 skimmed_fee_msat,
2037 claim_from_onchain_tx,
2038 outbound_amount_forwarded_msat,
2039 } => {
2040 7u8.write(writer)?;
2041 write_tlv_fields!(writer, {
2042 (0, total_fee_earned_msat, option),
2043 (1, prev_channel_id, option),
2044 (2, claim_from_onchain_tx, required),
2045 (3, next_channel_id, option),
2046 (5, outbound_amount_forwarded_msat, option),
2047 (7, skimmed_fee_msat, option),
2048 (9, prev_user_channel_id, option),
2049 (11, next_user_channel_id, option),
2050 (13, prev_node_id, option),
2051 (15, next_node_id, option),
2052 });
2053 },
2054 &Event::ChannelClosed {
2055 ref channel_id,
2056 ref user_channel_id,
2057 ref reason,
2058 ref counterparty_node_id,
2059 ref channel_capacity_sats,
2060 ref channel_funding_txo,
2061 ref last_local_balance_msat,
2062 } => {
2063 9u8.write(writer)?;
2064 // `user_channel_id` used to be a single u64 value. In order to remain backwards
2065 // compatible with versions prior to 0.0.113, the u128 is serialized as two
2066 // separate u64 values.
2067 let user_channel_id_low = *user_channel_id as u64;
2068 let user_channel_id_high = (*user_channel_id >> 64) as u64;
2069 write_tlv_fields!(writer, {
2070 (0, channel_id, required),
2071 (1, user_channel_id_low, required),
2072 (2, reason, required),
2073 (3, user_channel_id_high, required),
2074 (5, counterparty_node_id, option),
2075 (7, channel_capacity_sats, option),
2076 (9, channel_funding_txo, option),
2077 (11, last_local_balance_msat, option)
2078 });
2079 },
2080 &Event::DiscardFunding { ref channel_id, ref funding_info } => {
2081 11u8.write(writer)?;
2082
2083 let transaction = if let FundingInfo::Tx { transaction } = funding_info {
2084 Some(transaction)
2085 } else {
2086 None
2087 };
2088 write_tlv_fields!(writer, {
2089 (0, channel_id, required),
2090 (2, transaction, option),
2091 (4, funding_info, required),
2092 })
2093 },
2094 &Event::PaymentPathSuccessful {
2095 ref payment_id,
2096 ref payment_hash,
2097 ref path,
2098 ref hold_times,
2099 } => {
2100 13u8.write(writer)?;
2101 write_tlv_fields!(writer, {
2102 (0, payment_id, required),
2103 (1, *hold_times, optional_vec),
2104 (2, payment_hash, option),
2105 (4, path.hops, required_vec),
2106 (6, path.blinded_tail, option),
2107 })
2108 },
2109 &Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
2110 15u8.write(writer)?;
2111 let (payment_hash, invoice_received) = match payment_hash {
2112 Some(payment_hash) => (payment_hash, true),
2113 None => (&PaymentHash([0; 32]), false),
2114 };
2115 let legacy_reason = match reason {
2116 None => &None,
2117 // Variants available prior to version 0.0.124.
2118 Some(PaymentFailureReason::RecipientRejected)
2119 | Some(PaymentFailureReason::UserAbandoned)
2120 | Some(PaymentFailureReason::RetriesExhausted)
2121 | Some(PaymentFailureReason::PaymentExpired)
2122 | Some(PaymentFailureReason::RouteNotFound)
2123 | Some(PaymentFailureReason::UnexpectedError) => reason,
2124 // Variants introduced at version 0.0.124 or later. Prior versions fail to parse
2125 // unknown variants, while versions 0.0.124 or later will use None.
2126 Some(PaymentFailureReason::UnknownRequiredFeatures) => {
2127 &Some(PaymentFailureReason::RecipientRejected)
2128 },
2129 Some(PaymentFailureReason::InvoiceRequestExpired) => {
2130 &Some(PaymentFailureReason::RetriesExhausted)
2131 },
2132 Some(PaymentFailureReason::InvoiceRequestRejected) => {
2133 &Some(PaymentFailureReason::RecipientRejected)
2134 },
2135 Some(PaymentFailureReason::BlindedPathCreationFailed) => {
2136 &Some(PaymentFailureReason::RouteNotFound)
2137 },
2138 };
2139 write_tlv_fields!(writer, {
2140 (0, payment_id, required),
2141 (1, legacy_reason, option),
2142 (2, payment_hash, required),
2143 (3, invoice_received, required),
2144 (5, reason, option),
2145 })
2146 },
2147 &Event::OpenChannelRequest { .. } => {
2148 17u8.write(writer)?;
2149 // We never write the OpenChannelRequest events as, upon disconnection, peers
2150 // drop any channels which have not yet exchanged funding_signed.
2151 },
2152 &Event::PaymentClaimed {
2153 ref payment_hash,
2154 ref amount_msat,
2155 ref purpose,
2156 ref receiver_node_id,
2157 ref htlcs,
2158 ref sender_intended_total_msat,
2159 ref onion_fields,
2160 ref payment_id,
2161 } => {
2162 19u8.write(writer)?;
2163 write_tlv_fields!(writer, {
2164 (0, payment_hash, required),
2165 (1, receiver_node_id, option),
2166 (2, purpose, required),
2167 (4, amount_msat, required),
2168 (5, *htlcs, optional_vec),
2169 (7, sender_intended_total_msat, option),
2170 (9, onion_fields, option),
2171 (11, payment_id, option),
2172 });
2173 },
2174 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
2175 21u8.write(writer)?;
2176 write_tlv_fields!(writer, {
2177 (0, payment_id, required),
2178 (2, payment_hash, required),
2179 (4, path.hops, required_vec),
2180 (6, path.blinded_tail, option),
2181 })
2182 },
2183 &Event::ProbeFailed {
2184 ref payment_id,
2185 ref payment_hash,
2186 ref path,
2187 ref short_channel_id,
2188 } => {
2189 23u8.write(writer)?;
2190 write_tlv_fields!(writer, {
2191 (0, payment_id, required),
2192 (2, payment_hash, required),
2193 (4, path.hops, required_vec),
2194 (6, short_channel_id, option),
2195 (8, path.blinded_tail, option),
2196 })
2197 },
2198 &Event::HTLCHandlingFailed {
2199 ref prev_channel_id,
2200 ref failure_type,
2201 ref failure_reason,
2202 } => {
2203 25u8.write(writer)?;
2204 write_tlv_fields!(writer, {
2205 (0, prev_channel_id, required),
2206 (1, failure_reason, option),
2207 (2, failure_type, required),
2208 })
2209 },
2210 &Event::BumpTransaction(ref event) => {
2211 27u8.write(writer)?;
2212 match event {
2213 // We never write the ChannelClose|HTLCResolution events as they'll be replayed
2214 // upon restarting anyway if they remain unresolved.
2215 BumpTransactionEvent::ChannelClose { .. } => {},
2216 BumpTransactionEvent::HTLCResolution { .. } => {},
2217 }
2218 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
2219 },
2220 &Event::ChannelReady {
2221 ref channel_id,
2222 ref user_channel_id,
2223 ref counterparty_node_id,
2224 ref funding_txo,
2225 ref channel_type,
2226 } => {
2227 29u8.write(writer)?;
2228 write_tlv_fields!(writer, {
2229 (0, channel_id, required),
2230 (1, funding_txo, option),
2231 (2, user_channel_id, required),
2232 (4, counterparty_node_id, required),
2233 (6, channel_type, required),
2234 });
2235 },
2236 &Event::ChannelPending {
2237 ref channel_id,
2238 ref user_channel_id,
2239 ref former_temporary_channel_id,
2240 ref counterparty_node_id,
2241 ref funding_txo,
2242 ref channel_type,
2243 ref funding_redeem_script,
2244 } => {
2245 31u8.write(writer)?;
2246 write_tlv_fields!(writer, {
2247 (0, channel_id, required),
2248 (1, channel_type, option),
2249 (2, user_channel_id, required),
2250 (4, former_temporary_channel_id, required),
2251 (6, counterparty_node_id, required),
2252 (8, funding_txo, required),
2253 (9, funding_redeem_script, option),
2254 });
2255 },
2256 &Event::ConnectionNeeded { .. } => {
2257 35u8.write(writer)?;
2258 // Never write ConnectionNeeded events as buffered onion messages aren't serialized.
2259 },
2260 &Event::OnionMessageIntercepted { ref peer_node_id, ref message } => {
2261 37u8.write(writer)?;
2262 write_tlv_fields!(writer, {
2263 (0, peer_node_id, required),
2264 (2, message, required),
2265 });
2266 },
2267 &Event::OnionMessagePeerConnected { ref peer_node_id } => {
2268 39u8.write(writer)?;
2269 write_tlv_fields!(writer, {
2270 (0, peer_node_id, required),
2271 });
2272 },
2273 &Event::InvoiceReceived { ref payment_id, ref invoice, ref context, ref responder } => {
2274 41u8.write(writer)?;
2275 write_tlv_fields!(writer, {
2276 (0, payment_id, required),
2277 (2, invoice, required),
2278 (4, context, option),
2279 (6, responder, option),
2280 });
2281 },
2282 &Event::FundingTxBroadcastSafe {
2283 ref channel_id,
2284 ref user_channel_id,
2285 ref funding_txo,
2286 ref counterparty_node_id,
2287 ref former_temporary_channel_id,
2288 } => {
2289 43u8.write(writer)?;
2290 write_tlv_fields!(writer, {
2291 (0, channel_id, required),
2292 (2, user_channel_id, required),
2293 (4, funding_txo, required),
2294 (6, counterparty_node_id, required),
2295 (8, former_temporary_channel_id, required),
2296 });
2297 },
2298 &Event::PersistStaticInvoice { .. } => {
2299 45u8.write(writer)?;
2300 // No need to write these events because we can just restart the static invoice negotiation
2301 // on startup.
2302 },
2303 &Event::StaticInvoiceRequested { .. } => {
2304 47u8.write(writer)?;
2305 // Never write StaticInvoiceRequested events as buffered onion messages aren't serialized.
2306 },
2307 &Event::FundingTransactionReadyForSigning { .. } => {
2308 49u8.write(writer)?;
2309 // We never write out FundingTransactionReadyForSigning events as they will be regenerated when
2310 // necessary.
2311 },
2312 &Event::SplicePending {
2313 ref channel_id,
2314 ref user_channel_id,
2315 ref counterparty_node_id,
2316 ref new_funding_txo,
2317 ref channel_type,
2318 ref new_funding_redeem_script,
2319 } => {
2320 50u8.write(writer)?;
2321 write_tlv_fields!(writer, {
2322 (1, channel_id, required),
2323 (3, channel_type, required),
2324 (5, user_channel_id, required),
2325 (7, counterparty_node_id, required),
2326 (9, new_funding_txo, required),
2327 (11, new_funding_redeem_script, required),
2328 });
2329 },
2330 &Event::SpliceFailed {
2331 ref channel_id,
2332 ref user_channel_id,
2333 ref counterparty_node_id,
2334 ref abandoned_funding_txo,
2335 ref channel_type,
2336 ref contributed_inputs,
2337 ref contributed_outputs,
2338 } => {
2339 52u8.write(writer)?;
2340 write_tlv_fields!(writer, {
2341 (1, channel_id, required),
2342 (3, channel_type, option),
2343 (5, user_channel_id, required),
2344 (7, counterparty_node_id, required),
2345 (9, abandoned_funding_txo, option),
2346 (11, *contributed_inputs, optional_vec),
2347 (13, *contributed_outputs, optional_vec),
2348 });
2349 },
2350 // Note that, going forward, all new events must only write data inside of
2351 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
2352 // data via `write_tlv_fields`.
2353 }
2354 Ok(())
2355 }
2356}
2357impl MaybeReadable for Event {
2358 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
2359 match Readable::read(reader)? {
2360 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events.
2361 0u8 => Ok(None),
2362 1u8 => {
2363 let mut f = || {
2364 let mut payment_hash = PaymentHash([0; 32]);
2365 let mut payment_preimage = None;
2366 let mut payment_secret = None;
2367 let mut amount_msat = 0;
2368 let mut counterparty_skimmed_fee_msat_opt = None;
2369 let mut receiver_node_id = None;
2370 let mut _user_payment_id = None::<u64>; // Used in 0.0.103 and earlier, no longer written in 0.0.116+.
2371 let mut receiving_channel_id_legacy = None;
2372 let mut claim_deadline = None;
2373 let mut receiving_user_channel_id_legacy = None;
2374 let mut onion_fields = None;
2375 let mut payment_context = None;
2376 let mut payment_id = None;
2377 let mut receiving_channel_ids_opt = None;
2378 read_tlv_fields!(reader, {
2379 (0, payment_hash, required),
2380 (1, receiver_node_id, option),
2381 (2, payment_secret, option),
2382 (3, receiving_channel_id_legacy, option),
2383 (4, amount_msat, required),
2384 (5, receiving_user_channel_id_legacy, option),
2385 (6, _user_payment_id, option),
2386 (7, claim_deadline, option),
2387 (8, payment_preimage, option),
2388 (9, onion_fields, option),
2389 (10, counterparty_skimmed_fee_msat_opt, option),
2390 (11, payment_context, option),
2391 (13, payment_id, option),
2392 (15, receiving_channel_ids_opt, optional_vec),
2393 });
2394 let purpose = match payment_secret {
2395 Some(secret) => {
2396 PaymentPurpose::from_parts(payment_preimage, secret, payment_context)
2397 .map_err(|()| msgs::DecodeError::InvalidValue)?
2398 },
2399 None if payment_preimage.is_some() => {
2400 PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap())
2401 },
2402 None => return Err(msgs::DecodeError::InvalidValue),
2403 };
2404
2405 let receiving_channel_ids = receiving_channel_ids_opt
2406 .or_else(|| {
2407 receiving_channel_id_legacy
2408 .map(|chan_id| vec![(chan_id, receiving_user_channel_id_legacy)])
2409 })
2410 .unwrap_or_default();
2411
2412 Ok(Some(Event::PaymentClaimable {
2413 receiver_node_id,
2414 payment_hash,
2415 amount_msat,
2416 counterparty_skimmed_fee_msat: counterparty_skimmed_fee_msat_opt
2417 .unwrap_or(0),
2418 purpose,
2419 receiving_channel_ids,
2420 claim_deadline,
2421 onion_fields,
2422 payment_id,
2423 }))
2424 };
2425 f()
2426 },
2427 2u8 => {
2428 let mut f = || {
2429 let mut payment_preimage = PaymentPreimage([0; 32]);
2430 let mut payment_hash = None;
2431 let mut payment_id = None;
2432 let mut amount_msat = None;
2433 let mut fee_paid_msat = None;
2434 let mut bolt12_invoice = None;
2435 read_tlv_fields!(reader, {
2436 (0, payment_preimage, required),
2437 (1, payment_hash, option),
2438 (3, payment_id, option),
2439 (5, fee_paid_msat, option),
2440 (7, amount_msat, option),
2441 (9, bolt12_invoice, option),
2442 });
2443 if payment_hash.is_none() {
2444 payment_hash = Some(PaymentHash(
2445 Sha256::hash(&payment_preimage.0[..]).to_byte_array(),
2446 ));
2447 }
2448 Ok(Some(Event::PaymentSent {
2449 payment_id,
2450 payment_preimage,
2451 payment_hash: payment_hash.unwrap(),
2452 amount_msat,
2453 fee_paid_msat,
2454 bolt12_invoice,
2455 }))
2456 };
2457 f()
2458 },
2459 3u8 => {
2460 let mut f = || {
2461 #[cfg(any(test, feature = "_test_utils"))]
2462 let error_code = Readable::read(reader)?;
2463 #[cfg(any(test, feature = "_test_utils"))]
2464 let error_data = Readable::read(reader)?;
2465 let mut payment_hash = PaymentHash([0; 32]);
2466 let mut payment_failed_permanently = false;
2467 let mut network_update = None;
2468 let mut blinded_tail: Option<BlindedTail> = None;
2469 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
2470 let mut short_channel_id = None;
2471 let mut payment_id = None;
2472 let mut failure_opt = None;
2473 let mut hold_times = None;
2474 read_tlv_fields!(reader, {
2475 (0, payment_hash, required),
2476 (1, network_update, upgradable_option),
2477 (2, payment_failed_permanently, required),
2478 (4, blinded_tail, option),
2479 // Added as a part of LDK 0.0.101 and always filled in since.
2480 // Defaults to an empty Vec, though likely should have been `Option`al.
2481 (5, path, optional_vec),
2482 (7, short_channel_id, option),
2483 (11, payment_id, option),
2484 (13, failure_opt, upgradable_option),
2485 (15, hold_times, optional_vec),
2486 });
2487 let hold_times = hold_times.unwrap_or(Vec::new());
2488 let failure =
2489 failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
2490 Ok(Some(Event::PaymentPathFailed {
2491 payment_id,
2492 payment_hash,
2493 payment_failed_permanently,
2494 failure,
2495 path: Path { hops: path.unwrap(), blinded_tail },
2496 short_channel_id,
2497 #[cfg(any(test, feature = "_test_utils"))]
2498 error_code,
2499 #[cfg(any(test, feature = "_test_utils"))]
2500 error_data,
2501 hold_times,
2502 }))
2503 };
2504 f()
2505 },
2506 4u8 => Ok(None),
2507 5u8 => {
2508 let mut f = || {
2509 let mut outputs = WithoutLength(Vec::new());
2510 let mut channel_id: Option<ChannelId> = None;
2511 read_tlv_fields!(reader, {
2512 (0, outputs, required),
2513 (1, channel_id, option),
2514 });
2515 Ok(Some(Event::SpendableOutputs { outputs: outputs.0, channel_id }))
2516 };
2517 f()
2518 },
2519 6u8 => {
2520 let mut payment_hash = PaymentHash([0; 32]);
2521 let mut intercept_id = InterceptId([0; 32]);
2522 let mut requested_next_hop_scid =
2523 InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
2524 let mut inbound_amount_msat = 0;
2525 let mut expected_outbound_amount_msat = 0;
2526 read_tlv_fields!(reader, {
2527 (0, intercept_id, required),
2528 (2, requested_next_hop_scid, required),
2529 (4, payment_hash, required),
2530 (6, inbound_amount_msat, required),
2531 (8, expected_outbound_amount_msat, required),
2532 });
2533 let next_scid = match requested_next_hop_scid {
2534 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid,
2535 };
2536 Ok(Some(Event::HTLCIntercepted {
2537 payment_hash,
2538 requested_next_hop_scid: next_scid,
2539 inbound_amount_msat,
2540 expected_outbound_amount_msat,
2541 intercept_id,
2542 }))
2543 },
2544 7u8 => {
2545 let mut f = || {
2546 let mut prev_channel_id = None;
2547 let mut next_channel_id = None;
2548 let mut prev_user_channel_id = None;
2549 let mut next_user_channel_id = None;
2550 let mut prev_node_id = None;
2551 let mut next_node_id = None;
2552 let mut total_fee_earned_msat = None;
2553 let mut skimmed_fee_msat = None;
2554 let mut claim_from_onchain_tx = false;
2555 let mut outbound_amount_forwarded_msat = None;
2556 read_tlv_fields!(reader, {
2557 (0, total_fee_earned_msat, option),
2558 (1, prev_channel_id, option),
2559 (2, claim_from_onchain_tx, required),
2560 (3, next_channel_id, option),
2561 (5, outbound_amount_forwarded_msat, option),
2562 (7, skimmed_fee_msat, option),
2563 (9, prev_user_channel_id, option),
2564 (11, next_user_channel_id, option),
2565 (13, prev_node_id, option),
2566 (15, next_node_id, option),
2567 });
2568 Ok(Some(Event::PaymentForwarded {
2569 prev_channel_id,
2570 next_channel_id,
2571 prev_user_channel_id,
2572 next_user_channel_id,
2573 prev_node_id,
2574 next_node_id,
2575 total_fee_earned_msat,
2576 skimmed_fee_msat,
2577 claim_from_onchain_tx,
2578 outbound_amount_forwarded_msat,
2579 }))
2580 };
2581 f()
2582 },
2583 9u8 => {
2584 let mut f = || {
2585 let mut channel_id = ChannelId::new_zero();
2586 let mut reason = UpgradableRequired(None);
2587 let mut user_channel_id_low_opt: Option<u64> = None;
2588 let mut user_channel_id_high_opt: Option<u64> = None;
2589 let mut counterparty_node_id = None;
2590 let mut channel_capacity_sats = None;
2591 let mut channel_funding_txo = None;
2592 let mut last_local_balance_msat = None;
2593 read_tlv_fields!(reader, {
2594 (0, channel_id, required),
2595 (1, user_channel_id_low_opt, option),
2596 (2, reason, upgradable_required),
2597 (3, user_channel_id_high_opt, option),
2598 (5, counterparty_node_id, option),
2599 (7, channel_capacity_sats, option),
2600 (9, channel_funding_txo, option),
2601 (11, last_local_balance_msat, option)
2602 });
2603
2604 // `user_channel_id` used to be a single u64 value. In order to remain
2605 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
2606 // as two separate u64 values.
2607 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128)
2608 + ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
2609
2610 Ok(Some(Event::ChannelClosed {
2611 channel_id,
2612 user_channel_id,
2613 reason: _init_tlv_based_struct_field!(reason, upgradable_required),
2614 counterparty_node_id,
2615 channel_capacity_sats,
2616 channel_funding_txo,
2617 last_local_balance_msat,
2618 }))
2619 };
2620 f()
2621 },
2622 11u8 => {
2623 let mut f = || {
2624 let mut channel_id = ChannelId::new_zero();
2625 let mut transaction: Option<Transaction> = None;
2626 let mut funding_info: Option<FundingInfo> = None;
2627 read_tlv_fields!(reader, {
2628 (0, channel_id, required),
2629 (2, transaction, option),
2630 (4, funding_info, option),
2631 });
2632
2633 let funding_info = if let Some(tx) = transaction {
2634 FundingInfo::Tx { transaction: tx }
2635 } else {
2636 funding_info.ok_or(msgs::DecodeError::InvalidValue)?
2637 };
2638 Ok(Some(Event::DiscardFunding { channel_id, funding_info }))
2639 };
2640 f()
2641 },
2642 13u8 => {
2643 let mut f = || {
2644 _init_and_read_len_prefixed_tlv_fields!(reader, {
2645 (0, payment_id, required),
2646 (1, hold_times, optional_vec),
2647 (2, payment_hash, option),
2648 (4, path, required_vec),
2649 (6, blinded_tail, option),
2650 });
2651
2652 let hold_times = hold_times.unwrap_or(Vec::new());
2653
2654 Ok(Some(Event::PaymentPathSuccessful {
2655 payment_id: payment_id.0.unwrap(),
2656 payment_hash,
2657 path: Path { hops: path, blinded_tail },
2658 hold_times,
2659 }))
2660 };
2661 f()
2662 },
2663 15u8 => {
2664 let mut f = || {
2665 let mut payment_hash = PaymentHash([0; 32]);
2666 let mut payment_id = PaymentId([0; 32]);
2667 let mut reason = None;
2668 let mut legacy_reason = None;
2669 let mut invoice_received: Option<bool> = None;
2670 read_tlv_fields!(reader, {
2671 (0, payment_id, required),
2672 (1, legacy_reason, upgradable_option),
2673 (2, payment_hash, required),
2674 (3, invoice_received, option),
2675 (5, reason, upgradable_option),
2676 });
2677 let payment_hash = match invoice_received {
2678 Some(invoice_received) => invoice_received.then(|| payment_hash),
2679 None => (payment_hash != PaymentHash([0; 32])).then(|| payment_hash),
2680 };
2681 let reason = reason.or(legacy_reason);
2682 Ok(Some(Event::PaymentFailed {
2683 payment_id,
2684 payment_hash,
2685 reason: _init_tlv_based_struct_field!(reason, upgradable_option),
2686 }))
2687 };
2688 f()
2689 },
2690 17u8 => {
2691 // Value 17 is used for `Event::OpenChannelRequest`.
2692 Ok(None)
2693 },
2694 19u8 => {
2695 let mut f = || {
2696 let mut payment_hash = PaymentHash([0; 32]);
2697 let mut purpose = UpgradableRequired(None);
2698 let mut amount_msat = 0;
2699 let mut receiver_node_id = None;
2700 let mut htlcs: Option<Vec<ClaimedHTLC>> = Some(vec![]);
2701 let mut sender_intended_total_msat: Option<u64> = None;
2702 let mut onion_fields = None;
2703 let mut payment_id = None;
2704 read_tlv_fields!(reader, {
2705 (0, payment_hash, required),
2706 (1, receiver_node_id, option),
2707 (2, purpose, upgradable_required),
2708 (4, amount_msat, required),
2709 (5, htlcs, optional_vec),
2710 (7, sender_intended_total_msat, option),
2711 (9, onion_fields, option),
2712 (11, payment_id, option),
2713 });
2714 Ok(Some(Event::PaymentClaimed {
2715 receiver_node_id,
2716 payment_hash,
2717 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
2718 amount_msat,
2719 htlcs: htlcs.unwrap_or_default(),
2720 sender_intended_total_msat,
2721 onion_fields,
2722 payment_id,
2723 }))
2724 };
2725 f()
2726 },
2727 21u8 => {
2728 let mut f = || {
2729 _init_and_read_len_prefixed_tlv_fields!(reader, {
2730 (0, payment_id, required),
2731 (2, payment_hash, required),
2732 (4, path, required_vec),
2733 (6, blinded_tail, option),
2734 });
2735 Ok(Some(Event::ProbeSuccessful {
2736 payment_id: payment_id.0.unwrap(),
2737 payment_hash: payment_hash.0.unwrap(),
2738 path: Path { hops: path, blinded_tail },
2739 }))
2740 };
2741 f()
2742 },
2743 23u8 => {
2744 let mut f = || {
2745 _init_and_read_len_prefixed_tlv_fields!(reader, {
2746 (0, payment_id, required),
2747 (2, payment_hash, required),
2748 (4, path, required_vec),
2749 (6, short_channel_id, option),
2750 (8, blinded_tail, option),
2751 });
2752 Ok(Some(Event::ProbeFailed {
2753 payment_id: payment_id.0.unwrap(),
2754 payment_hash: payment_hash.0.unwrap(),
2755 path: Path { hops: path, blinded_tail },
2756 short_channel_id,
2757 }))
2758 };
2759 f()
2760 },
2761 25u8 => {
2762 let mut f = || {
2763 let mut prev_channel_id = ChannelId::new_zero();
2764 let mut failure_reason = None;
2765 let mut failure_type_opt = UpgradableRequired(None);
2766 read_tlv_fields!(reader, {
2767 (0, prev_channel_id, required),
2768 (1, failure_reason, option),
2769 (2, failure_type_opt, upgradable_required),
2770 });
2771
2772 // If a legacy HTLCHandlingFailureType::UnknownNextHop was written, upgrade
2773 // it to its new representation, otherwise leave unchanged.
2774 if let Some(HTLCHandlingFailureType::UnknownNextHop {
2775 requested_forward_scid,
2776 }) = failure_type_opt.0
2777 {
2778 failure_type_opt.0 = Some(HTLCHandlingFailureType::InvalidForward {
2779 requested_forward_scid,
2780 });
2781 failure_reason = Some(LocalHTLCFailureReason::UnknownNextPeer.into());
2782 }
2783 Ok(Some(Event::HTLCHandlingFailed {
2784 prev_channel_id,
2785 failure_type: _init_tlv_based_struct_field!(
2786 failure_type_opt,
2787 upgradable_required
2788 ),
2789 failure_reason,
2790 }))
2791 };
2792 f()
2793 },
2794 27u8 => Ok(None),
2795 29u8 => {
2796 let mut f = || {
2797 let mut channel_id = ChannelId::new_zero();
2798 let mut user_channel_id: u128 = 0;
2799 let mut counterparty_node_id = RequiredWrapper(None);
2800 let mut funding_txo = None;
2801 let mut channel_type = RequiredWrapper(None);
2802 read_tlv_fields!(reader, {
2803 (0, channel_id, required),
2804 (1, funding_txo, option),
2805 (2, user_channel_id, required),
2806 (4, counterparty_node_id, required),
2807 (6, channel_type, required),
2808 });
2809
2810 Ok(Some(Event::ChannelReady {
2811 channel_id,
2812 user_channel_id,
2813 counterparty_node_id: counterparty_node_id.0.unwrap(),
2814 funding_txo,
2815 channel_type: channel_type.0.unwrap(),
2816 }))
2817 };
2818 f()
2819 },
2820 31u8 => {
2821 let mut f = || {
2822 let mut channel_id = ChannelId::new_zero();
2823 let mut user_channel_id: u128 = 0;
2824 let mut former_temporary_channel_id = None;
2825 let mut counterparty_node_id = RequiredWrapper(None);
2826 let mut funding_txo = RequiredWrapper(None);
2827 let mut channel_type = None;
2828 let mut funding_redeem_script = None;
2829 read_tlv_fields!(reader, {
2830 (0, channel_id, required),
2831 (1, channel_type, option),
2832 (2, user_channel_id, required),
2833 (4, former_temporary_channel_id, required),
2834 (6, counterparty_node_id, required),
2835 (8, funding_txo, required),
2836 (9, funding_redeem_script, option),
2837 });
2838
2839 Ok(Some(Event::ChannelPending {
2840 channel_id,
2841 user_channel_id,
2842 former_temporary_channel_id,
2843 counterparty_node_id: counterparty_node_id.0.unwrap(),
2844 funding_txo: funding_txo.0.unwrap(),
2845 channel_type,
2846 funding_redeem_script,
2847 }))
2848 };
2849 f()
2850 },
2851 // This was Event::InvoiceRequestFailed prior to version 0.0.124.
2852 33u8 => {
2853 let mut f = || {
2854 _init_and_read_len_prefixed_tlv_fields!(reader, {
2855 (0, payment_id, required),
2856 });
2857 Ok(Some(Event::PaymentFailed {
2858 payment_id: payment_id.0.unwrap(),
2859 payment_hash: None,
2860 reason: Some(PaymentFailureReason::InvoiceRequestExpired),
2861 }))
2862 };
2863 f()
2864 },
2865 // Note that we do not write a length-prefixed TLV for ConnectionNeeded events.
2866 35u8 => Ok(None),
2867 37u8 => {
2868 let mut f = || {
2869 _init_and_read_len_prefixed_tlv_fields!(reader, {
2870 (0, peer_node_id, required),
2871 (2, message, required),
2872 });
2873 Ok(Some(Event::OnionMessageIntercepted {
2874 peer_node_id: peer_node_id.0.unwrap(),
2875 message: message.0.unwrap(),
2876 }))
2877 };
2878 f()
2879 },
2880 39u8 => {
2881 let mut f = || {
2882 _init_and_read_len_prefixed_tlv_fields!(reader, {
2883 (0, peer_node_id, required),
2884 });
2885 Ok(Some(Event::OnionMessagePeerConnected {
2886 peer_node_id: peer_node_id.0.unwrap(),
2887 }))
2888 };
2889 f()
2890 },
2891 41u8 => {
2892 let mut f = || {
2893 _init_and_read_len_prefixed_tlv_fields!(reader, {
2894 (0, payment_id, required),
2895 (2, invoice, required),
2896 (4, context, option),
2897 (6, responder, option),
2898 });
2899 Ok(Some(Event::InvoiceReceived {
2900 payment_id: payment_id.0.unwrap(),
2901 invoice: invoice.0.unwrap(),
2902 context,
2903 responder,
2904 }))
2905 };
2906 f()
2907 },
2908 43u8 => {
2909 let mut channel_id = RequiredWrapper(None);
2910 let mut user_channel_id = RequiredWrapper(None);
2911 let mut funding_txo = RequiredWrapper(None);
2912 let mut counterparty_node_id = RequiredWrapper(None);
2913 let mut former_temporary_channel_id = RequiredWrapper(None);
2914 read_tlv_fields!(reader, {
2915 (0, channel_id, required),
2916 (2, user_channel_id, required),
2917 (4, funding_txo, required),
2918 (6, counterparty_node_id, required),
2919 (8, former_temporary_channel_id, required)
2920 });
2921 Ok(Some(Event::FundingTxBroadcastSafe {
2922 channel_id: channel_id.0.unwrap(),
2923 user_channel_id: user_channel_id.0.unwrap(),
2924 funding_txo: funding_txo.0.unwrap(),
2925 counterparty_node_id: counterparty_node_id.0.unwrap(),
2926 former_temporary_channel_id: former_temporary_channel_id.0.unwrap(),
2927 }))
2928 },
2929 // Note that we do not write a length-prefixed TLV for PersistStaticInvoice events.
2930 45u8 => Ok(None),
2931 // Note that we do not write a length-prefixed TLV for StaticInvoiceRequested events.
2932 47u8 => Ok(None),
2933 // Note that we do not write a length-prefixed TLV for FundingTransactionReadyForSigning events.
2934 49u8 => Ok(None),
2935 50u8 => {
2936 let mut f = || {
2937 _init_and_read_len_prefixed_tlv_fields!(reader, {
2938 (1, channel_id, required),
2939 (3, channel_type, required),
2940 (5, user_channel_id, required),
2941 (7, counterparty_node_id, required),
2942 (9, new_funding_txo, required),
2943 (11, new_funding_redeem_script, required),
2944 });
2945
2946 Ok(Some(Event::SplicePending {
2947 channel_id: channel_id.0.unwrap(),
2948 user_channel_id: user_channel_id.0.unwrap(),
2949 counterparty_node_id: counterparty_node_id.0.unwrap(),
2950 new_funding_txo: new_funding_txo.0.unwrap(),
2951 channel_type: channel_type.0.unwrap(),
2952 new_funding_redeem_script: new_funding_redeem_script.0.unwrap(),
2953 }))
2954 };
2955 f()
2956 },
2957 52u8 => {
2958 let mut f = || {
2959 _init_and_read_len_prefixed_tlv_fields!(reader, {
2960 (1, channel_id, required),
2961 (3, channel_type, option),
2962 (5, user_channel_id, required),
2963 (7, counterparty_node_id, required),
2964 (9, abandoned_funding_txo, option),
2965 (11, contributed_inputs, optional_vec),
2966 (13, contributed_outputs, optional_vec),
2967 });
2968
2969 Ok(Some(Event::SpliceFailed {
2970 channel_id: channel_id.0.unwrap(),
2971 user_channel_id: user_channel_id.0.unwrap(),
2972 counterparty_node_id: counterparty_node_id.0.unwrap(),
2973 abandoned_funding_txo,
2974 channel_type,
2975 contributed_inputs: contributed_inputs.unwrap_or_default(),
2976 contributed_outputs: contributed_outputs.unwrap_or_default(),
2977 }))
2978 };
2979 f()
2980 },
2981 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
2982 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
2983 // reads.
2984 x if x % 2 == 1 => {
2985 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
2986 // which prefixes the whole thing with a length BigSize. Because the event is
2987 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
2988 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
2989 // exactly the number of bytes specified, ignoring them entirely.
2990 let tlv_len: BigSize = Readable::read(reader)?;
2991 FixedLengthReader::new(reader, tlv_len.0)
2992 .eat_remaining()
2993 .map_err(|_| msgs::DecodeError::ShortRead)?;
2994 Ok(None)
2995 },
2996 _ => Err(msgs::DecodeError::InvalidValue),
2997 }
2998 }
2999}
3000
3001/// A trait indicating an object may generate events.
3002///
3003/// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
3004///
3005/// Implementations of this trait may also feature an async version of event handling, as shown with
3006/// [`ChannelManager::process_pending_events_async`] and
3007/// [`ChainMonitor::process_pending_events_async`].
3008///
3009/// # Requirements
3010///
3011/// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
3012/// event since the last invocation.
3013///
3014/// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
3015/// and replay any unhandled events on startup. An [`Event`] is considered handled when
3016/// [`process_pending_events`] returns `Ok(())`, thus handlers MUST fully handle [`Event`]s and
3017/// persist any relevant changes to disk *before* returning `Ok(())`. In case of an error (e.g.,
3018/// persistence failure) implementors should return `Err(ReplayEvent())`, signalling to the
3019/// [`EventsProvider`] to replay unhandled events on the next invocation (generally immediately).
3020/// Note that some events might not be replayed, please refer to the documentation for
3021/// the individual [`Event`] variants for more detail.
3022///
3023/// Further, because an application may crash between an [`Event`] being handled and the
3024/// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
3025/// effect, [`Event`]s may be replayed.
3026///
3027/// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
3028/// consult the provider's documentation on the implication of processing events and how a handler
3029/// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
3030/// [`ChainMonitor::process_pending_events`]).
3031///
3032/// (C-not implementable) As there is likely no reason for a user to implement this trait on their
3033/// own type(s).
3034///
3035/// [`process_pending_events`]: Self::process_pending_events
3036/// [`handle_event`]: EventHandler::handle_event
3037/// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
3038/// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
3039/// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
3040/// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
3041pub trait EventsProvider {
3042 /// Processes any events generated since the last call using the given event handler.
3043 ///
3044 /// See the trait-level documentation for requirements.
3045 fn process_pending_events<H: Deref>(&self, handler: H)
3046 where
3047 H::Target: EventHandler;
3048}
3049
3050/// An error type that may be returned to LDK in order to safely abort event handling if it can't
3051/// currently succeed (e.g., due to a persistence failure).
3052///
3053/// Depending on the type, LDK may ensure the event is persisted and will eventually be replayed.
3054/// Please refer to the documentation of each [`Event`] variant for more details.
3055#[derive(Clone, Copy, Debug)]
3056pub struct ReplayEvent();
3057
3058/// A trait implemented for objects handling events from [`EventsProvider`].
3059///
3060/// An async variation also exists for implementations of [`EventsProvider`] that support async
3061/// event handling. The async event handler should satisfy the generic bounds: `F:
3062/// core::future::Future<Output = Result<(), ReplayEvent>>, H: Fn(Event) -> F`.
3063pub trait EventHandler {
3064 /// Handles the given [`Event`].
3065 ///
3066 /// See [`EventsProvider`] for details that must be considered when implementing this method.
3067 fn handle_event(&self, event: Event) -> Result<(), ReplayEvent>;
3068}
3069
3070impl<F> EventHandler for F
3071where
3072 F: Fn(Event) -> Result<(), ReplayEvent>,
3073{
3074 fn handle_event(&self, event: Event) -> Result<(), ReplayEvent> {
3075 self(event)
3076 }
3077}
3078
3079impl<T: EventHandler> EventHandler for Arc<T> {
3080 fn handle_event(&self, event: Event) -> Result<(), ReplayEvent> {
3081 self.deref().handle_event(event)
3082 }
3083}
3084
3085/// The BOLT 12 invoice that was paid, surfaced in [`Event::PaymentSent::bolt12_invoice`].
3086#[derive(Clone, Debug, PartialEq, Eq, Hash)]
3087pub enum PaidBolt12Invoice {
3088 /// The BOLT 12 invoice specified by the BOLT 12 specification,
3089 /// allowing the user to perform proof of payment.
3090 Bolt12Invoice(Bolt12Invoice),
3091 /// The Static invoice, used in the async payment specification update proposal,
3092 /// where the user cannot perform proof of payment.
3093 StaticInvoice(StaticInvoice),
3094}
3095
3096impl_writeable_tlv_based_enum!(PaidBolt12Invoice,
3097 {0, Bolt12Invoice} => (),
3098 {2, StaticInvoice} => (),
3099);