1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Events are returned from various bits in the library which indicate some action must be taken
13 //! Because we don't have a built-in runtime, it's up to the client to call events at a time in the
14 //! future, as well as generate and broadcast funding transactions handle payment preimages and a
17 use crate::chain::keysinterface::SpendableOutputDescriptor;
19 use crate::ln::chan_utils::{self, ChannelTransactionParameters, HTLCOutputInCommitment};
20 use crate::ln::channelmanager::{InterceptId, PaymentId};
21 use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
22 use crate::ln::features::ChannelTypeFeatures;
24 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
25 use crate::routing::gossip::NetworkUpdate;
26 use crate::util::errors::APIError;
27 use crate::util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, RequiredWrapper, UpgradableRequired, WithoutLength};
28 use crate::routing::router::{RouteHop, RouteParameters};
30 use bitcoin::{PackedLockTime, Transaction};
32 use bitcoin::{OutPoint, Txid, TxIn, TxOut, Witness};
33 use bitcoin::blockdata::script::Script;
34 use bitcoin::hashes::Hash;
35 use bitcoin::hashes::sha256::Hash as Sha256;
36 use bitcoin::secp256k1::PublicKey;
38 use bitcoin::secp256k1::{self, Secp256k1};
40 use bitcoin::secp256k1::ecdsa::Signature;
42 use crate::prelude::*;
43 use core::time::Duration;
47 /// Some information provided on receipt of payment depends on whether the payment received is a
48 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
49 #[derive(Clone, Debug, PartialEq, Eq)]
50 pub enum PaymentPurpose {
51 /// Information for receiving a payment that we generated an invoice for.
53 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
54 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
55 /// [`ChannelManager::claim_funds`].
57 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
58 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
59 payment_preimage: Option<PaymentPreimage>,
60 /// The "payment secret". This authenticates the sender to the recipient, preventing a
61 /// number of deanonymization attacks during the routing process.
62 /// It is provided here for your reference, however its accuracy is enforced directly by
63 /// [`ChannelManager`] using the values you previously provided to
64 /// [`ChannelManager::create_inbound_payment`] or
65 /// [`ChannelManager::create_inbound_payment_for_hash`].
67 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
68 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
69 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
70 payment_secret: PaymentSecret,
72 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
73 /// (the payee) providing a preimage.
74 SpontaneousPayment(PaymentPreimage),
77 impl_writeable_tlv_based_enum!(PaymentPurpose,
78 (0, InvoicePayment) => {
79 (0, payment_preimage, option),
80 (2, payment_secret, required),
82 (2, SpontaneousPayment)
85 /// When the payment path failure took place and extra details about it. [`PathFailure::OnPath`] may
86 /// contain a [`NetworkUpdate`] that needs to be applied to the [`NetworkGraph`].
88 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
89 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
90 #[derive(Clone, Debug, Eq, PartialEq)]
91 pub enum PathFailure {
92 /// We failed to initially send the payment and no HTLC was committed to. Contains the relevant
95 /// The error surfaced from initial send.
98 /// A hop on the path failed to forward our payment.
100 /// If present, this [`NetworkUpdate`] should be applied to the [`NetworkGraph`] so that routing
101 /// decisions can take into account the update.
103 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
104 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
105 network_update: Option<NetworkUpdate>,
109 impl_writeable_tlv_based_enum_upgradable!(PathFailure,
111 (0, network_update, upgradable_option),
113 (2, InitialSend) => {
114 (0, err, upgradable_required),
118 #[derive(Clone, Debug, PartialEq, Eq)]
119 /// The reason the channel was closed. See individual variants more details.
120 pub enum ClosureReason {
121 /// Closure generated from receiving a peer error message.
123 /// Our counterparty may have broadcasted their latest commitment state, and we have
125 CounterpartyForceClosed {
126 /// The error which the peer sent us.
128 /// The string should be sanitized before it is used (e.g emitted to logs
129 /// or printed to stdout). Otherwise, a well crafted error message may exploit
130 /// a security vulnerability in the terminal emulator or the logging subsystem.
133 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
135 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
137 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
138 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
139 //TODO: split between CounterpartyInitiated/LocallyInitiated
141 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
142 /// commitment transaction came from our counterparty, but it may also have come from
143 /// a copy of our own `ChannelMonitor`.
144 CommitmentTxConfirmed,
145 /// The funding transaction failed to confirm in a timely manner on an inbound channel.
147 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
149 /// A developer-readable error message which we generated.
152 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
153 /// forget the channel entirely - we can attempt again if the peer reconnects.
155 /// This includes cases where we restarted prior to funding completion, including prior to the
156 /// initial [`ChannelMonitor`] persistence completing.
158 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
159 /// peer because of mutual incompatibility between us and our channel counterparty.
161 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
163 /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
164 /// the [`ChannelManager`] deserialized.
166 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
167 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
168 OutdatedChannelManager
171 impl core::fmt::Display for ClosureReason {
172 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
173 f.write_str("Channel closed because ")?;
175 ClosureReason::CounterpartyForceClosed { peer_msg } => {
176 f.write_str("counterparty force-closed with message ")?;
177 f.write_str(&peer_msg)
179 ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
180 ClosureReason::CooperativeClosure => f.write_str("the channel was cooperatively closed"),
181 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
182 ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
183 ClosureReason::ProcessingError { err } => {
184 f.write_str("of an exception: ")?;
187 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
188 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
193 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
194 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
195 (1, FundingTimedOut) => {},
196 (2, HolderForceClosed) => {},
197 (6, CommitmentTxConfirmed) => {},
198 (4, CooperativeClosure) => {},
199 (8, ProcessingError) => { (1, err, required) },
200 (10, DisconnectedPeer) => {},
201 (12, OutdatedChannelManager) => {},
204 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
205 #[derive(Clone, Debug, PartialEq, Eq)]
206 pub enum HTLCDestination {
207 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
208 /// there is insufficient capacity in our outbound channel.
210 /// The `node_id` of the next node. For backwards compatibility, this field is
211 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
212 /// counterparty node information.
213 node_id: Option<PublicKey>,
214 /// The outgoing `channel_id` between us and the next node.
215 channel_id: [u8; 32],
217 /// Scenario where we are unsure of the next node to forward the HTLC to.
219 /// Short channel id we are requesting to forward an HTLC to.
220 requested_forward_scid: u64,
222 /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
225 /// Short channel id we are requesting to forward an HTLC to.
226 requested_forward_scid: u64
228 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
229 /// but is invalid for some reason, so we reject it.
231 /// Some of the reasons may include:
233 /// * Expected MPP amount to claim does not equal HTLC total
234 /// * Claimable amount does not match expected amount
236 /// The payment hash of the payment we attempted to process.
237 payment_hash: PaymentHash
241 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
242 (0, NextHopChannel) => {
243 (0, node_id, required),
244 (2, channel_id, required),
246 (1, InvalidForward) => {
247 (0, requested_forward_scid, required),
249 (2, UnknownNextHop) => {
250 (0, requested_forward_scid, required),
252 (4, FailedPayment) => {
253 (0, payment_hash, required),
258 /// A descriptor used to sign for a commitment transaction's anchor output.
259 #[derive(Clone, Debug)]
260 pub struct AnchorDescriptor {
261 /// A unique identifier used along with `channel_value_satoshis` to re-derive the
262 /// [`InMemorySigner`] required to sign `input`.
264 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
265 pub channel_keys_id: [u8; 32],
266 /// The value in satoshis of the channel we're attempting to spend the anchor output of. This is
267 /// used along with `channel_keys_id` to re-derive the [`InMemorySigner`] required to sign
270 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
271 pub channel_value_satoshis: u64,
272 /// The transaction input's outpoint corresponding to the commitment transaction's anchor
274 pub outpoint: OutPoint,
278 /// A descriptor used to sign for a commitment transaction's HTLC output.
279 #[derive(Clone, Debug)]
280 pub struct HTLCDescriptor {
281 /// A unique identifier used along with `channel_value_satoshis` to re-derive the
282 /// [`InMemorySigner`] required to sign `input`.
284 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
285 pub channel_keys_id: [u8; 32],
286 /// The value in satoshis of the channel we're attempting to spend the anchor output of. This is
287 /// used along with `channel_keys_id` to re-derive the [`InMemorySigner`] required to sign
290 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
291 pub channel_value_satoshis: u64,
292 /// The necessary channel parameters that need to be provided to the re-derived
293 /// [`InMemorySigner`] through [`BaseSign::provide_channel_parameters`].
295 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
296 /// [`BaseSign::provide_channel_parameters`]: crate::chain::keysinterface::BaseSign::provide_channel_parameters
297 pub channel_parameters: ChannelTransactionParameters,
298 /// The txid of the commitment transaction in which the HTLC output lives.
299 pub commitment_txid: Txid,
300 /// The number of the commitment transaction in which the HTLC output lives.
301 pub per_commitment_number: u64,
302 /// The details of the HTLC as it appears in the commitment transaction.
303 pub htlc: HTLCOutputInCommitment,
304 /// The preimage, if `Some`, to claim the HTLC output with. If `None`, the timeout path must be
306 pub preimage: Option<PaymentPreimage>,
307 /// The counterparty's signature required to spend the HTLC output.
308 pub counterparty_sig: Signature
312 impl HTLCDescriptor {
313 /// Returns the unsigned transaction input spending the HTLC output in the commitment
315 pub fn unsigned_tx_input(&self) -> TxIn {
316 chan_utils::build_htlc_input(&self.commitment_txid, &self.htlc, true /* opt_anchors */)
319 /// Returns the delayed output created as a result of spending the HTLC output in the commitment
321 pub fn tx_output<C: secp256k1::Signing + secp256k1::Verification>(
322 &self, per_commitment_point: &PublicKey, secp: &Secp256k1<C>
324 let channel_params = self.channel_parameters.as_holder_broadcastable();
325 let broadcaster_keys = channel_params.broadcaster_pubkeys();
326 let counterparty_keys = channel_params.countersignatory_pubkeys();
327 let broadcaster_delayed_key = chan_utils::derive_public_key(
328 secp, per_commitment_point, &broadcaster_keys.delayed_payment_basepoint
330 let counterparty_revocation_key = chan_utils::derive_public_revocation_key(
331 secp, per_commitment_point, &counterparty_keys.revocation_basepoint
333 chan_utils::build_htlc_output(
334 0 /* feerate_per_kw */, channel_params.contest_delay(), &self.htlc, true /* opt_anchors */,
335 false /* use_non_zero_fee_anchors */, &broadcaster_delayed_key, &counterparty_revocation_key
339 /// Returns the witness script of the HTLC output in the commitment transaction.
340 pub fn witness_script<C: secp256k1::Signing + secp256k1::Verification>(
341 &self, per_commitment_point: &PublicKey, secp: &Secp256k1<C>
343 let channel_params = self.channel_parameters.as_holder_broadcastable();
344 let broadcaster_keys = channel_params.broadcaster_pubkeys();
345 let counterparty_keys = channel_params.countersignatory_pubkeys();
346 let broadcaster_htlc_key = chan_utils::derive_public_key(
347 secp, per_commitment_point, &broadcaster_keys.htlc_basepoint
349 let counterparty_htlc_key = chan_utils::derive_public_key(
350 secp, per_commitment_point, &counterparty_keys.htlc_basepoint
352 let counterparty_revocation_key = chan_utils::derive_public_revocation_key(
353 secp, per_commitment_point, &counterparty_keys.revocation_basepoint
355 chan_utils::get_htlc_redeemscript_with_explicit_keys(
356 &self.htlc, true /* opt_anchors */, &broadcaster_htlc_key, &counterparty_htlc_key,
357 &counterparty_revocation_key,
361 /// Returns the fully signed witness required to spend the HTLC output in the commitment
363 pub fn tx_input_witness(&self, signature: &Signature, witness_script: &Script) -> Witness {
364 chan_utils::build_htlc_input_witness(
365 signature, &self.counterparty_sig, &self.preimage, witness_script, true /* opt_anchors */
371 /// Represents the different types of transactions, originating from LDK, to be bumped.
372 #[derive(Clone, Debug)]
373 pub enum BumpTransactionEvent {
374 /// Indicates that a channel featuring anchor outputs is to be closed by broadcasting the local
375 /// commitment transaction. Since commitment transactions have a static feerate pre-agreed upon,
376 /// they may need additional fees to be attached through a child transaction using the popular
377 /// [Child-Pays-For-Parent](https://bitcoinops.org/en/topics/cpfp) fee bumping technique. This
378 /// child transaction must include the anchor input described within `anchor_descriptor` along
379 /// with additional inputs to meet the target feerate. Failure to meet the target feerate
380 /// decreases the confirmation odds of the transaction package (which includes the commitment
381 /// and child anchor transactions), possibly resulting in a loss of funds. Once the transaction
382 /// is constructed, it must be fully signed for and broadcast by the consumer of the event
383 /// along with the `commitment_tx` enclosed. Note that the `commitment_tx` must always be
384 /// broadcast first, as the child anchor transaction depends on it.
386 /// The consumer should be able to sign for any of the additional inputs included within the
387 /// child anchor transaction. To sign its anchor input, an [`InMemorySigner`] should be
388 /// re-derived through [`KeysManager::derive_channel_keys`] with the help of
389 /// [`AnchorDescriptor::channel_keys_id`] and [`AnchorDescriptor::channel_value_satoshis`]. The
390 /// anchor input signature can be computed with [`BaseSign::sign_holder_anchor_input`],
391 /// which can then be provided to [`build_anchor_input_witness`] along with the `funding_pubkey`
392 /// to obtain the full witness required to spend.
394 /// It is possible to receive more than one instance of this event if a valid child anchor
395 /// transaction is never broadcast or is but not with a sufficient fee to be mined. Care should
396 /// be taken by the consumer of the event to ensure any future iterations of the child anchor
397 /// transaction adhere to the [Replace-By-Fee
398 /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
399 /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
400 /// these events is not user-controlled, users may ignore/drop the event if they are no longer
401 /// able to commit external confirmed funds to the child anchor transaction.
403 /// The set of `pending_htlcs` on the commitment transaction to be broadcast can be inspected to
404 /// determine whether a significant portion of the channel's funds are allocated to HTLCs,
405 /// enabling users to make their own decisions regarding the importance of the commitment
406 /// transaction's confirmation. Note that this is not required, but simply exists as an option
407 /// for users to override LDK's behavior. On commitments with no HTLCs (indicated by those with
408 /// an empty `pending_htlcs`), confirmation of the commitment transaction can be considered to
411 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
412 /// [`KeysManager::derive_channel_keys`]: crate::chain::keysinterface::KeysManager::derive_channel_keys
413 /// [`BaseSign::sign_holder_anchor_input`]: crate::chain::keysinterface::BaseSign::sign_holder_anchor_input
414 /// [`build_anchor_input_witness`]: crate::ln::chan_utils::build_anchor_input_witness
416 /// The target feerate that the transaction package, which consists of the commitment
417 /// transaction and the to-be-crafted child anchor transaction, must meet.
418 package_target_feerate_sat_per_1000_weight: u32,
419 /// The channel's commitment transaction to bump the fee of. This transaction should be
420 /// broadcast along with the anchor transaction constructed as a result of consuming this
422 commitment_tx: Transaction,
423 /// The absolute fee in satoshis of the commitment transaction. This can be used along the
424 /// with weight of the commitment transaction to determine its feerate.
425 commitment_tx_fee_satoshis: u64,
426 /// The descriptor to sign the anchor input of the anchor transaction constructed as a
427 /// result of consuming this event.
428 anchor_descriptor: AnchorDescriptor,
429 /// The set of pending HTLCs on the commitment transaction that need to be resolved once the
430 /// commitment transaction confirms.
431 pending_htlcs: Vec<HTLCOutputInCommitment>,
433 /// Indicates that a channel featuring anchor outputs has unilaterally closed on-chain by a
434 /// holder commitment transaction and its HTLC(s) need to be resolved on-chain. With the
435 /// zero-HTLC-transaction-fee variant of anchor outputs, the pre-signed HTLC
436 /// transactions have a zero fee, thus requiring additional inputs and/or outputs to be attached
437 /// for a timely confirmation within the chain. These additional inputs and/or outputs must be
438 /// appended to the resulting HTLC transaction to meet the target feerate. Failure to meet the
439 /// target feerate decreases the confirmation odds of the transaction, possibly resulting in a
440 /// loss of funds. Once the transaction meets the target feerate, it must be signed for and
441 /// broadcast by the consumer of the event.
443 /// The consumer should be able to sign for any of the non-HTLC inputs added to the resulting
444 /// HTLC transaction. To sign HTLC inputs, an [`InMemorySigner`] should be re-derived through
445 /// [`KeysManager::derive_channel_keys`] with the help of `channel_keys_id` and
446 /// `channel_value_satoshis`. Each HTLC input's signature can be computed with
447 /// [`BaseSign::sign_holder_htlc_transaction`], which can then be provided to
448 /// [`HTLCDescriptor::tx_input_witness`] to obtain the fully signed witness required to spend.
450 /// It is possible to receive more than one instance of this event if a valid HTLC transaction
451 /// is never broadcast or is but not with a sufficient fee to be mined. Care should be taken by
452 /// the consumer of the event to ensure any future iterations of the HTLC transaction adhere to
453 /// the [Replace-By-Fee
454 /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
455 /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
456 /// these events is not user-controlled, users may ignore/drop the event if either they are no
457 /// longer able to commit external confirmed funds to the HTLC transaction or the fee committed
458 /// to the HTLC transaction is greater in value than the HTLCs being claimed.
460 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
461 /// [`KeysManager::derive_channel_keys`]: crate::chain::keysinterface::KeysManager::derive_channel_keys
462 /// [`BaseSign::sign_holder_htlc_transaction`]: crate::chain::keysinterface::BaseSign::sign_holder_htlc_transaction
463 /// [`HTLCDescriptor::tx_input_witness`]: HTLCDescriptor::tx_input_witness
465 target_feerate_sat_per_1000_weight: u32,
466 htlc_descriptors: Vec<HTLCDescriptor>,
470 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
471 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
472 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
473 /// intercepts in upcoming work.
474 enum InterceptNextHop {
476 requested_next_hop_scid: u64,
480 impl_writeable_tlv_based_enum!(InterceptNextHop,
482 (0, requested_next_hop_scid, required),
486 /// An Event which you should probably take some action in response to.
488 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
489 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
490 /// written as it makes no sense to respond to it after reconnecting to peers).
491 #[derive(Clone, Debug, PartialEq, Eq)]
493 /// Used to indicate that the client should generate a funding transaction with the given
494 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
495 /// Generated in [`ChannelManager`] message handling.
496 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
497 /// counterparty can steal your funds!
499 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
500 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
501 FundingGenerationReady {
502 /// The random channel_id we picked which you'll need to pass into
503 /// [`ChannelManager::funding_transaction_generated`].
505 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
506 temporary_channel_id: [u8; 32],
507 /// The counterparty's node_id, which you'll need to pass back into
508 /// [`ChannelManager::funding_transaction_generated`].
510 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
511 counterparty_node_id: PublicKey,
512 /// The value, in satoshis, that the output should have.
513 channel_value_satoshis: u64,
514 /// The script which should be used in the transaction output.
515 output_script: Script,
516 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or a
517 /// random value for an inbound channel. This may be zero for objects serialized with LDK
518 /// versions prior to 0.0.113.
520 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
521 user_channel_id: u128,
523 /// Indicates that we've been offered a payment and it needs to be claimed via calling
524 /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
526 /// Note that if the preimage is not known, you should call
527 /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
528 /// to free up resources for this HTLC and avoid network congestion.
529 /// If you fail to call either [`ChannelManager::claim_funds`], [`ChannelManager::fail_htlc_backwards`],
530 /// or [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will be
531 /// automatically failed.
534 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
535 /// `PaymentClaimable` events may be generated for the same payment.
538 /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
540 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
541 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
542 /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
544 /// The node that will receive the payment after it has been claimed.
545 /// This is useful to identify payments received via [phantom nodes].
546 /// This field will always be filled in when the event was generated by LDK versions
547 /// 0.0.113 and above.
549 /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
550 receiver_node_id: Option<PublicKey>,
551 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
552 /// not stop you from registering duplicate payment hashes for inbound payments.
553 payment_hash: PaymentHash,
554 /// The value, in thousandths of a satoshi, that this payment is for.
556 /// Information for claiming this received payment, based on whether the purpose of the
557 /// payment is to pay an invoice or to send a spontaneous payment.
558 purpose: PaymentPurpose,
559 /// The `channel_id` indicating over which channel we received the payment.
560 via_channel_id: Option<[u8; 32]>,
561 /// The `user_channel_id` indicating over which channel we received the payment.
562 via_user_channel_id: Option<u128>,
564 /// Indicates a payment has been claimed and we've received money!
566 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
567 /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
568 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
569 /// [`Event::PaymentClaimable`] event.
572 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
573 /// `PaymentClaimable` events may be generated for the same payment. If you then call
574 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
575 /// multiple `PaymentClaimed` events.
577 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
579 /// The node that received the payment.
580 /// This is useful to identify payments which were received via [phantom nodes].
581 /// This field will always be filled in when the event was generated by LDK versions
582 /// 0.0.113 and above.
584 /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
585 receiver_node_id: Option<PublicKey>,
586 /// The payment hash of the claimed payment. Note that LDK will not stop you from
587 /// registering duplicate payment hashes for inbound payments.
588 payment_hash: PaymentHash,
589 /// The value, in thousandths of a satoshi, that this payment is for.
591 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
592 /// spontaneous payment.
593 purpose: PaymentPurpose,
595 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
596 /// and we got back the payment preimage for it).
598 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
599 /// event. In this situation, you SHOULD treat this payment as having succeeded.
601 /// The id returned by [`ChannelManager::send_payment`].
603 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
604 payment_id: Option<PaymentId>,
605 /// The preimage to the hash given to ChannelManager::send_payment.
606 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
607 /// store it somehow!
608 payment_preimage: PaymentPreimage,
609 /// The hash that was given to [`ChannelManager::send_payment`].
611 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
612 payment_hash: PaymentHash,
613 /// The total fee which was spent at intermediate hops in this payment, across all paths.
615 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
616 /// overpayment to the recipient node.
618 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
619 /// overstate the amount paid, though this is unlikely.
621 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
622 fee_paid_msat: Option<u64>,
624 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
625 /// provide failure information for each path attempt in the payment, including retries.
627 /// This event is provided once there are no further pending HTLCs for the payment and the
628 /// payment is no longer retryable, due either to the [`Retry`] provided or
629 /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
631 /// [`Retry`]: crate::ln::channelmanager::Retry
632 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
634 /// The id returned by [`ChannelManager::send_payment`] and used with
635 /// [`ChannelManager::abandon_payment`].
637 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
638 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
639 payment_id: PaymentId,
640 /// The hash that was given to [`ChannelManager::send_payment`].
642 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
643 payment_hash: PaymentHash,
645 /// Indicates that a path for an outbound payment was successful.
647 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
648 /// [`Event::PaymentSent`] for obtaining the payment preimage.
649 PaymentPathSuccessful {
650 /// The id returned by [`ChannelManager::send_payment`].
652 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
653 payment_id: PaymentId,
654 /// The hash that was given to [`ChannelManager::send_payment`].
656 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
657 payment_hash: Option<PaymentHash>,
658 /// The payment path that was successful.
660 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
663 /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
666 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
667 /// [`Event::PaymentFailed`].
669 /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
672 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
674 /// The id returned by [`ChannelManager::send_payment`] and used with
675 /// [`ChannelManager::abandon_payment`].
677 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
678 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
679 payment_id: Option<PaymentId>,
680 /// The hash that was given to [`ChannelManager::send_payment`].
682 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
683 payment_hash: PaymentHash,
684 /// Indicates the payment was rejected for some reason by the recipient. This implies that
685 /// the payment has failed, not just the route in question. If this is not set, the payment may
686 /// be retried via a different route.
687 payment_failed_permanently: bool,
688 /// Extra error details based on the failure type. May contain an update that needs to be
689 /// applied to the [`NetworkGraph`].
691 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
692 failure: PathFailure,
693 /// The payment path that failed.
695 /// The channel responsible for the failed payment path.
697 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
698 /// may not refer to a channel in the public network graph. These aliases may also collide
699 /// with channels in the public network graph.
701 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
702 /// retried. May be `None` for older [`Event`] serializations.
703 short_channel_id: Option<u64>,
704 /// Parameters used by LDK to compute a new [`Route`] when retrying the failed payment path.
706 /// [`Route`]: crate::routing::router::Route
707 retry: Option<RouteParameters>,
709 error_code: Option<u16>,
711 error_data: Option<Vec<u8>>,
713 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
715 /// The id returned by [`ChannelManager::send_probe`].
717 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
718 payment_id: PaymentId,
719 /// The hash generated by [`ChannelManager::send_probe`].
721 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
722 payment_hash: PaymentHash,
723 /// The payment path that was successful.
726 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
728 /// The id returned by [`ChannelManager::send_probe`].
730 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
731 payment_id: PaymentId,
732 /// The hash generated by [`ChannelManager::send_probe`].
734 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
735 payment_hash: PaymentHash,
736 /// The payment path that failed.
738 /// The channel responsible for the failed probe.
740 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
741 /// may not refer to a channel in the public network graph. These aliases may also collide
742 /// with channels in the public network graph.
743 short_channel_id: Option<u64>,
745 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
746 /// a time in the future.
748 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
749 PendingHTLCsForwardable {
750 /// The minimum amount of time that should be waited prior to calling
751 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
752 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
753 /// now + 5*time_forwardable).
754 time_forwardable: Duration,
756 /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
757 /// you've encoded an intercept scid in the receiver's invoice route hints using
758 /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
760 /// [`ChannelManager::forward_intercepted_htlc`] or
761 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
762 /// their docs for more information.
764 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
765 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
766 /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
767 /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
769 /// An id to help LDK identify which HTLC is being forwarded or failed.
770 intercept_id: InterceptId,
771 /// The fake scid that was programmed as the next hop's scid, generated using
772 /// [`ChannelManager::get_intercept_scid`].
774 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
775 requested_next_hop_scid: u64,
776 /// The payment hash used for this HTLC.
777 payment_hash: PaymentHash,
778 /// How many msats were received on the inbound edge of this HTLC.
779 inbound_amount_msat: u64,
780 /// How many msats the payer intended to route to the next node. Depending on the reason you are
781 /// intercepting this payment, you might take a fee by forwarding less than this amount.
783 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
784 /// check that whatever fee you want has been included here or subtract it as required. Further,
785 /// LDK will not stop you from forwarding more than you received.
786 expected_outbound_amount_msat: u64,
788 /// Used to indicate that an output which you should know how to spend was confirmed on chain
789 /// and is now spendable.
790 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
791 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
792 /// somewhere and spend them when you create on-chain transactions.
794 /// The outputs which you should store as spendable by you.
795 outputs: Vec<SpendableOutputDescriptor>,
797 /// This event is generated when a payment has been successfully forwarded through us and a
798 /// forwarding fee earned.
800 /// The incoming channel between the previous node and us. This is only `None` for events
801 /// generated or serialized by versions prior to 0.0.107.
802 prev_channel_id: Option<[u8; 32]>,
803 /// The outgoing channel between the next node and us. This is only `None` for events
804 /// generated or serialized by versions prior to 0.0.107.
805 next_channel_id: Option<[u8; 32]>,
806 /// The fee, in milli-satoshis, which was earned as a result of the payment.
808 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
809 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
810 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
811 /// claimed the full value in millisatoshis from the source. In this case,
812 /// `claim_from_onchain_tx` will be set.
814 /// If the channel which sent us the payment has been force-closed, we will claim the funds
815 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
816 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
817 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
819 fee_earned_msat: Option<u64>,
820 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
822 claim_from_onchain_tx: bool,
824 /// Used to indicate that a channel with the given `channel_id` is ready to
825 /// be used. This event is emitted either when the funding transaction has been confirmed
826 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
829 /// The channel_id of the channel that is ready.
830 channel_id: [u8; 32],
831 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
832 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
833 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
834 /// `user_channel_id` will be randomized for an inbound channel.
836 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
837 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
838 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
839 user_channel_id: u128,
840 /// The node_id of the channel counterparty.
841 counterparty_node_id: PublicKey,
842 /// The features that this channel will operate with.
843 channel_type: ChannelTypeFeatures,
845 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
846 /// process of closure.
848 /// The channel_id of the channel which has been closed. Note that on-chain transactions
849 /// resolving the channel are likely still awaiting confirmation.
850 channel_id: [u8; 32],
851 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
852 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
853 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
854 /// `user_channel_id` will be randomized for inbound channels.
855 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
856 /// zero for objects serialized with LDK versions prior to 0.0.102.
858 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
859 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
860 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
861 user_channel_id: u128,
862 /// The reason the channel was closed.
863 reason: ClosureReason
865 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
866 /// inputs for another purpose.
868 /// The channel_id of the channel which has been closed.
869 channel_id: [u8; 32],
870 /// The full transaction received from the user
871 transaction: Transaction
873 /// Indicates a request to open a new channel by a peer.
875 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the
876 /// request, call [`ChannelManager::force_close_without_broadcasting_txn`].
878 /// The event is only triggered when a new open channel request is received and the
879 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
881 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
882 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
883 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
885 /// The temporary channel ID of the channel requested to be opened.
887 /// When responding to the request, the `temporary_channel_id` should be passed
888 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
889 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
891 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
892 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
893 temporary_channel_id: [u8; 32],
894 /// The node_id of the counterparty requesting to open the channel.
896 /// When responding to the request, the `counterparty_node_id` should be passed
897 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
898 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
901 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
902 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
903 counterparty_node_id: PublicKey,
904 /// The channel value of the requested channel.
905 funding_satoshis: u64,
906 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
908 /// The features that this channel will operate with. If you reject the channel, a
909 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
912 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
913 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
916 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
917 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
918 /// 0.0.107. Channels setting this type also need to get manually accepted via
919 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
920 /// or will be rejected otherwise.
922 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
923 channel_type: ChannelTypeFeatures,
925 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
928 /// Some scenarios where this event may be sent include:
929 /// * Insufficient capacity in the outbound channel
930 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
931 /// * When an unknown SCID is requested for forwarding a payment.
932 /// * Claiming an amount for an MPP payment that exceeds the HTLC total
933 /// * The HTLC has timed out
935 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
936 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
938 /// The channel over which the HTLC was received.
939 prev_channel_id: [u8; 32],
940 /// Destination of the HTLC that failed to be processed.
941 failed_next_destination: HTLCDestination,
944 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
945 /// requires confirmed external funds to be readily available to spend.
947 /// LDK does not currently generate this event. It is limited to the scope of channels with
948 /// anchor outputs, which will be introduced in a future release.
949 BumpTransaction(BumpTransactionEvent),
952 impl Writeable for Event {
953 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
955 &Event::FundingGenerationReady { .. } => {
957 // We never write out FundingGenerationReady events as, upon disconnection, peers
958 // drop any channels which have not yet exchanged funding_signed.
960 &Event::PaymentClaimable { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id } => {
962 let mut payment_secret = None;
963 let payment_preimage;
965 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
966 payment_secret = Some(secret);
967 payment_preimage = *preimage;
969 PaymentPurpose::SpontaneousPayment(preimage) => {
970 payment_preimage = Some(*preimage);
973 write_tlv_fields!(writer, {
974 (0, payment_hash, required),
975 (1, receiver_node_id, option),
976 (2, payment_secret, option),
977 (3, via_channel_id, option),
978 (4, amount_msat, required),
979 (5, via_user_channel_id, option),
980 (6, 0u64, required), // user_payment_id required for compatibility with 0.0.103 and earlier
981 (8, payment_preimage, option),
984 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
986 write_tlv_fields!(writer, {
987 (0, payment_preimage, required),
988 (1, payment_hash, required),
989 (3, payment_id, option),
990 (5, fee_paid_msat, option),
993 &Event::PaymentPathFailed {
994 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
995 ref path, ref short_channel_id, ref retry,
1003 error_code.write(writer)?;
1005 error_data.write(writer)?;
1006 write_tlv_fields!(writer, {
1007 (0, payment_hash, required),
1008 (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
1009 (2, payment_failed_permanently, required),
1010 (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
1011 (5, *path, vec_type),
1012 (7, short_channel_id, option),
1014 (11, payment_id, option),
1015 (13, failure, required),
1018 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
1020 // Note that we now ignore these on the read end as we'll re-generate them in
1021 // ChannelManager, we write them here only for backwards compatibility.
1023 &Event::SpendableOutputs { ref outputs } => {
1025 write_tlv_fields!(writer, {
1026 (0, WithoutLength(outputs), required),
1029 &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1031 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1032 write_tlv_fields!(writer, {
1033 (0, intercept_id, required),
1034 (2, intercept_scid, required),
1035 (4, payment_hash, required),
1036 (6, inbound_amount_msat, required),
1037 (8, expected_outbound_amount_msat, required),
1040 &Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
1042 write_tlv_fields!(writer, {
1043 (0, fee_earned_msat, option),
1044 (1, prev_channel_id, option),
1045 (2, claim_from_onchain_tx, required),
1046 (3, next_channel_id, option),
1049 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
1051 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1052 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1053 // separate u64 values.
1054 let user_channel_id_low = *user_channel_id as u64;
1055 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1056 write_tlv_fields!(writer, {
1057 (0, channel_id, required),
1058 (1, user_channel_id_low, required),
1059 (2, reason, required),
1060 (3, user_channel_id_high, required),
1063 &Event::DiscardFunding { ref channel_id, ref transaction } => {
1064 11u8.write(writer)?;
1065 write_tlv_fields!(writer, {
1066 (0, channel_id, required),
1067 (2, transaction, required)
1070 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1071 13u8.write(writer)?;
1072 write_tlv_fields!(writer, {
1073 (0, payment_id, required),
1074 (2, payment_hash, option),
1075 (4, *path, vec_type)
1078 &Event::PaymentFailed { ref payment_id, ref payment_hash } => {
1079 15u8.write(writer)?;
1080 write_tlv_fields!(writer, {
1081 (0, payment_id, required),
1082 (2, payment_hash, required),
1085 &Event::OpenChannelRequest { .. } => {
1086 17u8.write(writer)?;
1087 // We never write the OpenChannelRequest events as, upon disconnection, peers
1088 // drop any channels which have not yet exchanged funding_signed.
1090 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id } => {
1091 19u8.write(writer)?;
1092 write_tlv_fields!(writer, {
1093 (0, payment_hash, required),
1094 (1, receiver_node_id, option),
1095 (2, purpose, required),
1096 (4, amount_msat, required),
1099 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1100 21u8.write(writer)?;
1101 write_tlv_fields!(writer, {
1102 (0, payment_id, required),
1103 (2, payment_hash, required),
1104 (4, *path, vec_type)
1107 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1108 23u8.write(writer)?;
1109 write_tlv_fields!(writer, {
1110 (0, payment_id, required),
1111 (2, payment_hash, required),
1112 (4, *path, vec_type),
1113 (6, short_channel_id, option),
1116 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1117 25u8.write(writer)?;
1118 write_tlv_fields!(writer, {
1119 (0, prev_channel_id, required),
1120 (2, failed_next_destination, required),
1124 &Event::BumpTransaction(ref event)=> {
1125 27u8.write(writer)?;
1127 // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1128 // upon restarting anyway if they remain unresolved.
1129 BumpTransactionEvent::ChannelClose { .. } => {}
1130 BumpTransactionEvent::HTLCResolution { .. } => {}
1132 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1134 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1135 29u8.write(writer)?;
1136 write_tlv_fields!(writer, {
1137 (0, channel_id, required),
1138 (2, user_channel_id, required),
1139 (4, counterparty_node_id, required),
1140 (6, channel_type, required),
1143 // Note that, going forward, all new events must only write data inside of
1144 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1145 // data via `write_tlv_fields`.
1150 impl MaybeReadable for Event {
1151 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1152 match Readable::read(reader)? {
1153 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
1154 // unlike all other events, thus we return immediately here.
1158 let mut payment_hash = PaymentHash([0; 32]);
1159 let mut payment_preimage = None;
1160 let mut payment_secret = None;
1161 let mut amount_msat = 0;
1162 let mut receiver_node_id = None;
1163 let mut _user_payment_id = None::<u64>; // For compatibility with 0.0.103 and earlier
1164 let mut via_channel_id = None;
1165 let mut via_user_channel_id = None;
1166 read_tlv_fields!(reader, {
1167 (0, payment_hash, required),
1168 (1, receiver_node_id, option),
1169 (2, payment_secret, option),
1170 (3, via_channel_id, option),
1171 (4, amount_msat, required),
1172 (5, via_user_channel_id, option),
1173 (6, _user_payment_id, option),
1174 (8, payment_preimage, option),
1176 let purpose = match payment_secret {
1177 Some(secret) => PaymentPurpose::InvoicePayment {
1179 payment_secret: secret
1181 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1182 None => return Err(msgs::DecodeError::InvalidValue),
1184 Ok(Some(Event::PaymentClaimable {
1190 via_user_channel_id,
1197 let mut payment_preimage = PaymentPreimage([0; 32]);
1198 let mut payment_hash = None;
1199 let mut payment_id = None;
1200 let mut fee_paid_msat = None;
1201 read_tlv_fields!(reader, {
1202 (0, payment_preimage, required),
1203 (1, payment_hash, option),
1204 (3, payment_id, option),
1205 (5, fee_paid_msat, option),
1207 if payment_hash.is_none() {
1208 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
1210 Ok(Some(Event::PaymentSent {
1213 payment_hash: payment_hash.unwrap(),
1222 let error_code = Readable::read(reader)?;
1224 let error_data = Readable::read(reader)?;
1225 let mut payment_hash = PaymentHash([0; 32]);
1226 let mut payment_failed_permanently = false;
1227 let mut network_update = None;
1228 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1229 let mut short_channel_id = None;
1230 let mut retry = None;
1231 let mut payment_id = None;
1232 let mut failure_opt = None;
1233 read_tlv_fields!(reader, {
1234 (0, payment_hash, required),
1235 (1, network_update, upgradable_option),
1236 (2, payment_failed_permanently, required),
1237 (5, path, vec_type),
1238 (7, short_channel_id, option),
1240 (11, payment_id, option),
1241 (13, failure_opt, upgradable_option),
1243 let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1244 Ok(Some(Event::PaymentPathFailed {
1247 payment_failed_permanently,
1249 path: path.unwrap(),
1263 let mut outputs = WithoutLength(Vec::new());
1264 read_tlv_fields!(reader, {
1265 (0, outputs, required),
1267 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
1272 let mut payment_hash = PaymentHash([0; 32]);
1273 let mut intercept_id = InterceptId([0; 32]);
1274 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1275 let mut inbound_amount_msat = 0;
1276 let mut expected_outbound_amount_msat = 0;
1277 read_tlv_fields!(reader, {
1278 (0, intercept_id, required),
1279 (2, requested_next_hop_scid, required),
1280 (4, payment_hash, required),
1281 (6, inbound_amount_msat, required),
1282 (8, expected_outbound_amount_msat, required),
1284 let next_scid = match requested_next_hop_scid {
1285 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1287 Ok(Some(Event::HTLCIntercepted {
1289 requested_next_hop_scid: next_scid,
1290 inbound_amount_msat,
1291 expected_outbound_amount_msat,
1297 let mut fee_earned_msat = None;
1298 let mut prev_channel_id = None;
1299 let mut claim_from_onchain_tx = false;
1300 let mut next_channel_id = None;
1301 read_tlv_fields!(reader, {
1302 (0, fee_earned_msat, option),
1303 (1, prev_channel_id, option),
1304 (2, claim_from_onchain_tx, required),
1305 (3, next_channel_id, option),
1307 Ok(Some(Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id }))
1313 let mut channel_id = [0; 32];
1314 let mut reason = UpgradableRequired(None);
1315 let mut user_channel_id_low_opt: Option<u64> = None;
1316 let mut user_channel_id_high_opt: Option<u64> = None;
1317 read_tlv_fields!(reader, {
1318 (0, channel_id, required),
1319 (1, user_channel_id_low_opt, option),
1320 (2, reason, upgradable_required),
1321 (3, user_channel_id_high_opt, option),
1324 // `user_channel_id` used to be a single u64 value. In order to remain
1325 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1326 // as two separate u64 values.
1327 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1328 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1330 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required) }))
1336 let mut channel_id = [0; 32];
1337 let mut transaction = Transaction{ version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
1338 read_tlv_fields!(reader, {
1339 (0, channel_id, required),
1340 (2, transaction, required),
1342 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1348 let mut payment_id = PaymentId([0; 32]);
1349 let mut payment_hash = None;
1350 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1351 read_tlv_fields!(reader, {
1352 (0, payment_id, required),
1353 (2, payment_hash, option),
1354 (4, path, vec_type),
1356 Ok(Some(Event::PaymentPathSuccessful {
1359 path: path.unwrap(),
1366 let mut payment_hash = PaymentHash([0; 32]);
1367 let mut payment_id = PaymentId([0; 32]);
1368 read_tlv_fields!(reader, {
1369 (0, payment_id, required),
1370 (2, payment_hash, required),
1372 Ok(Some(Event::PaymentFailed {
1380 // Value 17 is used for `Event::OpenChannelRequest`.
1385 let mut payment_hash = PaymentHash([0; 32]);
1386 let mut purpose = UpgradableRequired(None);
1387 let mut amount_msat = 0;
1388 let mut receiver_node_id = None;
1389 read_tlv_fields!(reader, {
1390 (0, payment_hash, required),
1391 (1, receiver_node_id, option),
1392 (2, purpose, upgradable_required),
1393 (4, amount_msat, required),
1395 Ok(Some(Event::PaymentClaimed {
1398 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1406 let mut payment_id = PaymentId([0; 32]);
1407 let mut payment_hash = PaymentHash([0; 32]);
1408 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1409 read_tlv_fields!(reader, {
1410 (0, payment_id, required),
1411 (2, payment_hash, required),
1412 (4, path, vec_type),
1414 Ok(Some(Event::ProbeSuccessful {
1417 path: path.unwrap(),
1424 let mut payment_id = PaymentId([0; 32]);
1425 let mut payment_hash = PaymentHash([0; 32]);
1426 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1427 let mut short_channel_id = None;
1428 read_tlv_fields!(reader, {
1429 (0, payment_id, required),
1430 (2, payment_hash, required),
1431 (4, path, vec_type),
1432 (6, short_channel_id, option),
1434 Ok(Some(Event::ProbeFailed {
1437 path: path.unwrap(),
1445 let mut prev_channel_id = [0; 32];
1446 let mut failed_next_destination_opt = UpgradableRequired(None);
1447 read_tlv_fields!(reader, {
1448 (0, prev_channel_id, required),
1449 (2, failed_next_destination_opt, upgradable_required),
1451 Ok(Some(Event::HTLCHandlingFailed {
1453 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1461 let mut channel_id = [0; 32];
1462 let mut user_channel_id: u128 = 0;
1463 let mut counterparty_node_id = RequiredWrapper(None);
1464 let mut channel_type = RequiredWrapper(None);
1465 read_tlv_fields!(reader, {
1466 (0, channel_id, required),
1467 (2, user_channel_id, required),
1468 (4, counterparty_node_id, required),
1469 (6, channel_type, required),
1472 Ok(Some(Event::ChannelReady {
1475 counterparty_node_id: counterparty_node_id.0.unwrap(),
1476 channel_type: channel_type.0.unwrap()
1481 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1482 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1484 x if x % 2 == 1 => {
1485 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1486 // which prefixes the whole thing with a length BigSize. Because the event is
1487 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1488 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1489 // exactly the number of bytes specified, ignoring them entirely.
1490 let tlv_len: BigSize = Readable::read(reader)?;
1491 FixedLengthReader::new(reader, tlv_len.0)
1492 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1495 _ => Err(msgs::DecodeError::InvalidValue)
1500 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1501 /// broadcast to most peers).
1502 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1503 #[derive(Clone, Debug)]
1504 pub enum MessageSendEvent {
1505 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1506 /// message provided to the given peer.
1508 /// The node_id of the node which should receive this message
1510 /// The message which should be sent.
1511 msg: msgs::AcceptChannel,
1513 /// Used to indicate that we've initiated a channel open and should send the open_channel
1514 /// message provided to the given peer.
1516 /// The node_id of the node which should receive this message
1518 /// The message which should be sent.
1519 msg: msgs::OpenChannel,
1521 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1522 SendFundingCreated {
1523 /// The node_id of the node which should receive this message
1525 /// The message which should be sent.
1526 msg: msgs::FundingCreated,
1528 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1530 /// The node_id of the node which should receive this message
1532 /// The message which should be sent.
1533 msg: msgs::FundingSigned,
1535 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1537 /// The node_id of the node which should receive these message(s)
1539 /// The channel_ready message which should be sent.
1540 msg: msgs::ChannelReady,
1542 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1543 SendAnnouncementSignatures {
1544 /// The node_id of the node which should receive these message(s)
1546 /// The announcement_signatures message which should be sent.
1547 msg: msgs::AnnouncementSignatures,
1549 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1550 /// message should be sent to the peer with the given node_id.
1552 /// The node_id of the node which should receive these message(s)
1554 /// The update messages which should be sent. ALL messages in the struct should be sent!
1555 updates: msgs::CommitmentUpdate,
1557 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1559 /// The node_id of the node which should receive this message
1561 /// The message which should be sent.
1562 msg: msgs::RevokeAndACK,
1564 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1566 /// The node_id of the node which should receive this message
1568 /// The message which should be sent.
1569 msg: msgs::ClosingSigned,
1571 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1573 /// The node_id of the node which should receive this message
1575 /// The message which should be sent.
1576 msg: msgs::Shutdown,
1578 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1579 SendChannelReestablish {
1580 /// The node_id of the node which should receive this message
1582 /// The message which should be sent.
1583 msg: msgs::ChannelReestablish,
1585 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1586 /// initial connection to ensure our peers know about our channels.
1587 SendChannelAnnouncement {
1588 /// The node_id of the node which should receive this message
1590 /// The channel_announcement which should be sent.
1591 msg: msgs::ChannelAnnouncement,
1592 /// The followup channel_update which should be sent.
1593 update_msg: msgs::ChannelUpdate,
1595 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1596 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1598 /// Note that after doing so, you very likely (unless you did so very recently) want to
1599 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1600 /// ensures that any nodes which see our channel_announcement also have a relevant
1601 /// node_announcement, including relevant feature flags which may be important for routing
1602 /// through or to us.
1604 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1605 BroadcastChannelAnnouncement {
1606 /// The channel_announcement which should be sent.
1607 msg: msgs::ChannelAnnouncement,
1608 /// The followup channel_update which should be sent.
1609 update_msg: Option<msgs::ChannelUpdate>,
1611 /// Used to indicate that a channel_update should be broadcast to all peers.
1612 BroadcastChannelUpdate {
1613 /// The channel_update which should be sent.
1614 msg: msgs::ChannelUpdate,
1616 /// Used to indicate that a node_announcement should be broadcast to all peers.
1617 BroadcastNodeAnnouncement {
1618 /// The node_announcement which should be sent.
1619 msg: msgs::NodeAnnouncement,
1621 /// Used to indicate that a channel_update should be sent to a single peer.
1622 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1623 /// private channel and we shouldn't be informing all of our peers of channel parameters.
1625 /// The node_id of the node which should receive this message
1627 /// The channel_update which should be sent.
1628 msg: msgs::ChannelUpdate,
1630 /// Broadcast an error downstream to be handled
1632 /// The node_id of the node which should receive this message
1634 /// The action which should be taken.
1635 action: msgs::ErrorAction
1637 /// Query a peer for channels with funding transaction UTXOs in a block range.
1638 SendChannelRangeQuery {
1639 /// The node_id of this message recipient
1641 /// The query_channel_range which should be sent.
1642 msg: msgs::QueryChannelRange,
1644 /// Request routing gossip messages from a peer for a list of channels identified by
1645 /// their short_channel_ids.
1647 /// The node_id of this message recipient
1649 /// The query_short_channel_ids which should be sent.
1650 msg: msgs::QueryShortChannelIds,
1652 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1653 /// emitted during processing of the query.
1654 SendReplyChannelRange {
1655 /// The node_id of this message recipient
1657 /// The reply_channel_range which should be sent.
1658 msg: msgs::ReplyChannelRange,
1660 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1661 /// enable receiving gossip messages from the peer.
1662 SendGossipTimestampFilter {
1663 /// The node_id of this message recipient
1665 /// The gossip_timestamp_filter which should be sent.
1666 msg: msgs::GossipTimestampFilter,
1670 /// A trait indicating an object may generate message send events
1671 pub trait MessageSendEventsProvider {
1672 /// Gets the list of pending events which were generated by previous actions, clearing the list
1674 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1677 /// A trait indicating an object may generate onion messages to send
1678 pub trait OnionMessageProvider {
1679 /// Gets the next pending onion message for the peer with the given node id.
1680 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<msgs::OnionMessage>;
1683 /// A trait indicating an object may generate events.
1685 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1687 /// Implementations of this trait may also feature an async version of event handling, as shown with
1688 /// [`ChannelManager::process_pending_events_async`] and
1689 /// [`ChainMonitor::process_pending_events_async`].
1693 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1694 /// event since the last invocation.
1696 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1697 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1698 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1699 /// relevant changes to disk *before* returning.
1701 /// Further, because an application may crash between an [`Event`] being handled and the
1702 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1703 /// effect, [`Event`]s may be replayed.
1705 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1706 /// consult the provider's documentation on the implication of processing events and how a handler
1707 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1708 /// [`ChainMonitor::process_pending_events`]).
1710 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1713 /// [`process_pending_events`]: Self::process_pending_events
1714 /// [`handle_event`]: EventHandler::handle_event
1715 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1716 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1717 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
1718 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
1719 pub trait EventsProvider {
1720 /// Processes any events generated since the last call using the given event handler.
1722 /// See the trait-level documentation for requirements.
1723 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1726 /// A trait implemented for objects handling events from [`EventsProvider`].
1728 /// An async variation also exists for implementations of [`EventsProvider`] that support async
1729 /// event handling. The async event handler should satisfy the generic bounds: `F:
1730 /// core::future::Future, H: Fn(Event) -> F`.
1731 pub trait EventHandler {
1732 /// Handles the given [`Event`].
1734 /// See [`EventsProvider`] for details that must be considered when implementing this method.
1735 fn handle_event(&self, event: Event);
1738 impl<F> EventHandler for F where F: Fn(Event) {
1739 fn handle_event(&self, event: Event) {
1744 impl<T: EventHandler> EventHandler for Arc<T> {
1745 fn handle_event(&self, event: Event) {
1746 self.deref().handle_event(event)