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::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, RequiredWrapper, WithoutLength};
27 use crate::routing::router::{RouteHop, RouteParameters};
29 use bitcoin::{PackedLockTime, Transaction};
31 use bitcoin::{OutPoint, Txid, TxIn, TxOut, Witness};
32 use bitcoin::blockdata::script::Script;
33 use bitcoin::hashes::Hash;
34 use bitcoin::hashes::sha256::Hash as Sha256;
35 use bitcoin::secp256k1::PublicKey;
37 use bitcoin::secp256k1::{self, Secp256k1};
39 use bitcoin::secp256k1::ecdsa::Signature;
41 use crate::prelude::*;
42 use core::time::Duration;
46 /// Some information provided on receipt of payment depends on whether the payment received is a
47 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
48 #[derive(Clone, Debug, PartialEq, Eq)]
49 pub enum PaymentPurpose {
50 /// Information for receiving a payment that we generated an invoice for.
52 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
53 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
54 /// [`ChannelManager::claim_funds`].
56 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
57 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
58 payment_preimage: Option<PaymentPreimage>,
59 /// The "payment secret". This authenticates the sender to the recipient, preventing a
60 /// number of deanonymization attacks during the routing process.
61 /// It is provided here for your reference, however its accuracy is enforced directly by
62 /// [`ChannelManager`] using the values you previously provided to
63 /// [`ChannelManager::create_inbound_payment`] or
64 /// [`ChannelManager::create_inbound_payment_for_hash`].
66 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
67 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
68 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
69 payment_secret: PaymentSecret,
71 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
72 /// (the payee) providing a preimage.
73 SpontaneousPayment(PaymentPreimage),
76 impl_writeable_tlv_based_enum!(PaymentPurpose,
77 (0, InvoicePayment) => {
78 (0, payment_preimage, option),
79 (2, payment_secret, required),
81 (2, SpontaneousPayment)
84 #[derive(Clone, Debug, PartialEq, Eq)]
85 /// The reason the channel was closed. See individual variants more details.
86 pub enum ClosureReason {
87 /// Closure generated from receiving a peer error message.
89 /// Our counterparty may have broadcasted their latest commitment state, and we have
91 CounterpartyForceClosed {
92 /// The error which the peer sent us.
94 /// The string should be sanitized before it is used (e.g emitted to logs
95 /// or printed to stdout). Otherwise, a well crafted error message may exploit
96 /// a security vulnerability in the terminal emulator or the logging subsystem.
99 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
101 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
103 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
104 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
105 //TODO: split between CounterpartyInitiated/LocallyInitiated
107 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
108 /// commitment transaction came from our counterparty, but it may also have come from
109 /// a copy of our own `ChannelMonitor`.
110 CommitmentTxConfirmed,
111 /// The funding transaction failed to confirm in a timely manner on an inbound channel.
113 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
115 /// A developer-readable error message which we generated.
118 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
119 /// forget the channel entirely - we can attempt again if the peer reconnects.
121 /// This includes cases where we restarted prior to funding completion, including prior to the
122 /// initial [`ChannelMonitor`] persistence completing.
124 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
125 /// peer because of mutual incompatibility between us and our channel counterparty.
127 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
129 /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
130 /// the [`ChannelManager`] deserialized.
132 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
133 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
134 OutdatedChannelManager
137 impl core::fmt::Display for ClosureReason {
138 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
139 f.write_str("Channel closed because ")?;
141 ClosureReason::CounterpartyForceClosed { peer_msg } => {
142 f.write_str("counterparty force-closed with message ")?;
143 f.write_str(&peer_msg)
145 ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
146 ClosureReason::CooperativeClosure => f.write_str("the channel was cooperatively closed"),
147 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
148 ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
149 ClosureReason::ProcessingError { err } => {
150 f.write_str("of an exception: ")?;
153 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
154 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
159 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
160 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
161 (1, FundingTimedOut) => {},
162 (2, HolderForceClosed) => {},
163 (6, CommitmentTxConfirmed) => {},
164 (4, CooperativeClosure) => {},
165 (8, ProcessingError) => { (1, err, required) },
166 (10, DisconnectedPeer) => {},
167 (12, OutdatedChannelManager) => {},
170 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
171 #[derive(Clone, Debug, PartialEq, Eq)]
172 pub enum HTLCDestination {
173 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
174 /// there is insufficient capacity in our outbound channel.
176 /// The `node_id` of the next node. For backwards compatibility, this field is
177 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
178 /// counterparty node information.
179 node_id: Option<PublicKey>,
180 /// The outgoing `channel_id` between us and the next node.
181 channel_id: [u8; 32],
183 /// Scenario where we are unsure of the next node to forward the HTLC to.
185 /// Short channel id we are requesting to forward an HTLC to.
186 requested_forward_scid: u64,
188 /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
191 /// Short channel id we are requesting to forward an HTLC to.
192 requested_forward_scid: u64
194 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
195 /// but is invalid for some reason, so we reject it.
197 /// Some of the reasons may include:
199 /// * Expected MPP amount to claim does not equal HTLC total
200 /// * Claimable amount does not match expected amount
202 /// The payment hash of the payment we attempted to process.
203 payment_hash: PaymentHash
207 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
208 (0, NextHopChannel) => {
209 (0, node_id, required),
210 (2, channel_id, required),
212 (1, InvalidForward) => {
213 (0, requested_forward_scid, required),
215 (2, UnknownNextHop) => {
216 (0, requested_forward_scid, required),
218 (4, FailedPayment) => {
219 (0, payment_hash, required),
224 /// A descriptor used to sign for a commitment transaction's anchor output.
225 #[derive(Clone, Debug)]
226 pub struct AnchorDescriptor {
227 /// A unique identifier used along with `channel_value_satoshis` to re-derive the
228 /// [`InMemorySigner`] required to sign `input`.
230 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
231 pub channel_keys_id: [u8; 32],
232 /// The value in satoshis of the channel we're attempting to spend the anchor output of. This is
233 /// used along with `channel_keys_id` to re-derive the [`InMemorySigner`] required to sign
236 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
237 pub channel_value_satoshis: u64,
238 /// The transaction input's outpoint corresponding to the commitment transaction's anchor
240 pub outpoint: OutPoint,
244 /// A descriptor used to sign for a commitment transaction's HTLC output.
245 #[derive(Clone, Debug)]
246 pub struct HTLCDescriptor {
247 /// A unique identifier used along with `channel_value_satoshis` to re-derive the
248 /// [`InMemorySigner`] required to sign `input`.
250 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
251 pub channel_keys_id: [u8; 32],
252 /// The value in satoshis of the channel we're attempting to spend the anchor output of. This is
253 /// used along with `channel_keys_id` to re-derive the [`InMemorySigner`] required to sign
256 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
257 pub channel_value_satoshis: u64,
258 /// The necessary channel parameters that need to be provided to the re-derived
259 /// [`InMemorySigner`] through [`BaseSign::provide_channel_parameters`].
261 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
262 /// [`BaseSign::provide_channel_parameters`]: crate::chain::keysinterface::BaseSign::provide_channel_parameters
263 pub channel_parameters: ChannelTransactionParameters,
264 /// The txid of the commitment transaction in which the HTLC output lives.
265 pub commitment_txid: Txid,
266 /// The number of the commitment transaction in which the HTLC output lives.
267 pub per_commitment_number: u64,
268 /// The details of the HTLC as it appears in the commitment transaction.
269 pub htlc: HTLCOutputInCommitment,
270 /// The preimage, if `Some`, to claim the HTLC output with. If `None`, the timeout path must be
272 pub preimage: Option<PaymentPreimage>,
273 /// The counterparty's signature required to spend the HTLC output.
274 pub counterparty_sig: Signature
278 impl HTLCDescriptor {
279 /// Returns the unsigned transaction input spending the HTLC output in the commitment
281 pub fn unsigned_tx_input(&self) -> TxIn {
282 chan_utils::build_htlc_input(&self.commitment_txid, &self.htlc, true /* opt_anchors */)
285 /// Returns the delayed output created as a result of spending the HTLC output in the commitment
287 pub fn tx_output<C: secp256k1::Signing + secp256k1::Verification>(
288 &self, per_commitment_point: &PublicKey, secp: &Secp256k1<C>
290 let channel_params = self.channel_parameters.as_holder_broadcastable();
291 let broadcaster_keys = channel_params.broadcaster_pubkeys();
292 let counterparty_keys = channel_params.countersignatory_pubkeys();
293 let broadcaster_delayed_key = chan_utils::derive_public_key(
294 secp, per_commitment_point, &broadcaster_keys.delayed_payment_basepoint
296 let counterparty_revocation_key = chan_utils::derive_public_revocation_key(
297 secp, per_commitment_point, &counterparty_keys.revocation_basepoint
299 chan_utils::build_htlc_output(
300 0 /* feerate_per_kw */, channel_params.contest_delay(), &self.htlc, true /* opt_anchors */,
301 false /* use_non_zero_fee_anchors */, &broadcaster_delayed_key, &counterparty_revocation_key
305 /// Returns the witness script of the HTLC output in the commitment transaction.
306 pub fn witness_script<C: secp256k1::Signing + secp256k1::Verification>(
307 &self, per_commitment_point: &PublicKey, secp: &Secp256k1<C>
309 let channel_params = self.channel_parameters.as_holder_broadcastable();
310 let broadcaster_keys = channel_params.broadcaster_pubkeys();
311 let counterparty_keys = channel_params.countersignatory_pubkeys();
312 let broadcaster_htlc_key = chan_utils::derive_public_key(
313 secp, per_commitment_point, &broadcaster_keys.htlc_basepoint
315 let counterparty_htlc_key = chan_utils::derive_public_key(
316 secp, per_commitment_point, &counterparty_keys.htlc_basepoint
318 let counterparty_revocation_key = chan_utils::derive_public_revocation_key(
319 secp, per_commitment_point, &counterparty_keys.revocation_basepoint
321 chan_utils::get_htlc_redeemscript_with_explicit_keys(
322 &self.htlc, true /* opt_anchors */, &broadcaster_htlc_key, &counterparty_htlc_key,
323 &counterparty_revocation_key,
327 /// Returns the fully signed witness required to spend the HTLC output in the commitment
329 pub fn tx_input_witness(&self, signature: &Signature, witness_script: &Script) -> Witness {
330 chan_utils::build_htlc_input_witness(
331 signature, &self.counterparty_sig, &self.preimage, witness_script, true /* opt_anchors */
337 /// Represents the different types of transactions, originating from LDK, to be bumped.
338 #[derive(Clone, Debug)]
339 pub enum BumpTransactionEvent {
340 /// Indicates that a channel featuring anchor outputs is to be closed by broadcasting the local
341 /// commitment transaction. Since commitment transactions have a static feerate pre-agreed upon,
342 /// they may need additional fees to be attached through a child transaction using the popular
343 /// [Child-Pays-For-Parent](https://bitcoinops.org/en/topics/cpfp) fee bumping technique. This
344 /// child transaction must include the anchor input described within `anchor_descriptor` along
345 /// with additional inputs to meet the target feerate. Failure to meet the target feerate
346 /// decreases the confirmation odds of the transaction package (which includes the commitment
347 /// and child anchor transactions), possibly resulting in a loss of funds. Once the transaction
348 /// is constructed, it must be fully signed for and broadcast by the consumer of the event
349 /// along with the `commitment_tx` enclosed. Note that the `commitment_tx` must always be
350 /// broadcast first, as the child anchor transaction depends on it.
352 /// The consumer should be able to sign for any of the additional inputs included within the
353 /// child anchor transaction. To sign its anchor input, an [`InMemorySigner`] should be
354 /// re-derived through [`KeysManager::derive_channel_keys`] with the help of
355 /// [`AnchorDescriptor::channel_keys_id`] and [`AnchorDescriptor::channel_value_satoshis`]. The
356 /// anchor input signature can be computed with [`BaseSign::sign_holder_anchor_input`],
357 /// which can then be provided to [`build_anchor_input_witness`] along with the `funding_pubkey`
358 /// to obtain the full witness required to spend.
360 /// It is possible to receive more than one instance of this event if a valid child anchor
361 /// transaction is never broadcast or is but not with a sufficient fee to be mined. Care should
362 /// be taken by the consumer of the event to ensure any future iterations of the child anchor
363 /// transaction adhere to the [Replace-By-Fee
364 /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
365 /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
366 /// these events is not user-controlled, users may ignore/drop the event if they are no longer
367 /// able to commit external confirmed funds to the child anchor transaction.
369 /// The set of `pending_htlcs` on the commitment transaction to be broadcast can be inspected to
370 /// determine whether a significant portion of the channel's funds are allocated to HTLCs,
371 /// enabling users to make their own decisions regarding the importance of the commitment
372 /// transaction's confirmation. Note that this is not required, but simply exists as an option
373 /// for users to override LDK's behavior. On commitments with no HTLCs (indicated by those with
374 /// an empty `pending_htlcs`), confirmation of the commitment transaction can be considered to
377 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
378 /// [`KeysManager::derive_channel_keys`]: crate::chain::keysinterface::KeysManager::derive_channel_keys
379 /// [`BaseSign::sign_holder_anchor_input`]: crate::chain::keysinterface::BaseSign::sign_holder_anchor_input
380 /// [`build_anchor_input_witness`]: crate::ln::chan_utils::build_anchor_input_witness
382 /// The target feerate that the transaction package, which consists of the commitment
383 /// transaction and the to-be-crafted child anchor transaction, must meet.
384 package_target_feerate_sat_per_1000_weight: u32,
385 /// The channel's commitment transaction to bump the fee of. This transaction should be
386 /// broadcast along with the anchor transaction constructed as a result of consuming this
388 commitment_tx: Transaction,
389 /// The absolute fee in satoshis of the commitment transaction. This can be used along the
390 /// with weight of the commitment transaction to determine its feerate.
391 commitment_tx_fee_satoshis: u64,
392 /// The descriptor to sign the anchor input of the anchor transaction constructed as a
393 /// result of consuming this event.
394 anchor_descriptor: AnchorDescriptor,
395 /// The set of pending HTLCs on the commitment transaction that need to be resolved once the
396 /// commitment transaction confirms.
397 pending_htlcs: Vec<HTLCOutputInCommitment>,
399 /// Indicates that a channel featuring anchor outputs has unilaterally closed on-chain by a
400 /// holder commitment transaction and its HTLC(s) need to be resolved on-chain. With the
401 /// zero-HTLC-transaction-fee variant of anchor outputs, the pre-signed HTLC
402 /// transactions have a zero fee, thus requiring additional inputs and/or outputs to be attached
403 /// for a timely confirmation within the chain. These additional inputs and/or outputs must be
404 /// appended to the resulting HTLC transaction to meet the target feerate. Failure to meet the
405 /// target feerate decreases the confirmation odds of the transaction, possibly resulting in a
406 /// loss of funds. Once the transaction meets the target feerate, it must be signed for and
407 /// broadcast by the consumer of the event.
409 /// The consumer should be able to sign for any of the non-HTLC inputs added to the resulting
410 /// HTLC transaction. To sign HTLC inputs, an [`InMemorySigner`] should be re-derived through
411 /// [`KeysManager::derive_channel_keys`] with the help of `channel_keys_id` and
412 /// `channel_value_satoshis`. Each HTLC input's signature can be computed with
413 /// [`BaseSign::sign_holder_htlc_transaction`], which can then be provided to
414 /// [`HTLCDescriptor::tx_input_witness`] to obtain the fully signed witness required to spend.
416 /// It is possible to receive more than one instance of this event if a valid HTLC transaction
417 /// is never broadcast or is but not with a sufficient fee to be mined. Care should be taken by
418 /// the consumer of the event to ensure any future iterations of the HTLC transaction adhere to
419 /// the [Replace-By-Fee
420 /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
421 /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
422 /// these events is not user-controlled, users may ignore/drop the event if either they are no
423 /// longer able to commit external confirmed funds to the HTLC transaction or the fee committed
424 /// to the HTLC transaction is greater in value than the HTLCs being claimed.
426 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
427 /// [`KeysManager::derive_channel_keys`]: crate::chain::keysinterface::KeysManager::derive_channel_keys
428 /// [`BaseSign::sign_holder_htlc_transaction`]: crate::chain::keysinterface::BaseSign::sign_holder_htlc_transaction
429 /// [`HTLCDescriptor::tx_input_witness`]: HTLCDescriptor::tx_input_witness
431 target_feerate_sat_per_1000_weight: u32,
432 htlc_descriptors: Vec<HTLCDescriptor>,
436 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
437 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
438 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
439 /// intercepts in upcoming work.
440 enum InterceptNextHop {
442 requested_next_hop_scid: u64,
446 impl_writeable_tlv_based_enum!(InterceptNextHop,
448 (0, requested_next_hop_scid, required),
452 /// An Event which you should probably take some action in response to.
454 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
455 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
456 /// written as it makes no sense to respond to it after reconnecting to peers).
457 #[derive(Clone, Debug, PartialEq, Eq)]
459 /// Used to indicate that the client should generate a funding transaction with the given
460 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
461 /// Generated in [`ChannelManager`] message handling.
462 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
463 /// counterparty can steal your funds!
465 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
466 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
467 FundingGenerationReady {
468 /// The random channel_id we picked which you'll need to pass into
469 /// [`ChannelManager::funding_transaction_generated`].
471 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
472 temporary_channel_id: [u8; 32],
473 /// The counterparty's node_id, which you'll need to pass back into
474 /// [`ChannelManager::funding_transaction_generated`].
476 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
477 counterparty_node_id: PublicKey,
478 /// The value, in satoshis, that the output should have.
479 channel_value_satoshis: u64,
480 /// The script which should be used in the transaction output.
481 output_script: Script,
482 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or a
483 /// random value for an inbound channel. This may be zero for objects serialized with LDK
484 /// versions prior to 0.0.113.
486 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
487 user_channel_id: u128,
489 /// Indicates that we've been offered a payment and it needs to be claimed via calling
490 /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
492 /// Note that if the preimage is not known, you should call
493 /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
494 /// to free up resources for this HTLC and avoid network congestion.
495 /// If you fail to call either [`ChannelManager::claim_funds`], [`ChannelManager::fail_htlc_backwards`],
496 /// or [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will be
497 /// automatically failed.
500 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
501 /// `PaymentClaimable` events may be generated for the same payment.
504 /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
506 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
507 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
508 /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
510 /// The node that will receive the payment after it has been claimed.
511 /// This is useful to identify payments received via [phantom nodes].
512 /// This field will always be filled in when the event was generated by LDK versions
513 /// 0.0.113 and above.
515 /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
516 receiver_node_id: Option<PublicKey>,
517 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
518 /// not stop you from registering duplicate payment hashes for inbound payments.
519 payment_hash: PaymentHash,
520 /// The value, in thousandths of a satoshi, that this payment is for.
522 /// Information for claiming this received payment, based on whether the purpose of the
523 /// payment is to pay an invoice or to send a spontaneous payment.
524 purpose: PaymentPurpose,
525 /// The `channel_id` indicating over which channel we received the payment.
526 via_channel_id: Option<[u8; 32]>,
527 /// The `user_channel_id` indicating over which channel we received the payment.
528 via_user_channel_id: Option<u128>,
530 /// Indicates a payment has been claimed and we've received money!
532 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
533 /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
534 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
535 /// [`Event::PaymentClaimable`] event.
538 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
539 /// `PaymentClaimable` events may be generated for the same payment. If you then call
540 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
541 /// multiple `PaymentClaimed` events.
543 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
545 /// The node that received the payment.
546 /// This is useful to identify payments which were received via [phantom nodes].
547 /// This field will always be filled in when the event was generated by LDK versions
548 /// 0.0.113 and above.
550 /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
551 receiver_node_id: Option<PublicKey>,
552 /// The payment hash of the claimed payment. Note that LDK will not stop you from
553 /// registering duplicate payment hashes for inbound payments.
554 payment_hash: PaymentHash,
555 /// The value, in thousandths of a satoshi, that this payment is for.
557 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
558 /// spontaneous payment.
559 purpose: PaymentPurpose,
561 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
562 /// and we got back the payment preimage for it).
564 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
565 /// event. In this situation, you SHOULD treat this payment as having succeeded.
567 /// The id returned by [`ChannelManager::send_payment`].
569 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
570 payment_id: Option<PaymentId>,
571 /// The preimage to the hash given to ChannelManager::send_payment.
572 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
573 /// store it somehow!
574 payment_preimage: PaymentPreimage,
575 /// The hash that was given to [`ChannelManager::send_payment`].
577 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
578 payment_hash: PaymentHash,
579 /// The total fee which was spent at intermediate hops in this payment, across all paths.
581 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
582 /// overpayment to the recipient node.
584 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
585 /// overstate the amount paid, though this is unlikely.
587 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
588 fee_paid_msat: Option<u64>,
590 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
591 /// provide failure information for each MPP part in the payment.
593 /// This event is provided once there are no further pending HTLCs for the payment and the
594 /// payment is no longer retryable, due either to the [`Retry`] provided or
595 /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
597 /// [`Retry`]: crate::ln::channelmanager::Retry
598 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
600 /// The id returned by [`ChannelManager::send_payment`] and used with
601 /// [`ChannelManager::abandon_payment`].
603 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
604 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
605 payment_id: PaymentId,
606 /// The hash that was given to [`ChannelManager::send_payment`].
608 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
609 payment_hash: PaymentHash,
611 /// Indicates that a path for an outbound payment was successful.
613 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
614 /// [`Event::PaymentSent`] for obtaining the payment preimage.
615 PaymentPathSuccessful {
616 /// The id returned by [`ChannelManager::send_payment`].
618 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
619 payment_id: PaymentId,
620 /// The hash that was given to [`ChannelManager::send_payment`].
622 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
623 payment_hash: Option<PaymentHash>,
624 /// The payment path that was successful.
626 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
629 /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
632 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
633 /// [`Event::PaymentFailed`].
635 /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
638 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
640 /// The id returned by [`ChannelManager::send_payment`] and used with
641 /// [`ChannelManager::abandon_payment`].
643 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
644 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
645 payment_id: Option<PaymentId>,
646 /// The hash that was given to [`ChannelManager::send_payment`].
648 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
649 payment_hash: PaymentHash,
650 /// Indicates the payment was rejected for some reason by the recipient. This implies that
651 /// the payment has failed, not just the route in question. If this is not set, the payment may
652 /// be retried via a different route.
653 payment_failed_permanently: bool,
654 /// Any failure information conveyed via the Onion return packet by a node along the failed
657 /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into
658 /// account the update.
660 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
661 network_update: Option<NetworkUpdate>,
662 /// The payment path that failed.
664 /// The channel responsible for the failed payment path.
666 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
667 /// may not refer to a channel in the public network graph. These aliases may also collide
668 /// with channels in the public network graph.
670 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
671 /// retried. May be `None` for older [`Event`] serializations.
672 short_channel_id: Option<u64>,
673 /// Parameters used by LDK to compute a new [`Route`] when retrying the failed payment path.
675 /// [`Route`]: crate::routing::router::Route
676 retry: Option<RouteParameters>,
678 error_code: Option<u16>,
680 error_data: Option<Vec<u8>>,
682 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
684 /// The id returned by [`ChannelManager::send_probe`].
686 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
687 payment_id: PaymentId,
688 /// The hash generated by [`ChannelManager::send_probe`].
690 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
691 payment_hash: PaymentHash,
692 /// The payment path that was successful.
695 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
697 /// The id returned by [`ChannelManager::send_probe`].
699 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
700 payment_id: PaymentId,
701 /// The hash generated by [`ChannelManager::send_probe`].
703 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
704 payment_hash: PaymentHash,
705 /// The payment path that failed.
707 /// The channel responsible for the failed probe.
709 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
710 /// may not refer to a channel in the public network graph. These aliases may also collide
711 /// with channels in the public network graph.
712 short_channel_id: Option<u64>,
714 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
715 /// a time in the future.
717 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
718 PendingHTLCsForwardable {
719 /// The minimum amount of time that should be waited prior to calling
720 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
721 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
722 /// now + 5*time_forwardable).
723 time_forwardable: Duration,
725 /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
726 /// you've encoded an intercept scid in the receiver's invoice route hints using
727 /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
729 /// [`ChannelManager::forward_intercepted_htlc`] or
730 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
731 /// their docs for more information.
733 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
734 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
735 /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
736 /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
738 /// An id to help LDK identify which HTLC is being forwarded or failed.
739 intercept_id: InterceptId,
740 /// The fake scid that was programmed as the next hop's scid, generated using
741 /// [`ChannelManager::get_intercept_scid`].
743 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
744 requested_next_hop_scid: u64,
745 /// The payment hash used for this HTLC.
746 payment_hash: PaymentHash,
747 /// How many msats were received on the inbound edge of this HTLC.
748 inbound_amount_msat: u64,
749 /// How many msats the payer intended to route to the next node. Depending on the reason you are
750 /// intercepting this payment, you might take a fee by forwarding less than this amount.
752 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
753 /// check that whatever fee you want has been included here or subtract it as required. Further,
754 /// LDK will not stop you from forwarding more than you received.
755 expected_outbound_amount_msat: u64,
757 /// Used to indicate that an output which you should know how to spend was confirmed on chain
758 /// and is now spendable.
759 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
760 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
761 /// somewhere and spend them when you create on-chain transactions.
763 /// The outputs which you should store as spendable by you.
764 outputs: Vec<SpendableOutputDescriptor>,
766 /// This event is generated when a payment has been successfully forwarded through us and a
767 /// forwarding fee earned.
769 /// The incoming channel between the previous node and us. This is only `None` for events
770 /// generated or serialized by versions prior to 0.0.107.
771 prev_channel_id: Option<[u8; 32]>,
772 /// The outgoing channel between the next node and us. This is only `None` for events
773 /// generated or serialized by versions prior to 0.0.107.
774 next_channel_id: Option<[u8; 32]>,
775 /// The fee, in milli-satoshis, which was earned as a result of the payment.
777 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
778 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
779 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
780 /// claimed the full value in millisatoshis from the source. In this case,
781 /// `claim_from_onchain_tx` will be set.
783 /// If the channel which sent us the payment has been force-closed, we will claim the funds
784 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
785 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
786 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
788 fee_earned_msat: Option<u64>,
789 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
791 claim_from_onchain_tx: bool,
793 /// Used to indicate that a channel with the given `channel_id` is ready to
794 /// be used. This event is emitted either when the funding transaction has been confirmed
795 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
798 /// The channel_id of the channel that is ready.
799 channel_id: [u8; 32],
800 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
801 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
802 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
803 /// `user_channel_id` will be randomized for an inbound channel.
805 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
806 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
807 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
808 user_channel_id: u128,
809 /// The node_id of the channel counterparty.
810 counterparty_node_id: PublicKey,
811 /// The features that this channel will operate with.
812 channel_type: ChannelTypeFeatures,
814 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
815 /// process of closure.
817 /// The channel_id of the channel which has been closed. Note that on-chain transactions
818 /// resolving the channel are likely still awaiting confirmation.
819 channel_id: [u8; 32],
820 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
821 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
822 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
823 /// `user_channel_id` will be randomized for inbound channels.
824 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
825 /// zero for objects serialized with LDK versions prior to 0.0.102.
827 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
828 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
829 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
830 user_channel_id: u128,
831 /// The reason the channel was closed.
832 reason: ClosureReason
834 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
835 /// inputs for another purpose.
837 /// The channel_id of the channel which has been closed.
838 channel_id: [u8; 32],
839 /// The full transaction received from the user
840 transaction: Transaction
842 /// Indicates a request to open a new channel by a peer.
844 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the
845 /// request, call [`ChannelManager::force_close_without_broadcasting_txn`].
847 /// The event is only triggered when a new open channel request is received and the
848 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
850 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
851 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
852 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
854 /// The temporary channel ID of the channel requested to be opened.
856 /// When responding to the request, the `temporary_channel_id` should be passed
857 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
858 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
860 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
861 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
862 temporary_channel_id: [u8; 32],
863 /// The node_id of the counterparty requesting to open the channel.
865 /// When responding to the request, the `counterparty_node_id` should be passed
866 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
867 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
870 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
871 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
872 counterparty_node_id: PublicKey,
873 /// The channel value of the requested channel.
874 funding_satoshis: u64,
875 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
877 /// The features that this channel will operate with. If you reject the channel, a
878 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
881 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
882 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
885 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
886 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
887 /// 0.0.107. Channels setting this type also need to get manually accepted via
888 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
889 /// or will be rejected otherwise.
891 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
892 channel_type: ChannelTypeFeatures,
894 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
897 /// Some scenarios where this event may be sent include:
898 /// * Insufficient capacity in the outbound channel
899 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
900 /// * When an unknown SCID is requested for forwarding a payment.
901 /// * Claiming an amount for an MPP payment that exceeds the HTLC total
902 /// * The HTLC has timed out
904 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
905 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
907 /// The channel over which the HTLC was received.
908 prev_channel_id: [u8; 32],
909 /// Destination of the HTLC that failed to be processed.
910 failed_next_destination: HTLCDestination,
913 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
914 /// requires confirmed external funds to be readily available to spend.
916 /// LDK does not currently generate this event. It is limited to the scope of channels with
917 /// anchor outputs, which will be introduced in a future release.
918 BumpTransaction(BumpTransactionEvent),
921 impl Writeable for Event {
922 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
924 &Event::FundingGenerationReady { .. } => {
926 // We never write out FundingGenerationReady events as, upon disconnection, peers
927 // drop any channels which have not yet exchanged funding_signed.
929 &Event::PaymentClaimable { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id } => {
931 let mut payment_secret = None;
932 let payment_preimage;
934 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
935 payment_secret = Some(secret);
936 payment_preimage = *preimage;
938 PaymentPurpose::SpontaneousPayment(preimage) => {
939 payment_preimage = Some(*preimage);
942 write_tlv_fields!(writer, {
943 (0, payment_hash, required),
944 (1, receiver_node_id, option),
945 (2, payment_secret, option),
946 (3, via_channel_id, option),
947 (4, amount_msat, required),
948 (5, via_user_channel_id, option),
949 (6, 0u64, required), // user_payment_id required for compatibility with 0.0.103 and earlier
950 (8, payment_preimage, option),
953 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
955 write_tlv_fields!(writer, {
956 (0, payment_preimage, required),
957 (1, payment_hash, required),
958 (3, payment_id, option),
959 (5, fee_paid_msat, option),
962 &Event::PaymentPathFailed {
963 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update,
964 ref path, ref short_channel_id, ref retry,
972 error_code.write(writer)?;
974 error_data.write(writer)?;
975 write_tlv_fields!(writer, {
976 (0, payment_hash, required),
977 (1, network_update, option),
978 (2, payment_failed_permanently, required),
979 (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
980 (5, *path, vec_type),
981 (7, short_channel_id, option),
983 (11, payment_id, option),
986 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
988 // Note that we now ignore these on the read end as we'll re-generate them in
989 // ChannelManager, we write them here only for backwards compatibility.
991 &Event::SpendableOutputs { ref outputs } => {
993 write_tlv_fields!(writer, {
994 (0, WithoutLength(outputs), required),
997 &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
999 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1000 write_tlv_fields!(writer, {
1001 (0, intercept_id, required),
1002 (2, intercept_scid, required),
1003 (4, payment_hash, required),
1004 (6, inbound_amount_msat, required),
1005 (8, expected_outbound_amount_msat, required),
1008 &Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
1010 write_tlv_fields!(writer, {
1011 (0, fee_earned_msat, option),
1012 (1, prev_channel_id, option),
1013 (2, claim_from_onchain_tx, required),
1014 (3, next_channel_id, option),
1017 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
1019 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1020 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1021 // separate u64 values.
1022 let user_channel_id_low = *user_channel_id as u64;
1023 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1024 write_tlv_fields!(writer, {
1025 (0, channel_id, required),
1026 (1, user_channel_id_low, required),
1027 (2, reason, required),
1028 (3, user_channel_id_high, required),
1031 &Event::DiscardFunding { ref channel_id, ref transaction } => {
1032 11u8.write(writer)?;
1033 write_tlv_fields!(writer, {
1034 (0, channel_id, required),
1035 (2, transaction, required)
1038 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1039 13u8.write(writer)?;
1040 write_tlv_fields!(writer, {
1041 (0, payment_id, required),
1042 (2, payment_hash, option),
1043 (4, *path, vec_type)
1046 &Event::PaymentFailed { ref payment_id, ref payment_hash } => {
1047 15u8.write(writer)?;
1048 write_tlv_fields!(writer, {
1049 (0, payment_id, required),
1050 (2, payment_hash, required),
1053 &Event::OpenChannelRequest { .. } => {
1054 17u8.write(writer)?;
1055 // We never write the OpenChannelRequest events as, upon disconnection, peers
1056 // drop any channels which have not yet exchanged funding_signed.
1058 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id } => {
1059 19u8.write(writer)?;
1060 write_tlv_fields!(writer, {
1061 (0, payment_hash, required),
1062 (1, receiver_node_id, option),
1063 (2, purpose, required),
1064 (4, amount_msat, required),
1067 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1068 21u8.write(writer)?;
1069 write_tlv_fields!(writer, {
1070 (0, payment_id, required),
1071 (2, payment_hash, required),
1072 (4, *path, vec_type)
1075 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1076 23u8.write(writer)?;
1077 write_tlv_fields!(writer, {
1078 (0, payment_id, required),
1079 (2, payment_hash, required),
1080 (4, *path, vec_type),
1081 (6, short_channel_id, option),
1084 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1085 25u8.write(writer)?;
1086 write_tlv_fields!(writer, {
1087 (0, prev_channel_id, required),
1088 (2, failed_next_destination, required),
1092 &Event::BumpTransaction(ref event)=> {
1093 27u8.write(writer)?;
1095 // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1096 // upon restarting anyway if they remain unresolved.
1097 BumpTransactionEvent::ChannelClose { .. } => {}
1098 BumpTransactionEvent::HTLCResolution { .. } => {}
1100 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1102 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1103 29u8.write(writer)?;
1104 write_tlv_fields!(writer, {
1105 (0, channel_id, required),
1106 (2, user_channel_id, required),
1107 (4, counterparty_node_id, required),
1108 (6, channel_type, required),
1111 // Note that, going forward, all new events must only write data inside of
1112 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1113 // data via `write_tlv_fields`.
1118 impl MaybeReadable for Event {
1119 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1120 match Readable::read(reader)? {
1121 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
1122 // unlike all other events, thus we return immediately here.
1126 let mut payment_hash = PaymentHash([0; 32]);
1127 let mut payment_preimage = None;
1128 let mut payment_secret = None;
1129 let mut amount_msat = 0;
1130 let mut receiver_node_id = None;
1131 let mut _user_payment_id = None::<u64>; // For compatibility with 0.0.103 and earlier
1132 let mut via_channel_id = None;
1133 let mut via_user_channel_id = None;
1134 read_tlv_fields!(reader, {
1135 (0, payment_hash, required),
1136 (1, receiver_node_id, option),
1137 (2, payment_secret, option),
1138 (3, via_channel_id, option),
1139 (4, amount_msat, required),
1140 (5, via_user_channel_id, option),
1141 (6, _user_payment_id, option),
1142 (8, payment_preimage, option),
1144 let purpose = match payment_secret {
1145 Some(secret) => PaymentPurpose::InvoicePayment {
1147 payment_secret: secret
1149 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1150 None => return Err(msgs::DecodeError::InvalidValue),
1152 Ok(Some(Event::PaymentClaimable {
1158 via_user_channel_id,
1165 let mut payment_preimage = PaymentPreimage([0; 32]);
1166 let mut payment_hash = None;
1167 let mut payment_id = None;
1168 let mut fee_paid_msat = None;
1169 read_tlv_fields!(reader, {
1170 (0, payment_preimage, required),
1171 (1, payment_hash, option),
1172 (3, payment_id, option),
1173 (5, fee_paid_msat, option),
1175 if payment_hash.is_none() {
1176 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
1178 Ok(Some(Event::PaymentSent {
1181 payment_hash: payment_hash.unwrap(),
1190 let error_code = Readable::read(reader)?;
1192 let error_data = Readable::read(reader)?;
1193 let mut payment_hash = PaymentHash([0; 32]);
1194 let mut payment_failed_permanently = false;
1195 let mut network_update = None;
1196 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1197 let mut short_channel_id = None;
1198 let mut retry = None;
1199 let mut payment_id = None;
1200 read_tlv_fields!(reader, {
1201 (0, payment_hash, required),
1202 (1, network_update, upgradable_required),
1203 (2, payment_failed_permanently, required),
1204 (5, path, vec_type),
1205 (7, short_channel_id, option),
1207 (11, payment_id, option),
1209 Ok(Some(Event::PaymentPathFailed {
1212 payment_failed_permanently,
1214 path: path.unwrap(),
1228 let mut outputs = WithoutLength(Vec::new());
1229 read_tlv_fields!(reader, {
1230 (0, outputs, required),
1232 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
1237 let mut payment_hash = PaymentHash([0; 32]);
1238 let mut intercept_id = InterceptId([0; 32]);
1239 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1240 let mut inbound_amount_msat = 0;
1241 let mut expected_outbound_amount_msat = 0;
1242 read_tlv_fields!(reader, {
1243 (0, intercept_id, required),
1244 (2, requested_next_hop_scid, required),
1245 (4, payment_hash, required),
1246 (6, inbound_amount_msat, required),
1247 (8, expected_outbound_amount_msat, required),
1249 let next_scid = match requested_next_hop_scid {
1250 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1252 Ok(Some(Event::HTLCIntercepted {
1254 requested_next_hop_scid: next_scid,
1255 inbound_amount_msat,
1256 expected_outbound_amount_msat,
1262 let mut fee_earned_msat = None;
1263 let mut prev_channel_id = None;
1264 let mut claim_from_onchain_tx = false;
1265 let mut next_channel_id = None;
1266 read_tlv_fields!(reader, {
1267 (0, fee_earned_msat, option),
1268 (1, prev_channel_id, option),
1269 (2, claim_from_onchain_tx, required),
1270 (3, next_channel_id, option),
1272 Ok(Some(Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id }))
1278 let mut channel_id = [0; 32];
1279 let mut reason = None;
1280 let mut user_channel_id_low_opt: Option<u64> = None;
1281 let mut user_channel_id_high_opt: Option<u64> = None;
1282 read_tlv_fields!(reader, {
1283 (0, channel_id, required),
1284 (1, user_channel_id_low_opt, option),
1285 (2, reason, upgradable_required),
1286 (3, user_channel_id_high_opt, option),
1288 if reason.is_none() { return Ok(None); }
1290 // `user_channel_id` used to be a single u64 value. In order to remain
1291 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1292 // as two separate u64 values.
1293 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1294 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1296 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: reason.unwrap() }))
1302 let mut channel_id = [0; 32];
1303 let mut transaction = Transaction{ version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
1304 read_tlv_fields!(reader, {
1305 (0, channel_id, required),
1306 (2, transaction, required),
1308 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1314 let mut payment_id = PaymentId([0; 32]);
1315 let mut payment_hash = None;
1316 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1317 read_tlv_fields!(reader, {
1318 (0, payment_id, required),
1319 (2, payment_hash, option),
1320 (4, path, vec_type),
1322 Ok(Some(Event::PaymentPathSuccessful {
1325 path: path.unwrap(),
1332 let mut payment_hash = PaymentHash([0; 32]);
1333 let mut payment_id = PaymentId([0; 32]);
1334 read_tlv_fields!(reader, {
1335 (0, payment_id, required),
1336 (2, payment_hash, required),
1338 Ok(Some(Event::PaymentFailed {
1346 // Value 17 is used for `Event::OpenChannelRequest`.
1351 let mut payment_hash = PaymentHash([0; 32]);
1352 let mut purpose = None;
1353 let mut amount_msat = 0;
1354 let mut receiver_node_id = None;
1355 read_tlv_fields!(reader, {
1356 (0, payment_hash, required),
1357 (1, receiver_node_id, option),
1358 (2, purpose, upgradable_required),
1359 (4, amount_msat, required),
1361 if purpose.is_none() { return Ok(None); }
1362 Ok(Some(Event::PaymentClaimed {
1365 purpose: purpose.unwrap(),
1373 let mut payment_id = PaymentId([0; 32]);
1374 let mut payment_hash = PaymentHash([0; 32]);
1375 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1376 read_tlv_fields!(reader, {
1377 (0, payment_id, required),
1378 (2, payment_hash, required),
1379 (4, path, vec_type),
1381 Ok(Some(Event::ProbeSuccessful {
1384 path: path.unwrap(),
1391 let mut payment_id = PaymentId([0; 32]);
1392 let mut payment_hash = PaymentHash([0; 32]);
1393 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1394 let mut short_channel_id = None;
1395 read_tlv_fields!(reader, {
1396 (0, payment_id, required),
1397 (2, payment_hash, required),
1398 (4, path, vec_type),
1399 (6, short_channel_id, option),
1401 Ok(Some(Event::ProbeFailed {
1404 path: path.unwrap(),
1412 let mut prev_channel_id = [0; 32];
1413 let mut failed_next_destination_opt = None;
1414 read_tlv_fields!(reader, {
1415 (0, prev_channel_id, required),
1416 (2, failed_next_destination_opt, upgradable_required),
1418 if let Some(failed_next_destination) = failed_next_destination_opt {
1419 Ok(Some(Event::HTLCHandlingFailed {
1421 failed_next_destination,
1424 // If we fail to read a `failed_next_destination` assume it's because
1425 // `MaybeReadable::read` returned `Ok(None)`, though it's also possible we
1426 // were simply missing the field.
1435 let mut channel_id = [0; 32];
1436 let mut user_channel_id: u128 = 0;
1437 let mut counterparty_node_id = RequiredWrapper(None);
1438 let mut channel_type = RequiredWrapper(None);
1439 read_tlv_fields!(reader, {
1440 (0, channel_id, required),
1441 (2, user_channel_id, required),
1442 (4, counterparty_node_id, required),
1443 (6, channel_type, required),
1446 Ok(Some(Event::ChannelReady {
1449 counterparty_node_id: counterparty_node_id.0.unwrap(),
1450 channel_type: channel_type.0.unwrap()
1455 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1456 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1458 x if x % 2 == 1 => {
1459 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1460 // which prefixes the whole thing with a length BigSize. Because the event is
1461 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1462 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1463 // exactly the number of bytes specified, ignoring them entirely.
1464 let tlv_len: BigSize = Readable::read(reader)?;
1465 FixedLengthReader::new(reader, tlv_len.0)
1466 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1469 _ => Err(msgs::DecodeError::InvalidValue)
1474 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1475 /// broadcast to most peers).
1476 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1477 #[derive(Clone, Debug)]
1478 pub enum MessageSendEvent {
1479 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1480 /// message provided to the given peer.
1482 /// The node_id of the node which should receive this message
1484 /// The message which should be sent.
1485 msg: msgs::AcceptChannel,
1487 /// Used to indicate that we've initiated a channel open and should send the open_channel
1488 /// message provided to the given peer.
1490 /// The node_id of the node which should receive this message
1492 /// The message which should be sent.
1493 msg: msgs::OpenChannel,
1495 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1496 SendFundingCreated {
1497 /// The node_id of the node which should receive this message
1499 /// The message which should be sent.
1500 msg: msgs::FundingCreated,
1502 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1504 /// The node_id of the node which should receive this message
1506 /// The message which should be sent.
1507 msg: msgs::FundingSigned,
1509 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1511 /// The node_id of the node which should receive these message(s)
1513 /// The channel_ready message which should be sent.
1514 msg: msgs::ChannelReady,
1516 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1517 SendAnnouncementSignatures {
1518 /// The node_id of the node which should receive these message(s)
1520 /// The announcement_signatures message which should be sent.
1521 msg: msgs::AnnouncementSignatures,
1523 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1524 /// message should be sent to the peer with the given node_id.
1526 /// The node_id of the node which should receive these message(s)
1528 /// The update messages which should be sent. ALL messages in the struct should be sent!
1529 updates: msgs::CommitmentUpdate,
1531 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1533 /// The node_id of the node which should receive this message
1535 /// The message which should be sent.
1536 msg: msgs::RevokeAndACK,
1538 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1540 /// The node_id of the node which should receive this message
1542 /// The message which should be sent.
1543 msg: msgs::ClosingSigned,
1545 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1547 /// The node_id of the node which should receive this message
1549 /// The message which should be sent.
1550 msg: msgs::Shutdown,
1552 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1553 SendChannelReestablish {
1554 /// The node_id of the node which should receive this message
1556 /// The message which should be sent.
1557 msg: msgs::ChannelReestablish,
1559 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1560 /// initial connection to ensure our peers know about our channels.
1561 SendChannelAnnouncement {
1562 /// The node_id of the node which should receive this message
1564 /// The channel_announcement which should be sent.
1565 msg: msgs::ChannelAnnouncement,
1566 /// The followup channel_update which should be sent.
1567 update_msg: msgs::ChannelUpdate,
1569 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1570 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1572 /// Note that after doing so, you very likely (unless you did so very recently) want to
1573 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1574 /// ensures that any nodes which see our channel_announcement also have a relevant
1575 /// node_announcement, including relevant feature flags which may be important for routing
1576 /// through or to us.
1578 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1579 BroadcastChannelAnnouncement {
1580 /// The channel_announcement which should be sent.
1581 msg: msgs::ChannelAnnouncement,
1582 /// The followup channel_update which should be sent.
1583 update_msg: Option<msgs::ChannelUpdate>,
1585 /// Used to indicate that a channel_update should be broadcast to all peers.
1586 BroadcastChannelUpdate {
1587 /// The channel_update which should be sent.
1588 msg: msgs::ChannelUpdate,
1590 /// Used to indicate that a node_announcement should be broadcast to all peers.
1591 BroadcastNodeAnnouncement {
1592 /// The node_announcement which should be sent.
1593 msg: msgs::NodeAnnouncement,
1595 /// Used to indicate that a channel_update should be sent to a single peer.
1596 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1597 /// private channel and we shouldn't be informing all of our peers of channel parameters.
1599 /// The node_id of the node which should receive this message
1601 /// The channel_update which should be sent.
1602 msg: msgs::ChannelUpdate,
1604 /// Broadcast an error downstream to be handled
1606 /// The node_id of the node which should receive this message
1608 /// The action which should be taken.
1609 action: msgs::ErrorAction
1611 /// Query a peer for channels with funding transaction UTXOs in a block range.
1612 SendChannelRangeQuery {
1613 /// The node_id of this message recipient
1615 /// The query_channel_range which should be sent.
1616 msg: msgs::QueryChannelRange,
1618 /// Request routing gossip messages from a peer for a list of channels identified by
1619 /// their short_channel_ids.
1621 /// The node_id of this message recipient
1623 /// The query_short_channel_ids which should be sent.
1624 msg: msgs::QueryShortChannelIds,
1626 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1627 /// emitted during processing of the query.
1628 SendReplyChannelRange {
1629 /// The node_id of this message recipient
1631 /// The reply_channel_range which should be sent.
1632 msg: msgs::ReplyChannelRange,
1634 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1635 /// enable receiving gossip messages from the peer.
1636 SendGossipTimestampFilter {
1637 /// The node_id of this message recipient
1639 /// The gossip_timestamp_filter which should be sent.
1640 msg: msgs::GossipTimestampFilter,
1644 /// A trait indicating an object may generate message send events
1645 pub trait MessageSendEventsProvider {
1646 /// Gets the list of pending events which were generated by previous actions, clearing the list
1648 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1651 /// A trait indicating an object may generate onion messages to send
1652 pub trait OnionMessageProvider {
1653 /// Gets the next pending onion message for the peer with the given node id.
1654 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<msgs::OnionMessage>;
1657 /// A trait indicating an object may generate events.
1659 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1661 /// Implementations of this trait may also feature an async version of event handling, as shown with
1662 /// [`ChannelManager::process_pending_events_async`] and
1663 /// [`ChainMonitor::process_pending_events_async`].
1667 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1668 /// event since the last invocation.
1670 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1671 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1672 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1673 /// relevant changes to disk *before* returning.
1675 /// Further, because an application may crash between an [`Event`] being handled and the
1676 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1677 /// effect, [`Event`]s may be replayed.
1679 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1680 /// consult the provider's documentation on the implication of processing events and how a handler
1681 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1682 /// [`ChainMonitor::process_pending_events`]).
1684 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1687 /// [`process_pending_events`]: Self::process_pending_events
1688 /// [`handle_event`]: EventHandler::handle_event
1689 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1690 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1691 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
1692 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
1693 pub trait EventsProvider {
1694 /// Processes any events generated since the last call using the given event handler.
1696 /// See the trait-level documentation for requirements.
1697 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1700 /// A trait implemented for objects handling events from [`EventsProvider`].
1702 /// An async variation also exists for implementations of [`EventsProvider`] that support async
1703 /// event handling. The async event handler should satisfy the generic bounds: `F:
1704 /// core::future::Future, H: Fn(Event) -> F`.
1705 pub trait EventHandler {
1706 /// Handles the given [`Event`].
1708 /// See [`EventsProvider`] for details that must be considered when implementing this method.
1709 fn handle_event(&self, event: Event);
1712 impl<F> EventHandler for F where F: Fn(Event) {
1713 fn handle_event(&self, event: Event) {
1718 impl<T: EventHandler> EventHandler for Arc<T> {
1719 fn handle_event(&self, event: Event) {
1720 self.deref().handle_event(event)