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::msgs::DecodeError;
25 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
26 use crate::routing::gossip::NetworkUpdate;
27 use crate::util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, WithoutLength, OptionDeserWrapper};
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 #[derive(Clone, Debug, PartialEq, Eq)]
86 /// The reason the channel was closed. See individual variants more details.
87 pub enum ClosureReason {
88 /// Closure generated from receiving a peer error message.
90 /// Our counterparty may have broadcasted their latest commitment state, and we have
92 CounterpartyForceClosed {
93 /// The error which the peer sent us.
95 /// The string should be sanitized before it is used (e.g emitted to logs
96 /// or printed to stdout). Otherwise, a well crafted error message may exploit
97 /// a security vulnerability in the terminal emulator or the logging subsystem.
100 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
102 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
104 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
105 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
106 //TODO: split between CounterpartyInitiated/LocallyInitiated
108 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
109 /// commitment transaction came from our counterparty, but it may also have come from
110 /// a copy of our own `ChannelMonitor`.
111 CommitmentTxConfirmed,
112 /// The funding transaction failed to confirm in a timely manner on an inbound channel.
114 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
116 /// A developer-readable error message which we generated.
119 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
120 /// forget the channel entirely - we can attempt again if the peer reconnects.
122 /// This includes cases where we restarted prior to funding completion, including prior to the
123 /// initial [`ChannelMonitor`] persistence completing.
125 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
126 /// peer because of mutual incompatibility between us and our channel counterparty.
128 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
130 /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
131 /// the [`ChannelManager`] deserialized.
133 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
134 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
135 OutdatedChannelManager
138 impl core::fmt::Display for ClosureReason {
139 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
140 f.write_str("Channel closed because ")?;
142 ClosureReason::CounterpartyForceClosed { peer_msg } => {
143 f.write_str("counterparty force-closed with message ")?;
144 f.write_str(&peer_msg)
146 ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
147 ClosureReason::CooperativeClosure => f.write_str("the channel was cooperatively closed"),
148 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
149 ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
150 ClosureReason::ProcessingError { err } => {
151 f.write_str("of an exception: ")?;
154 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
155 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
160 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
161 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
162 (1, FundingTimedOut) => {},
163 (2, HolderForceClosed) => {},
164 (6, CommitmentTxConfirmed) => {},
165 (4, CooperativeClosure) => {},
166 (8, ProcessingError) => { (1, err, required) },
167 (10, DisconnectedPeer) => {},
168 (12, OutdatedChannelManager) => {},
171 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
172 #[derive(Clone, Debug, PartialEq, Eq)]
173 pub enum HTLCDestination {
174 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
175 /// there is insufficient capacity in our outbound channel.
177 /// The `node_id` of the next node. For backwards compatibility, this field is
178 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
179 /// counterparty node information.
180 node_id: Option<PublicKey>,
181 /// The outgoing `channel_id` between us and the next node.
182 channel_id: [u8; 32],
184 /// Scenario where we are unsure of the next node to forward the HTLC to.
186 /// Short channel id we are requesting to forward an HTLC to.
187 requested_forward_scid: u64,
189 /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
192 /// Short channel id we are requesting to forward an HTLC to.
193 requested_forward_scid: u64
195 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
196 /// but is invalid for some reason, so we reject it.
198 /// Some of the reasons may include:
200 /// * Expected MPP amount to claim does not equal HTLC total
201 /// * Claimable amount does not match expected amount
203 /// The payment hash of the payment we attempted to process.
204 payment_hash: PaymentHash
208 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
209 (0, NextHopChannel) => {
210 (0, node_id, required),
211 (2, channel_id, required),
213 (1, InvalidForward) => {
214 (0, requested_forward_scid, required),
216 (2, UnknownNextHop) => {
217 (0, requested_forward_scid, required),
219 (4, FailedPayment) => {
220 (0, payment_hash, required),
225 /// A descriptor used to sign for a commitment transaction's anchor output.
226 #[derive(Clone, Debug)]
227 pub struct AnchorDescriptor {
228 /// A unique identifier used along with `channel_value_satoshis` to re-derive the
229 /// [`InMemorySigner`] required to sign `input`.
231 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
232 pub channel_keys_id: [u8; 32],
233 /// The value in satoshis of the channel we're attempting to spend the anchor output of. This is
234 /// used along with `channel_keys_id` to re-derive the [`InMemorySigner`] required to sign
237 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
238 pub channel_value_satoshis: u64,
239 /// The transaction input's outpoint corresponding to the commitment transaction's anchor
241 pub outpoint: OutPoint,
245 /// A descriptor used to sign for a commitment transaction's HTLC output.
246 #[derive(Clone, Debug)]
247 pub struct HTLCDescriptor {
248 /// A unique identifier used along with `channel_value_satoshis` to re-derive the
249 /// [`InMemorySigner`] required to sign `input`.
251 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
252 pub channel_keys_id: [u8; 32],
253 /// The value in satoshis of the channel we're attempting to spend the anchor output of. This is
254 /// used along with `channel_keys_id` to re-derive the [`InMemorySigner`] required to sign
257 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
258 pub channel_value_satoshis: u64,
259 /// The necessary channel parameters that need to be provided to the re-derived
260 /// [`InMemorySigner`] through [`BaseSign::provide_channel_parameters`].
262 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
263 /// [`BaseSign::provide_channel_parameters`]: crate::chain::keysinterface::BaseSign::provide_channel_parameters
264 pub channel_parameters: ChannelTransactionParameters,
265 /// The txid of the commitment transaction in which the HTLC output lives.
266 pub commitment_txid: Txid,
267 /// The number of the commitment transaction in which the HTLC output lives.
268 pub per_commitment_number: u64,
269 /// The details of the HTLC as it appears in the commitment transaction.
270 pub htlc: HTLCOutputInCommitment,
271 /// The preimage, if `Some`, to claim the HTLC output with. If `None`, the timeout path must be
273 pub preimage: Option<PaymentPreimage>,
274 /// The counterparty's signature required to spend the HTLC output.
275 pub counterparty_sig: Signature
279 impl HTLCDescriptor {
280 /// Returns the unsigned transaction input spending the HTLC output in the commitment
282 pub fn unsigned_tx_input(&self) -> TxIn {
283 chan_utils::build_htlc_input(&self.commitment_txid, &self.htlc, true /* opt_anchors */)
286 /// Returns the delayed output created as a result of spending the HTLC output in the commitment
288 pub fn tx_output<C: secp256k1::Signing + secp256k1::Verification>(
289 &self, per_commitment_point: &PublicKey, secp: &Secp256k1<C>
291 let channel_params = self.channel_parameters.as_holder_broadcastable();
292 let broadcaster_keys = channel_params.broadcaster_pubkeys();
293 let counterparty_keys = channel_params.countersignatory_pubkeys();
294 let broadcaster_delayed_key = chan_utils::derive_public_key(
295 secp, per_commitment_point, &broadcaster_keys.delayed_payment_basepoint
297 let counterparty_revocation_key = chan_utils::derive_public_revocation_key(
298 secp, per_commitment_point, &counterparty_keys.revocation_basepoint
300 chan_utils::build_htlc_output(
301 0 /* feerate_per_kw */, channel_params.contest_delay(), &self.htlc, true /* opt_anchors */,
302 false /* use_non_zero_fee_anchors */, &broadcaster_delayed_key, &counterparty_revocation_key
306 /// Returns the witness script of the HTLC output in the commitment transaction.
307 pub fn witness_script<C: secp256k1::Signing + secp256k1::Verification>(
308 &self, per_commitment_point: &PublicKey, secp: &Secp256k1<C>
310 let channel_params = self.channel_parameters.as_holder_broadcastable();
311 let broadcaster_keys = channel_params.broadcaster_pubkeys();
312 let counterparty_keys = channel_params.countersignatory_pubkeys();
313 let broadcaster_htlc_key = chan_utils::derive_public_key(
314 secp, per_commitment_point, &broadcaster_keys.htlc_basepoint
316 let counterparty_htlc_key = chan_utils::derive_public_key(
317 secp, per_commitment_point, &counterparty_keys.htlc_basepoint
319 let counterparty_revocation_key = chan_utils::derive_public_revocation_key(
320 secp, per_commitment_point, &counterparty_keys.revocation_basepoint
322 chan_utils::get_htlc_redeemscript_with_explicit_keys(
323 &self.htlc, true /* opt_anchors */, &broadcaster_htlc_key, &counterparty_htlc_key,
324 &counterparty_revocation_key,
328 /// Returns the fully signed witness required to spend the HTLC output in the commitment
330 pub fn tx_input_witness(&self, signature: &Signature, witness_script: &Script) -> Witness {
331 chan_utils::build_htlc_input_witness(
332 signature, &self.counterparty_sig, &self.preimage, witness_script, true /* opt_anchors */
338 /// Represents the different types of transactions, originating from LDK, to be bumped.
339 #[derive(Clone, Debug)]
340 pub enum BumpTransactionEvent {
341 /// Indicates that a channel featuring anchor outputs is to be closed by broadcasting the local
342 /// commitment transaction. Since commitment transactions have a static feerate pre-agreed upon,
343 /// they may need additional fees to be attached through a child transaction using the popular
344 /// [Child-Pays-For-Parent](https://bitcoinops.org/en/topics/cpfp) fee bumping technique. This
345 /// child transaction must include the anchor input described within `anchor_descriptor` along
346 /// with additional inputs to meet the target feerate. Failure to meet the target feerate
347 /// decreases the confirmation odds of the transaction package (which includes the commitment
348 /// and child anchor transactions), possibly resulting in a loss of funds. Once the transaction
349 /// is constructed, it must be fully signed for and broadcast by the consumer of the event
350 /// along with the `commitment_tx` enclosed. Note that the `commitment_tx` must always be
351 /// broadcast first, as the child anchor transaction depends on it.
353 /// The consumer should be able to sign for any of the additional inputs included within the
354 /// child anchor transaction. To sign its anchor input, an [`InMemorySigner`] should be
355 /// re-derived through [`KeysManager::derive_channel_keys`] with the help of
356 /// [`AnchorDescriptor::channel_keys_id`] and [`AnchorDescriptor::channel_value_satoshis`]. The
357 /// anchor input signature can be computed with [`BaseSign::sign_holder_anchor_input`],
358 /// which can then be provided to [`build_anchor_input_witness`] along with the `funding_pubkey`
359 /// to obtain the full witness required to spend.
361 /// It is possible to receive more than one instance of this event if a valid child anchor
362 /// transaction is never broadcast or is but not with a sufficient fee to be mined. Care should
363 /// be taken by the consumer of the event to ensure any future iterations of the child anchor
364 /// transaction adhere to the [Replace-By-Fee
365 /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
366 /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
367 /// these events is not user-controlled, users may ignore/drop the event if they are no longer
368 /// able to commit external confirmed funds to the child anchor transaction.
370 /// The set of `pending_htlcs` on the commitment transaction to be broadcast can be inspected to
371 /// determine whether a significant portion of the channel's funds are allocated to HTLCs,
372 /// enabling users to make their own decisions regarding the importance of the commitment
373 /// transaction's confirmation. Note that this is not required, but simply exists as an option
374 /// for users to override LDK's behavior. On commitments with no HTLCs (indicated by those with
375 /// an empty `pending_htlcs`), confirmation of the commitment transaction can be considered to
378 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
379 /// [`KeysManager::derive_channel_keys`]: crate::chain::keysinterface::KeysManager::derive_channel_keys
380 /// [`BaseSign::sign_holder_anchor_input`]: crate::chain::keysinterface::BaseSign::sign_holder_anchor_input
381 /// [`build_anchor_input_witness`]: crate::ln::chan_utils::build_anchor_input_witness
383 /// The target feerate that the transaction package, which consists of the commitment
384 /// transaction and the to-be-crafted child anchor transaction, must meet.
385 package_target_feerate_sat_per_1000_weight: u32,
386 /// The channel's commitment transaction to bump the fee of. This transaction should be
387 /// broadcast along with the anchor transaction constructed as a result of consuming this
389 commitment_tx: Transaction,
390 /// The absolute fee in satoshis of the commitment transaction. This can be used along the
391 /// with weight of the commitment transaction to determine its feerate.
392 commitment_tx_fee_satoshis: u64,
393 /// The descriptor to sign the anchor input of the anchor transaction constructed as a
394 /// result of consuming this event.
395 anchor_descriptor: AnchorDescriptor,
396 /// The set of pending HTLCs on the commitment transaction that need to be resolved once the
397 /// commitment transaction confirms.
398 pending_htlcs: Vec<HTLCOutputInCommitment>,
400 /// Indicates that a channel featuring anchor outputs has unilaterally closed on-chain by a
401 /// holder commitment transaction and its HTLC(s) need to be resolved on-chain. With the
402 /// zero-HTLC-transaction-fee variant of anchor outputs, the pre-signed HTLC
403 /// transactions have a zero fee, thus requiring additional inputs and/or outputs to be attached
404 /// for a timely confirmation within the chain. These additional inputs and/or outputs must be
405 /// appended to the resulting HTLC transaction to meet the target feerate. Failure to meet the
406 /// target feerate decreases the confirmation odds of the transaction, possibly resulting in a
407 /// loss of funds. Once the transaction meets the target feerate, it must be signed for and
408 /// broadcast by the consumer of the event.
410 /// The consumer should be able to sign for any of the non-HTLC inputs added to the resulting
411 /// HTLC transaction. To sign HTLC inputs, an [`InMemorySigner`] should be re-derived through
412 /// [`KeysManager::derive_channel_keys`] with the help of `channel_keys_id` and
413 /// `channel_value_satoshis`. Each HTLC input's signature can be computed with
414 /// [`BaseSign::sign_holder_htlc_transaction`], which can then be provided to
415 /// [`HTLCDescriptor::tx_input_witness`] to obtain the fully signed witness required to spend.
417 /// It is possible to receive more than one instance of this event if a valid HTLC transaction
418 /// is never broadcast or is but not with a sufficient fee to be mined. Care should be taken by
419 /// the consumer of the event to ensure any future iterations of the HTLC transaction adhere to
420 /// the [Replace-By-Fee
421 /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
422 /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
423 /// these events is not user-controlled, users may ignore/drop the event if either they are no
424 /// longer able to commit external confirmed funds to the HTLC transaction or the fee committed
425 /// to the HTLC transaction is greater in value than the HTLCs being claimed.
427 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
428 /// [`KeysManager::derive_channel_keys`]: crate::chain::keysinterface::KeysManager::derive_channel_keys
429 /// [`BaseSign::sign_holder_htlc_transaction`]: crate::chain::keysinterface::BaseSign::sign_holder_htlc_transaction
430 /// [`HTLCDescriptor::tx_input_witness`]: HTLCDescriptor::tx_input_witness
432 target_feerate_sat_per_1000_weight: u32,
433 htlc_descriptors: Vec<HTLCDescriptor>,
437 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
438 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
439 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
440 /// intercepts in upcoming work.
441 enum InterceptNextHop {
443 requested_next_hop_scid: u64,
447 impl_writeable_tlv_based_enum!(InterceptNextHop,
449 (0, requested_next_hop_scid, required),
453 /// An Event which you should probably take some action in response to.
455 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
456 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
457 /// written as it makes no sense to respond to it after reconnecting to peers).
458 #[derive(Clone, Debug, PartialEq, Eq)]
460 /// Used to indicate that the client should generate a funding transaction with the given
461 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
462 /// Generated in [`ChannelManager`] message handling.
463 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
464 /// counterparty can steal your funds!
466 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
467 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
468 FundingGenerationReady {
469 /// The random channel_id we picked which you'll need to pass into
470 /// [`ChannelManager::funding_transaction_generated`].
472 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
473 temporary_channel_id: [u8; 32],
474 /// The counterparty's node_id, which you'll need to pass back into
475 /// [`ChannelManager::funding_transaction_generated`].
477 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
478 counterparty_node_id: PublicKey,
479 /// The value, in satoshis, that the output should have.
480 channel_value_satoshis: u64,
481 /// The script which should be used in the transaction output.
482 output_script: Script,
483 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or a
484 /// random value for an inbound channel. This may be zero for objects serialized with LDK
485 /// versions prior to 0.0.113.
487 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
488 user_channel_id: u128,
490 /// Indicates that we've been offered a payment and it needs to be claimed via calling
491 /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
493 /// Note that if the preimage is not known, you should call
494 /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
495 /// to free up resources for this HTLC and avoid network congestion.
496 /// If you fail to call either [`ChannelManager::claim_funds`], [`ChannelManager::fail_htlc_backwards`],
497 /// or [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will be
498 /// automatically failed.
501 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
502 /// `PaymentClaimable` events may be generated for the same payment.
505 /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
507 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
508 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
509 /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
511 /// The node that will receive the payment after it has been claimed.
512 /// This is useful to identify payments received via [phantom nodes].
513 /// This field will always be filled in when the event was generated by LDK versions
514 /// 0.0.113 and above.
516 /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
517 receiver_node_id: Option<PublicKey>,
518 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
519 /// not stop you from registering duplicate payment hashes for inbound payments.
520 payment_hash: PaymentHash,
521 /// The value, in thousandths of a satoshi, that this payment is for.
523 /// Information for claiming this received payment, based on whether the purpose of the
524 /// payment is to pay an invoice or to send a spontaneous payment.
525 purpose: PaymentPurpose,
526 /// The `channel_id` indicating over which channel we received the payment.
527 via_channel_id: Option<[u8; 32]>,
528 /// The `user_channel_id` indicating over which channel we received the payment.
529 via_user_channel_id: Option<u128>,
531 /// Indicates a payment has been claimed and we've received money!
533 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
534 /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
535 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
536 /// [`Event::PaymentClaimable`] event.
539 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
540 /// `PaymentClaimable` events may be generated for the same payment. If you then call
541 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
542 /// multiple `PaymentClaimed` events.
544 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
546 /// The node that received the payment.
547 /// This is useful to identify payments which were received via [phantom nodes].
548 /// This field will always be filled in when the event was generated by LDK versions
549 /// 0.0.113 and above.
551 /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
552 receiver_node_id: Option<PublicKey>,
553 /// The payment hash of the claimed payment. Note that LDK will not stop you from
554 /// registering duplicate payment hashes for inbound payments.
555 payment_hash: PaymentHash,
556 /// The value, in thousandths of a satoshi, that this payment is for.
558 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
559 /// spontaneous payment.
560 purpose: PaymentPurpose,
562 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
563 /// and we got back the payment preimage for it).
565 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
566 /// event. In this situation, you SHOULD treat this payment as having succeeded.
568 /// The id returned by [`ChannelManager::send_payment`].
570 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
571 payment_id: Option<PaymentId>,
572 /// The preimage to the hash given to ChannelManager::send_payment.
573 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
574 /// store it somehow!
575 payment_preimage: PaymentPreimage,
576 /// The hash that was given to [`ChannelManager::send_payment`].
578 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
579 payment_hash: PaymentHash,
580 /// The total fee which was spent at intermediate hops in this payment, across all paths.
582 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
583 /// overpayment to the recipient node.
585 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
586 /// overstate the amount paid, though this is unlikely.
588 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
589 fee_paid_msat: Option<u64>,
591 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
592 /// provide failure information for each MPP part in the payment.
594 /// This event is provided once there are no further pending HTLCs for the payment and the
595 /// payment is no longer retryable, due either to the [`Retry`] provided or
596 /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
598 /// [`Retry`]: crate::ln::channelmanager::Retry
599 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
601 /// The id returned by [`ChannelManager::send_payment`] and used with
602 /// [`ChannelManager::abandon_payment`].
604 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
605 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
606 payment_id: PaymentId,
607 /// The hash that was given to [`ChannelManager::send_payment`].
609 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
610 payment_hash: PaymentHash,
612 /// Indicates that a path for an outbound payment was successful.
614 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
615 /// [`Event::PaymentSent`] for obtaining the payment preimage.
616 PaymentPathSuccessful {
617 /// The id returned by [`ChannelManager::send_payment`].
619 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
620 payment_id: PaymentId,
621 /// The hash that was given to [`ChannelManager::send_payment`].
623 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
624 payment_hash: Option<PaymentHash>,
625 /// The payment path that was successful.
627 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
630 /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
633 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
634 /// [`Event::PaymentFailed`] and [`all_paths_failed`].
636 /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
639 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
640 /// [`all_paths_failed`]: Self::PaymentPathFailed::all_paths_failed
642 /// The id returned by [`ChannelManager::send_payment`] and used with
643 /// [`ChannelManager::abandon_payment`].
645 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
646 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
647 payment_id: Option<PaymentId>,
648 /// The hash that was given to [`ChannelManager::send_payment`].
650 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
651 payment_hash: PaymentHash,
652 /// Indicates the payment was rejected for some reason by the recipient. This implies that
653 /// the payment has failed, not just the route in question. If this is not set, the payment may
654 /// be retried via a different route.
655 payment_failed_permanently: bool,
656 /// Any failure information conveyed via the Onion return packet by a node along the failed
659 /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into
660 /// account the update.
662 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
663 network_update: Option<NetworkUpdate>,
664 /// For both single-path and multi-path payments, this is set if all paths of the payment have
665 /// failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the
666 /// larger MPP payment were still in flight when this event was generated.
667 all_paths_failed: bool,
668 /// The payment path that failed.
670 /// The channel responsible for the failed payment path.
672 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
673 /// may not refer to a channel in the public network graph. These aliases may also collide
674 /// with channels in the public network graph.
676 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
677 /// retried. May be `None` for older [`Event`] serializations.
678 short_channel_id: Option<u64>,
679 /// Parameters used by LDK to compute a new [`Route`] when retrying the failed payment path.
681 /// [`Route`]: crate::routing::router::Route
682 retry: Option<RouteParameters>,
684 error_code: Option<u16>,
686 error_data: Option<Vec<u8>>,
688 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
690 /// The id returned by [`ChannelManager::send_probe`].
692 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
693 payment_id: PaymentId,
694 /// The hash generated by [`ChannelManager::send_probe`].
696 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
697 payment_hash: PaymentHash,
698 /// The payment path that was successful.
701 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
703 /// The id returned by [`ChannelManager::send_probe`].
705 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
706 payment_id: PaymentId,
707 /// The hash generated by [`ChannelManager::send_probe`].
709 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
710 payment_hash: PaymentHash,
711 /// The payment path that failed.
713 /// The channel responsible for the failed probe.
715 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
716 /// may not refer to a channel in the public network graph. These aliases may also collide
717 /// with channels in the public network graph.
718 short_channel_id: Option<u64>,
720 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
721 /// a time in the future.
723 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
724 PendingHTLCsForwardable {
725 /// The minimum amount of time that should be waited prior to calling
726 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
727 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
728 /// now + 5*time_forwardable).
729 time_forwardable: Duration,
731 /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
732 /// you've encoded an intercept scid in the receiver's invoice route hints using
733 /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
735 /// [`ChannelManager::forward_intercepted_htlc`] or
736 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
737 /// their docs for more information.
739 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
740 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
741 /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
742 /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
744 /// An id to help LDK identify which HTLC is being forwarded or failed.
745 intercept_id: InterceptId,
746 /// The fake scid that was programmed as the next hop's scid, generated using
747 /// [`ChannelManager::get_intercept_scid`].
749 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
750 requested_next_hop_scid: u64,
751 /// The payment hash used for this HTLC.
752 payment_hash: PaymentHash,
753 /// How many msats were received on the inbound edge of this HTLC.
754 inbound_amount_msat: u64,
755 /// How many msats the payer intended to route to the next node. Depending on the reason you are
756 /// intercepting this payment, you might take a fee by forwarding less than this amount.
758 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
759 /// check that whatever fee you want has been included here or subtract it as required. Further,
760 /// LDK will not stop you from forwarding more than you received.
761 expected_outbound_amount_msat: u64,
763 /// Used to indicate that an output which you should know how to spend was confirmed on chain
764 /// and is now spendable.
765 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
766 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
767 /// somewhere and spend them when you create on-chain transactions.
769 /// The outputs which you should store as spendable by you.
770 outputs: Vec<SpendableOutputDescriptor>,
772 /// This event is generated when a payment has been successfully forwarded through us and a
773 /// forwarding fee earned.
775 /// The incoming channel between the previous node and us. This is only `None` for events
776 /// generated or serialized by versions prior to 0.0.107.
777 prev_channel_id: Option<[u8; 32]>,
778 /// The outgoing channel between the next node and us. This is only `None` for events
779 /// generated or serialized by versions prior to 0.0.107.
780 next_channel_id: Option<[u8; 32]>,
781 /// The fee, in milli-satoshis, which was earned as a result of the payment.
783 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
784 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
785 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
786 /// claimed the full value in millisatoshis from the source. In this case,
787 /// `claim_from_onchain_tx` will be set.
789 /// If the channel which sent us the payment has been force-closed, we will claim the funds
790 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
791 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
792 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
794 fee_earned_msat: Option<u64>,
795 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
797 claim_from_onchain_tx: bool,
799 /// Used to indicate that a channel with the given `channel_id` is ready to
800 /// be used. This event is emitted either when the funding transaction has been confirmed
801 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
804 /// The channel_id of the channel that is ready.
805 channel_id: [u8; 32],
806 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
807 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
808 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
809 /// `user_channel_id` will be randomized for an inbound channel.
811 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
812 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
813 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
814 user_channel_id: u128,
815 /// The node_id of the channel counterparty.
816 counterparty_node_id: PublicKey,
817 /// The features that this channel will operate with.
818 channel_type: ChannelTypeFeatures,
820 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
821 /// process of closure.
823 /// The channel_id of the channel which has been closed. Note that on-chain transactions
824 /// resolving the channel are likely still awaiting confirmation.
825 channel_id: [u8; 32],
826 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
827 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
828 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
829 /// `user_channel_id` will be randomized for inbound channels.
830 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
831 /// zero for objects serialized with LDK versions prior to 0.0.102.
833 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
834 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
835 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
836 user_channel_id: u128,
837 /// The reason the channel was closed.
838 reason: ClosureReason
840 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
841 /// inputs for another purpose.
843 /// The channel_id of the channel which has been closed.
844 channel_id: [u8; 32],
845 /// The full transaction received from the user
846 transaction: Transaction
848 /// Indicates a request to open a new channel by a peer.
850 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the
851 /// request, call [`ChannelManager::force_close_without_broadcasting_txn`].
853 /// The event is only triggered when a new open channel request is received and the
854 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
856 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
857 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
858 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
860 /// The temporary channel ID of the channel requested to be opened.
862 /// When responding to the request, the `temporary_channel_id` should be passed
863 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
864 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
866 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
867 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
868 temporary_channel_id: [u8; 32],
869 /// The node_id of the counterparty requesting to open the channel.
871 /// When responding to the request, the `counterparty_node_id` should be passed
872 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
873 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
876 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
877 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
878 counterparty_node_id: PublicKey,
879 /// The channel value of the requested channel.
880 funding_satoshis: u64,
881 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
883 /// The features that this channel will operate with. If you reject the channel, a
884 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
887 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
888 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
891 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
892 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
893 /// 0.0.107. Channels setting this type also need to get manually accepted via
894 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
895 /// or will be rejected otherwise.
897 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
898 channel_type: ChannelTypeFeatures,
900 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
903 /// Some scenarios where this event may be sent include:
904 /// * Insufficient capacity in the outbound channel
905 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
906 /// * When an unknown SCID is requested for forwarding a payment.
907 /// * Claiming an amount for an MPP payment that exceeds the HTLC total
908 /// * The HTLC has timed out
910 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
911 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
913 /// The channel over which the HTLC was received.
914 prev_channel_id: [u8; 32],
915 /// Destination of the HTLC that failed to be processed.
916 failed_next_destination: HTLCDestination,
919 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
920 /// requires confirmed external funds to be readily available to spend.
922 /// LDK does not currently generate this event. It is limited to the scope of channels with
923 /// anchor outputs, which will be introduced in a future release.
924 BumpTransaction(BumpTransactionEvent),
927 impl Writeable for Event {
928 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
930 &Event::FundingGenerationReady { .. } => {
932 // We never write out FundingGenerationReady events as, upon disconnection, peers
933 // drop any channels which have not yet exchanged funding_signed.
935 &Event::PaymentClaimable { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id } => {
937 let mut payment_secret = None;
938 let payment_preimage;
940 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
941 payment_secret = Some(secret);
942 payment_preimage = *preimage;
944 PaymentPurpose::SpontaneousPayment(preimage) => {
945 payment_preimage = Some(*preimage);
948 write_tlv_fields!(writer, {
949 (0, payment_hash, required),
950 (1, receiver_node_id, option),
951 (2, payment_secret, option),
952 (3, via_channel_id, option),
953 (4, amount_msat, required),
954 (5, via_user_channel_id, option),
955 (6, 0u64, required), // user_payment_id required for compatibility with 0.0.103 and earlier
956 (8, payment_preimage, option),
959 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
961 write_tlv_fields!(writer, {
962 (0, payment_preimage, required),
963 (1, payment_hash, required),
964 (3, payment_id, option),
965 (5, fee_paid_msat, option),
968 &Event::PaymentPathFailed {
969 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update,
970 ref all_paths_failed, ref path, ref short_channel_id, ref retry,
978 error_code.write(writer)?;
980 error_data.write(writer)?;
981 write_tlv_fields!(writer, {
982 (0, payment_hash, required),
983 (1, network_update, option),
984 (2, payment_failed_permanently, required),
985 (3, all_paths_failed, required),
986 (5, *path, vec_type),
987 (7, short_channel_id, option),
989 (11, payment_id, option),
992 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
994 // Note that we now ignore these on the read end as we'll re-generate them in
995 // ChannelManager, we write them here only for backwards compatibility.
997 &Event::SpendableOutputs { ref outputs } => {
999 write_tlv_fields!(writer, {
1000 (0, WithoutLength(outputs), required),
1003 &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1005 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1006 write_tlv_fields!(writer, {
1007 (0, intercept_id, required),
1008 (2, intercept_scid, required),
1009 (4, payment_hash, required),
1010 (6, inbound_amount_msat, required),
1011 (8, expected_outbound_amount_msat, required),
1014 &Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
1016 write_tlv_fields!(writer, {
1017 (0, fee_earned_msat, option),
1018 (1, prev_channel_id, option),
1019 (2, claim_from_onchain_tx, required),
1020 (3, next_channel_id, option),
1023 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
1025 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1026 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1027 // separate u64 values.
1028 let user_channel_id_low = *user_channel_id as u64;
1029 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1030 write_tlv_fields!(writer, {
1031 (0, channel_id, required),
1032 (1, user_channel_id_low, required),
1033 (2, reason, required),
1034 (3, user_channel_id_high, required),
1037 &Event::DiscardFunding { ref channel_id, ref transaction } => {
1038 11u8.write(writer)?;
1039 write_tlv_fields!(writer, {
1040 (0, channel_id, required),
1041 (2, transaction, required)
1044 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1045 13u8.write(writer)?;
1046 write_tlv_fields!(writer, {
1047 (0, payment_id, required),
1048 (2, payment_hash, option),
1049 (4, *path, vec_type)
1052 &Event::PaymentFailed { ref payment_id, ref payment_hash } => {
1053 15u8.write(writer)?;
1054 write_tlv_fields!(writer, {
1055 (0, payment_id, required),
1056 (2, payment_hash, required),
1059 &Event::OpenChannelRequest { .. } => {
1060 17u8.write(writer)?;
1061 // We never write the OpenChannelRequest events as, upon disconnection, peers
1062 // drop any channels which have not yet exchanged funding_signed.
1064 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id } => {
1065 19u8.write(writer)?;
1066 write_tlv_fields!(writer, {
1067 (0, payment_hash, required),
1068 (1, receiver_node_id, option),
1069 (2, purpose, required),
1070 (4, amount_msat, required),
1073 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1074 21u8.write(writer)?;
1075 write_tlv_fields!(writer, {
1076 (0, payment_id, required),
1077 (2, payment_hash, required),
1078 (4, *path, vec_type)
1081 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1082 23u8.write(writer)?;
1083 write_tlv_fields!(writer, {
1084 (0, payment_id, required),
1085 (2, payment_hash, required),
1086 (4, *path, vec_type),
1087 (6, short_channel_id, option),
1090 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1091 25u8.write(writer)?;
1092 write_tlv_fields!(writer, {
1093 (0, prev_channel_id, required),
1094 (2, failed_next_destination, required),
1098 &Event::BumpTransaction(ref event)=> {
1099 27u8.write(writer)?;
1101 // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1102 // upon restarting anyway if they remain unresolved.
1103 BumpTransactionEvent::ChannelClose { .. } => {}
1104 BumpTransactionEvent::HTLCResolution { .. } => {}
1106 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1108 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1109 29u8.write(writer)?;
1110 write_tlv_fields!(writer, {
1111 (0, channel_id, required),
1112 (2, user_channel_id, required),
1113 (4, counterparty_node_id, required),
1114 (6, channel_type, required),
1117 // Note that, going forward, all new events must only write data inside of
1118 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1119 // data via `write_tlv_fields`.
1124 impl MaybeReadable for Event {
1125 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1126 match Readable::read(reader)? {
1127 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
1128 // unlike all other events, thus we return immediately here.
1132 let mut payment_hash = PaymentHash([0; 32]);
1133 let mut payment_preimage = None;
1134 let mut payment_secret = None;
1135 let mut amount_msat = 0;
1136 let mut receiver_node_id = None;
1137 let mut _user_payment_id = None::<u64>; // For compatibility with 0.0.103 and earlier
1138 let mut via_channel_id = None;
1139 let mut via_user_channel_id = None;
1140 read_tlv_fields!(reader, {
1141 (0, payment_hash, required),
1142 (1, receiver_node_id, option),
1143 (2, payment_secret, option),
1144 (3, via_channel_id, option),
1145 (4, amount_msat, required),
1146 (5, via_user_channel_id, option),
1147 (6, _user_payment_id, option),
1148 (8, payment_preimage, option),
1150 let purpose = match payment_secret {
1151 Some(secret) => PaymentPurpose::InvoicePayment {
1153 payment_secret: secret
1155 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1156 None => return Err(msgs::DecodeError::InvalidValue),
1158 Ok(Some(Event::PaymentClaimable {
1164 via_user_channel_id,
1171 let mut payment_preimage = PaymentPreimage([0; 32]);
1172 let mut payment_hash = None;
1173 let mut payment_id = None;
1174 let mut fee_paid_msat = None;
1175 read_tlv_fields!(reader, {
1176 (0, payment_preimage, required),
1177 (1, payment_hash, option),
1178 (3, payment_id, option),
1179 (5, fee_paid_msat, option),
1181 if payment_hash.is_none() {
1182 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
1184 Ok(Some(Event::PaymentSent {
1187 payment_hash: payment_hash.unwrap(),
1196 let error_code = Readable::read(reader)?;
1198 let error_data = Readable::read(reader)?;
1199 let mut payment_hash = PaymentHash([0; 32]);
1200 let mut payment_failed_permanently = false;
1201 let mut network_update = None;
1202 let mut all_paths_failed = Some(true);
1203 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1204 let mut short_channel_id = None;
1205 let mut retry = None;
1206 let mut payment_id = None;
1207 read_tlv_fields!(reader, {
1208 (0, payment_hash, required),
1209 (1, network_update, ignorable),
1210 (2, payment_failed_permanently, required),
1211 (3, all_paths_failed, option),
1212 (5, path, vec_type),
1213 (7, short_channel_id, option),
1215 (11, payment_id, option),
1217 Ok(Some(Event::PaymentPathFailed {
1220 payment_failed_permanently,
1222 all_paths_failed: all_paths_failed.unwrap(),
1223 path: path.unwrap(),
1237 let mut outputs = WithoutLength(Vec::new());
1238 read_tlv_fields!(reader, {
1239 (0, outputs, required),
1241 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
1246 let mut payment_hash = PaymentHash([0; 32]);
1247 let mut intercept_id = InterceptId([0; 32]);
1248 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1249 let mut inbound_amount_msat = 0;
1250 let mut expected_outbound_amount_msat = 0;
1251 read_tlv_fields!(reader, {
1252 (0, intercept_id, required),
1253 (2, requested_next_hop_scid, required),
1254 (4, payment_hash, required),
1255 (6, inbound_amount_msat, required),
1256 (8, expected_outbound_amount_msat, required),
1258 let next_scid = match requested_next_hop_scid {
1259 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1261 Ok(Some(Event::HTLCIntercepted {
1263 requested_next_hop_scid: next_scid,
1264 inbound_amount_msat,
1265 expected_outbound_amount_msat,
1271 let mut fee_earned_msat = None;
1272 let mut prev_channel_id = None;
1273 let mut claim_from_onchain_tx = false;
1274 let mut next_channel_id = None;
1275 read_tlv_fields!(reader, {
1276 (0, fee_earned_msat, option),
1277 (1, prev_channel_id, option),
1278 (2, claim_from_onchain_tx, required),
1279 (3, next_channel_id, option),
1281 Ok(Some(Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id }))
1287 let mut channel_id = [0; 32];
1288 let mut reason = None;
1289 let mut user_channel_id_low_opt: Option<u64> = None;
1290 let mut user_channel_id_high_opt: Option<u64> = None;
1291 read_tlv_fields!(reader, {
1292 (0, channel_id, required),
1293 (1, user_channel_id_low_opt, option),
1294 (2, reason, ignorable),
1295 (3, user_channel_id_high_opt, option),
1297 if reason.is_none() { return Ok(None); }
1299 // `user_channel_id` used to be a single u64 value. In order to remain
1300 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1301 // as two separate u64 values.
1302 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1303 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1305 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: reason.unwrap() }))
1311 let mut channel_id = [0; 32];
1312 let mut transaction = Transaction{ version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
1313 read_tlv_fields!(reader, {
1314 (0, channel_id, required),
1315 (2, transaction, required),
1317 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1323 let mut payment_id = PaymentId([0; 32]);
1324 let mut payment_hash = None;
1325 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1326 read_tlv_fields!(reader, {
1327 (0, payment_id, required),
1328 (2, payment_hash, option),
1329 (4, path, vec_type),
1331 Ok(Some(Event::PaymentPathSuccessful {
1334 path: path.unwrap(),
1341 let mut payment_hash = PaymentHash([0; 32]);
1342 let mut payment_id = PaymentId([0; 32]);
1343 read_tlv_fields!(reader, {
1344 (0, payment_id, required),
1345 (2, payment_hash, required),
1347 Ok(Some(Event::PaymentFailed {
1355 // Value 17 is used for `Event::OpenChannelRequest`.
1360 let mut payment_hash = PaymentHash([0; 32]);
1361 let mut purpose = None;
1362 let mut amount_msat = 0;
1363 let mut receiver_node_id = None;
1364 read_tlv_fields!(reader, {
1365 (0, payment_hash, required),
1366 (1, receiver_node_id, option),
1367 (2, purpose, ignorable),
1368 (4, amount_msat, required),
1370 if purpose.is_none() { return Ok(None); }
1371 Ok(Some(Event::PaymentClaimed {
1374 purpose: purpose.unwrap(),
1382 let mut payment_id = PaymentId([0; 32]);
1383 let mut payment_hash = PaymentHash([0; 32]);
1384 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1385 read_tlv_fields!(reader, {
1386 (0, payment_id, required),
1387 (2, payment_hash, required),
1388 (4, path, vec_type),
1390 Ok(Some(Event::ProbeSuccessful {
1393 path: path.unwrap(),
1400 let mut payment_id = PaymentId([0; 32]);
1401 let mut payment_hash = PaymentHash([0; 32]);
1402 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1403 let mut short_channel_id = None;
1404 read_tlv_fields!(reader, {
1405 (0, payment_id, required),
1406 (2, payment_hash, required),
1407 (4, path, vec_type),
1408 (6, short_channel_id, option),
1410 Ok(Some(Event::ProbeFailed {
1413 path: path.unwrap(),
1421 let mut prev_channel_id = [0; 32];
1422 let mut failed_next_destination_opt = None;
1423 read_tlv_fields!(reader, {
1424 (0, prev_channel_id, required),
1425 (2, failed_next_destination_opt, ignorable),
1427 if let Some(failed_next_destination) = failed_next_destination_opt {
1428 Ok(Some(Event::HTLCHandlingFailed {
1430 failed_next_destination,
1433 // If we fail to read a `failed_next_destination` assume it's because
1434 // `MaybeReadable::read` returned `Ok(None)`, though it's also possible we
1435 // were simply missing the field.
1444 let mut channel_id = [0; 32];
1445 let mut user_channel_id: u128 = 0;
1446 let mut counterparty_node_id = OptionDeserWrapper(None);
1447 let mut channel_type = OptionDeserWrapper(None);
1448 read_tlv_fields!(reader, {
1449 (0, channel_id, required),
1450 (2, user_channel_id, required),
1451 (4, counterparty_node_id, required),
1452 (6, channel_type, required),
1455 Ok(Some(Event::ChannelReady {
1458 counterparty_node_id: counterparty_node_id.0.unwrap(),
1459 channel_type: channel_type.0.unwrap()
1464 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1465 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1467 x if x % 2 == 1 => {
1468 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1469 // which prefixes the whole thing with a length BigSize. Because the event is
1470 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1471 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1472 // exactly the number of bytes specified, ignoring them entirely.
1473 let tlv_len: BigSize = Readable::read(reader)?;
1474 FixedLengthReader::new(reader, tlv_len.0)
1475 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1478 _ => Err(msgs::DecodeError::InvalidValue)
1483 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1484 /// broadcast to most peers).
1485 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1486 #[derive(Clone, Debug)]
1487 pub enum MessageSendEvent {
1488 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1489 /// message provided to the given peer.
1491 /// The node_id of the node which should receive this message
1493 /// The message which should be sent.
1494 msg: msgs::AcceptChannel,
1496 /// Used to indicate that we've initiated a channel open and should send the open_channel
1497 /// message provided to the given peer.
1499 /// The node_id of the node which should receive this message
1501 /// The message which should be sent.
1502 msg: msgs::OpenChannel,
1504 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1505 SendFundingCreated {
1506 /// The node_id of the node which should receive this message
1508 /// The message which should be sent.
1509 msg: msgs::FundingCreated,
1511 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1513 /// The node_id of the node which should receive this message
1515 /// The message which should be sent.
1516 msg: msgs::FundingSigned,
1518 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1520 /// The node_id of the node which should receive these message(s)
1522 /// The channel_ready message which should be sent.
1523 msg: msgs::ChannelReady,
1525 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1526 SendAnnouncementSignatures {
1527 /// The node_id of the node which should receive these message(s)
1529 /// The announcement_signatures message which should be sent.
1530 msg: msgs::AnnouncementSignatures,
1532 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1533 /// message should be sent to the peer with the given node_id.
1535 /// The node_id of the node which should receive these message(s)
1537 /// The update messages which should be sent. ALL messages in the struct should be sent!
1538 updates: msgs::CommitmentUpdate,
1540 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1542 /// The node_id of the node which should receive this message
1544 /// The message which should be sent.
1545 msg: msgs::RevokeAndACK,
1547 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1549 /// The node_id of the node which should receive this message
1551 /// The message which should be sent.
1552 msg: msgs::ClosingSigned,
1554 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1556 /// The node_id of the node which should receive this message
1558 /// The message which should be sent.
1559 msg: msgs::Shutdown,
1561 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1562 SendChannelReestablish {
1563 /// The node_id of the node which should receive this message
1565 /// The message which should be sent.
1566 msg: msgs::ChannelReestablish,
1568 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1569 /// initial connection to ensure our peers know about our channels.
1570 SendChannelAnnouncement {
1571 /// The node_id of the node which should receive this message
1573 /// The channel_announcement which should be sent.
1574 msg: msgs::ChannelAnnouncement,
1575 /// The followup channel_update which should be sent.
1576 update_msg: msgs::ChannelUpdate,
1578 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1579 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1581 /// Note that after doing so, you very likely (unless you did so very recently) want to
1582 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1583 /// ensures that any nodes which see our channel_announcement also have a relevant
1584 /// node_announcement, including relevant feature flags which may be important for routing
1585 /// through or to us.
1587 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1588 BroadcastChannelAnnouncement {
1589 /// The channel_announcement which should be sent.
1590 msg: msgs::ChannelAnnouncement,
1591 /// The followup channel_update which should be sent.
1592 update_msg: Option<msgs::ChannelUpdate>,
1594 /// Used to indicate that a channel_update should be broadcast to all peers.
1595 BroadcastChannelUpdate {
1596 /// The channel_update which should be sent.
1597 msg: msgs::ChannelUpdate,
1599 /// Used to indicate that a node_announcement should be broadcast to all peers.
1600 BroadcastNodeAnnouncement {
1601 /// The node_announcement which should be sent.
1602 msg: msgs::NodeAnnouncement,
1604 /// Used to indicate that a channel_update should be sent to a single peer.
1605 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1606 /// private channel and we shouldn't be informing all of our peers of channel parameters.
1608 /// The node_id of the node which should receive this message
1610 /// The channel_update which should be sent.
1611 msg: msgs::ChannelUpdate,
1613 /// Broadcast an error downstream to be handled
1615 /// The node_id of the node which should receive this message
1617 /// The action which should be taken.
1618 action: msgs::ErrorAction
1620 /// Query a peer for channels with funding transaction UTXOs in a block range.
1621 SendChannelRangeQuery {
1622 /// The node_id of this message recipient
1624 /// The query_channel_range which should be sent.
1625 msg: msgs::QueryChannelRange,
1627 /// Request routing gossip messages from a peer for a list of channels identified by
1628 /// their short_channel_ids.
1630 /// The node_id of this message recipient
1632 /// The query_short_channel_ids which should be sent.
1633 msg: msgs::QueryShortChannelIds,
1635 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1636 /// emitted during processing of the query.
1637 SendReplyChannelRange {
1638 /// The node_id of this message recipient
1640 /// The reply_channel_range which should be sent.
1641 msg: msgs::ReplyChannelRange,
1643 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1644 /// enable receiving gossip messages from the peer.
1645 SendGossipTimestampFilter {
1646 /// The node_id of this message recipient
1648 /// The gossip_timestamp_filter which should be sent.
1649 msg: msgs::GossipTimestampFilter,
1653 /// A trait indicating an object may generate message send events
1654 pub trait MessageSendEventsProvider {
1655 /// Gets the list of pending events which were generated by previous actions, clearing the list
1657 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1660 /// A trait indicating an object may generate onion messages to send
1661 pub trait OnionMessageProvider {
1662 /// Gets the next pending onion message for the peer with the given node id.
1663 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<msgs::OnionMessage>;
1666 /// A trait indicating an object may generate events.
1668 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1670 /// Implementations of this trait may also feature an async version of event handling, as shown with
1671 /// [`ChannelManager::process_pending_events_async`] and
1672 /// [`ChainMonitor::process_pending_events_async`].
1676 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1677 /// event since the last invocation.
1679 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1680 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1681 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1682 /// relevant changes to disk *before* returning.
1684 /// Further, because an application may crash between an [`Event`] being handled and the
1685 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1686 /// effect, [`Event`]s may be replayed.
1688 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1689 /// consult the provider's documentation on the implication of processing events and how a handler
1690 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1691 /// [`ChainMonitor::process_pending_events`]).
1693 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1696 /// [`process_pending_events`]: Self::process_pending_events
1697 /// [`handle_event`]: EventHandler::handle_event
1698 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1699 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1700 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
1701 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
1702 pub trait EventsProvider {
1703 /// Processes any events generated since the last call using the given event handler.
1705 /// See the trait-level documentation for requirements.
1706 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1709 /// A trait implemented for objects handling events from [`EventsProvider`].
1711 /// An async variation also exists for implementations of [`EventsProvider`] that support async
1712 /// event handling. The async event handler should satisfy the generic bounds: `F:
1713 /// core::future::Future, H: Fn(Event) -> F`.
1714 pub trait EventHandler {
1715 /// Handles the given [`Event`].
1717 /// See [`EventsProvider`] for details that must be considered when implementing this method.
1718 fn handle_event(&self, event: Event);
1721 impl<F> EventHandler for F where F: Fn(Event) {
1722 fn handle_event(&self, event: Event) {
1727 impl<T: EventHandler> EventHandler for Arc<T> {
1728 fn handle_event(&self, event: Event) {
1729 self.deref().handle_event(event)