1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Events are returned from various bits in the library which indicate some action must be taken
13 //! Because we don't have a built-in runtime, it's up to the client to call events at a time in the
14 //! future, as well as generate and broadcast funding transactions handle payment preimages and a
17 use crate::chain::keysinterface::SpendableOutputDescriptor;
19 use crate::ln::chan_utils::{self, ChannelTransactionParameters, HTLCOutputInCommitment};
20 use crate::ln::channelmanager::{InterceptId, PaymentId};
21 use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
22 use crate::ln::features::ChannelTypeFeatures;
24 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
25 use crate::routing::gossip::NetworkUpdate;
26 use crate::util::errors::APIError;
27 use crate::util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, RequiredWrapper, UpgradableRequired, WithoutLength};
28 use crate::util::string::UntrustedString;
29 use crate::routing::router::{RouteHop, RouteParameters};
31 use bitcoin::{PackedLockTime, Transaction};
33 use bitcoin::{OutPoint, Txid, TxIn, TxOut, Witness};
34 use bitcoin::blockdata::script::Script;
35 use bitcoin::hashes::Hash;
36 use bitcoin::hashes::sha256::Hash as Sha256;
37 use bitcoin::secp256k1::PublicKey;
39 use bitcoin::secp256k1::{self, Secp256k1};
41 use bitcoin::secp256k1::ecdsa::Signature;
43 use crate::prelude::*;
44 use core::time::Duration;
48 /// Some information provided on receipt of payment depends on whether the payment received is a
49 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
50 #[derive(Clone, Debug, PartialEq, Eq)]
51 pub enum PaymentPurpose {
52 /// Information for receiving a payment that we generated an invoice for.
54 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
55 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
56 /// [`ChannelManager::claim_funds`].
58 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
59 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
60 payment_preimage: Option<PaymentPreimage>,
61 /// The "payment secret". This authenticates the sender to the recipient, preventing a
62 /// number of deanonymization attacks during the routing process.
63 /// It is provided here for your reference, however its accuracy is enforced directly by
64 /// [`ChannelManager`] using the values you previously provided to
65 /// [`ChannelManager::create_inbound_payment`] or
66 /// [`ChannelManager::create_inbound_payment_for_hash`].
68 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
69 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
70 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
71 payment_secret: PaymentSecret,
73 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
74 /// (the payee) providing a preimage.
75 SpontaneousPayment(PaymentPreimage),
78 impl_writeable_tlv_based_enum!(PaymentPurpose,
79 (0, InvoicePayment) => {
80 (0, payment_preimage, option),
81 (2, payment_secret, required),
83 (2, SpontaneousPayment)
86 /// When the payment path failure took place and extra details about it. [`PathFailure::OnPath`] may
87 /// contain a [`NetworkUpdate`] that needs to be applied to the [`NetworkGraph`].
89 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
90 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
91 #[derive(Clone, Debug, Eq, PartialEq)]
92 pub enum PathFailure {
93 /// We failed to initially send the payment and no HTLC was committed to. Contains the relevant
96 /// The error surfaced from initial send.
99 /// A hop on the path failed to forward our payment.
101 /// If present, this [`NetworkUpdate`] should be applied to the [`NetworkGraph`] so that routing
102 /// decisions can take into account the update.
104 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
105 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
106 network_update: Option<NetworkUpdate>,
110 impl_writeable_tlv_based_enum_upgradable!(PathFailure,
112 (0, network_update, upgradable_option),
114 (2, InitialSend) => {
115 (0, err, upgradable_required),
119 #[derive(Clone, Debug, PartialEq, Eq)]
120 /// The reason the channel was closed. See individual variants more details.
121 pub enum ClosureReason {
122 /// Closure generated from receiving a peer error message.
124 /// Our counterparty may have broadcasted their latest commitment state, and we have
126 CounterpartyForceClosed {
127 /// The error which the peer sent us.
129 /// Be careful about printing the peer_msg, a well-crafted message could exploit
130 /// a security vulnerability in the terminal emulator or the logging subsystem.
131 /// To be safe, use `Display` on `UntrustedString`
133 /// [`UntrustedString`]: crate::util::string::UntrustedString
134 peer_msg: UntrustedString,
136 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
138 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
140 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
141 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
142 //TODO: split between CounterpartyInitiated/LocallyInitiated
144 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
145 /// commitment transaction came from our counterparty, but it may also have come from
146 /// a copy of our own `ChannelMonitor`.
147 CommitmentTxConfirmed,
148 /// The funding transaction failed to confirm in a timely manner on an inbound channel.
150 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
152 /// A developer-readable error message which we generated.
155 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
156 /// forget the channel entirely - we can attempt again if the peer reconnects.
158 /// This includes cases where we restarted prior to funding completion, including prior to the
159 /// initial [`ChannelMonitor`] persistence completing.
161 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
162 /// peer because of mutual incompatibility between us and our channel counterparty.
164 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
166 /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
167 /// the [`ChannelManager`] deserialized.
169 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
170 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
171 OutdatedChannelManager
174 impl core::fmt::Display for ClosureReason {
175 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
176 f.write_str("Channel closed because ")?;
178 ClosureReason::CounterpartyForceClosed { peer_msg } => {
179 f.write_fmt(format_args!("counterparty force-closed with message: {}", peer_msg))
181 ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
182 ClosureReason::CooperativeClosure => f.write_str("the channel was cooperatively closed"),
183 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
184 ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
185 ClosureReason::ProcessingError { err } => {
186 f.write_str("of an exception: ")?;
189 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
190 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
195 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
196 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
197 (1, FundingTimedOut) => {},
198 (2, HolderForceClosed) => {},
199 (6, CommitmentTxConfirmed) => {},
200 (4, CooperativeClosure) => {},
201 (8, ProcessingError) => { (1, err, required) },
202 (10, DisconnectedPeer) => {},
203 (12, OutdatedChannelManager) => {},
206 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
207 #[derive(Clone, Debug, PartialEq, Eq)]
208 pub enum HTLCDestination {
209 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
210 /// there is insufficient capacity in our outbound channel.
212 /// The `node_id` of the next node. For backwards compatibility, this field is
213 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
214 /// counterparty node information.
215 node_id: Option<PublicKey>,
216 /// The outgoing `channel_id` between us and the next node.
217 channel_id: [u8; 32],
219 /// Scenario where we are unsure of the next node to forward the HTLC to.
221 /// Short channel id we are requesting to forward an HTLC to.
222 requested_forward_scid: u64,
224 /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
227 /// Short channel id we are requesting to forward an HTLC to.
228 requested_forward_scid: u64
230 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
231 /// but is invalid for some reason, so we reject it.
233 /// Some of the reasons may include:
235 /// * Expected MPP amount to claim does not equal HTLC total
236 /// * Claimable amount does not match expected amount
238 /// The payment hash of the payment we attempted to process.
239 payment_hash: PaymentHash
243 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
244 (0, NextHopChannel) => {
245 (0, node_id, required),
246 (2, channel_id, required),
248 (1, InvalidForward) => {
249 (0, requested_forward_scid, required),
251 (2, UnknownNextHop) => {
252 (0, requested_forward_scid, required),
254 (4, FailedPayment) => {
255 (0, payment_hash, required),
260 /// A descriptor used to sign for a commitment transaction's anchor output.
261 #[derive(Clone, Debug)]
262 pub struct AnchorDescriptor {
263 /// A unique identifier used along with `channel_value_satoshis` to re-derive the
264 /// [`InMemorySigner`] required to sign `input`.
266 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
267 pub channel_keys_id: [u8; 32],
268 /// The value in satoshis of the channel we're attempting to spend the anchor output of. This is
269 /// used along with `channel_keys_id` to re-derive the [`InMemorySigner`] required to sign
272 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
273 pub channel_value_satoshis: u64,
274 /// The transaction input's outpoint corresponding to the commitment transaction's anchor
276 pub outpoint: OutPoint,
280 /// A descriptor used to sign for a commitment transaction's HTLC output.
281 #[derive(Clone, Debug)]
282 pub struct HTLCDescriptor {
283 /// A unique identifier used along with `channel_value_satoshis` to re-derive the
284 /// [`InMemorySigner`] required to sign `input`.
286 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
287 pub channel_keys_id: [u8; 32],
288 /// The value in satoshis of the channel we're attempting to spend the anchor output of. This is
289 /// used along with `channel_keys_id` to re-derive the [`InMemorySigner`] required to sign
292 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
293 pub channel_value_satoshis: u64,
294 /// The necessary channel parameters that need to be provided to the re-derived
295 /// [`InMemorySigner`] through [`BaseSign::provide_channel_parameters`].
297 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
298 /// [`BaseSign::provide_channel_parameters`]: crate::chain::keysinterface::BaseSign::provide_channel_parameters
299 pub channel_parameters: ChannelTransactionParameters,
300 /// The txid of the commitment transaction in which the HTLC output lives.
301 pub commitment_txid: Txid,
302 /// The number of the commitment transaction in which the HTLC output lives.
303 pub per_commitment_number: u64,
304 /// The details of the HTLC as it appears in the commitment transaction.
305 pub htlc: HTLCOutputInCommitment,
306 /// The preimage, if `Some`, to claim the HTLC output with. If `None`, the timeout path must be
308 pub preimage: Option<PaymentPreimage>,
309 /// The counterparty's signature required to spend the HTLC output.
310 pub counterparty_sig: Signature
314 impl HTLCDescriptor {
315 /// Returns the unsigned transaction input spending the HTLC output in the commitment
317 pub fn unsigned_tx_input(&self) -> TxIn {
318 chan_utils::build_htlc_input(&self.commitment_txid, &self.htlc, true /* opt_anchors */)
321 /// Returns the delayed output created as a result of spending the HTLC output in the commitment
323 pub fn tx_output<C: secp256k1::Signing + secp256k1::Verification>(
324 &self, per_commitment_point: &PublicKey, secp: &Secp256k1<C>
326 let channel_params = self.channel_parameters.as_holder_broadcastable();
327 let broadcaster_keys = channel_params.broadcaster_pubkeys();
328 let counterparty_keys = channel_params.countersignatory_pubkeys();
329 let broadcaster_delayed_key = chan_utils::derive_public_key(
330 secp, per_commitment_point, &broadcaster_keys.delayed_payment_basepoint
332 let counterparty_revocation_key = chan_utils::derive_public_revocation_key(
333 secp, per_commitment_point, &counterparty_keys.revocation_basepoint
335 chan_utils::build_htlc_output(
336 0 /* feerate_per_kw */, channel_params.contest_delay(), &self.htlc, true /* opt_anchors */,
337 false /* use_non_zero_fee_anchors */, &broadcaster_delayed_key, &counterparty_revocation_key
341 /// Returns the witness script of the HTLC output in the commitment transaction.
342 pub fn witness_script<C: secp256k1::Signing + secp256k1::Verification>(
343 &self, per_commitment_point: &PublicKey, secp: &Secp256k1<C>
345 let channel_params = self.channel_parameters.as_holder_broadcastable();
346 let broadcaster_keys = channel_params.broadcaster_pubkeys();
347 let counterparty_keys = channel_params.countersignatory_pubkeys();
348 let broadcaster_htlc_key = chan_utils::derive_public_key(
349 secp, per_commitment_point, &broadcaster_keys.htlc_basepoint
351 let counterparty_htlc_key = chan_utils::derive_public_key(
352 secp, per_commitment_point, &counterparty_keys.htlc_basepoint
354 let counterparty_revocation_key = chan_utils::derive_public_revocation_key(
355 secp, per_commitment_point, &counterparty_keys.revocation_basepoint
357 chan_utils::get_htlc_redeemscript_with_explicit_keys(
358 &self.htlc, true /* opt_anchors */, &broadcaster_htlc_key, &counterparty_htlc_key,
359 &counterparty_revocation_key,
363 /// Returns the fully signed witness required to spend the HTLC output in the commitment
365 pub fn tx_input_witness(&self, signature: &Signature, witness_script: &Script) -> Witness {
366 chan_utils::build_htlc_input_witness(
367 signature, &self.counterparty_sig, &self.preimage, witness_script, true /* opt_anchors */
373 /// Represents the different types of transactions, originating from LDK, to be bumped.
374 #[derive(Clone, Debug)]
375 pub enum BumpTransactionEvent {
376 /// Indicates that a channel featuring anchor outputs is to be closed by broadcasting the local
377 /// commitment transaction. Since commitment transactions have a static feerate pre-agreed upon,
378 /// they may need additional fees to be attached through a child transaction using the popular
379 /// [Child-Pays-For-Parent](https://bitcoinops.org/en/topics/cpfp) fee bumping technique. This
380 /// child transaction must include the anchor input described within `anchor_descriptor` along
381 /// with additional inputs to meet the target feerate. Failure to meet the target feerate
382 /// decreases the confirmation odds of the transaction package (which includes the commitment
383 /// and child anchor transactions), possibly resulting in a loss of funds. Once the transaction
384 /// is constructed, it must be fully signed for and broadcast by the consumer of the event
385 /// along with the `commitment_tx` enclosed. Note that the `commitment_tx` must always be
386 /// broadcast first, as the child anchor transaction depends on it.
388 /// The consumer should be able to sign for any of the additional inputs included within the
389 /// child anchor transaction. To sign its anchor input, an [`InMemorySigner`] should be
390 /// re-derived through [`KeysManager::derive_channel_keys`] with the help of
391 /// [`AnchorDescriptor::channel_keys_id`] and [`AnchorDescriptor::channel_value_satoshis`]. The
392 /// anchor input signature can be computed with [`BaseSign::sign_holder_anchor_input`],
393 /// which can then be provided to [`build_anchor_input_witness`] along with the `funding_pubkey`
394 /// to obtain the full witness required to spend.
396 /// It is possible to receive more than one instance of this event if a valid child anchor
397 /// transaction is never broadcast or is but not with a sufficient fee to be mined. Care should
398 /// be taken by the consumer of the event to ensure any future iterations of the child anchor
399 /// transaction adhere to the [Replace-By-Fee
400 /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
401 /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
402 /// these events is not user-controlled, users may ignore/drop the event if they are no longer
403 /// able to commit external confirmed funds to the child anchor transaction.
405 /// The set of `pending_htlcs` on the commitment transaction to be broadcast can be inspected to
406 /// determine whether a significant portion of the channel's funds are allocated to HTLCs,
407 /// enabling users to make their own decisions regarding the importance of the commitment
408 /// transaction's confirmation. Note that this is not required, but simply exists as an option
409 /// for users to override LDK's behavior. On commitments with no HTLCs (indicated by those with
410 /// an empty `pending_htlcs`), confirmation of the commitment transaction can be considered to
413 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
414 /// [`KeysManager::derive_channel_keys`]: crate::chain::keysinterface::KeysManager::derive_channel_keys
415 /// [`BaseSign::sign_holder_anchor_input`]: crate::chain::keysinterface::BaseSign::sign_holder_anchor_input
416 /// [`build_anchor_input_witness`]: crate::ln::chan_utils::build_anchor_input_witness
418 /// The target feerate that the transaction package, which consists of the commitment
419 /// transaction and the to-be-crafted child anchor transaction, must meet.
420 package_target_feerate_sat_per_1000_weight: u32,
421 /// The channel's commitment transaction to bump the fee of. This transaction should be
422 /// broadcast along with the anchor transaction constructed as a result of consuming this
424 commitment_tx: Transaction,
425 /// The absolute fee in satoshis of the commitment transaction. This can be used along the
426 /// with weight of the commitment transaction to determine its feerate.
427 commitment_tx_fee_satoshis: u64,
428 /// The descriptor to sign the anchor input of the anchor transaction constructed as a
429 /// result of consuming this event.
430 anchor_descriptor: AnchorDescriptor,
431 /// The set of pending HTLCs on the commitment transaction that need to be resolved once the
432 /// commitment transaction confirms.
433 pending_htlcs: Vec<HTLCOutputInCommitment>,
435 /// Indicates that a channel featuring anchor outputs has unilaterally closed on-chain by a
436 /// holder commitment transaction and its HTLC(s) need to be resolved on-chain. With the
437 /// zero-HTLC-transaction-fee variant of anchor outputs, the pre-signed HTLC
438 /// transactions have a zero fee, thus requiring additional inputs and/or outputs to be attached
439 /// for a timely confirmation within the chain. These additional inputs and/or outputs must be
440 /// appended to the resulting HTLC transaction to meet the target feerate. Failure to meet the
441 /// target feerate decreases the confirmation odds of the transaction, possibly resulting in a
442 /// loss of funds. Once the transaction meets the target feerate, it must be signed for and
443 /// broadcast by the consumer of the event.
445 /// The consumer should be able to sign for any of the non-HTLC inputs added to the resulting
446 /// HTLC transaction. To sign HTLC inputs, an [`InMemorySigner`] should be re-derived through
447 /// [`KeysManager::derive_channel_keys`] with the help of `channel_keys_id` and
448 /// `channel_value_satoshis`. Each HTLC input's signature can be computed with
449 /// [`BaseSign::sign_holder_htlc_transaction`], which can then be provided to
450 /// [`HTLCDescriptor::tx_input_witness`] to obtain the fully signed witness required to spend.
452 /// It is possible to receive more than one instance of this event if a valid HTLC transaction
453 /// is never broadcast or is but not with a sufficient fee to be mined. Care should be taken by
454 /// the consumer of the event to ensure any future iterations of the HTLC transaction adhere to
455 /// the [Replace-By-Fee
456 /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
457 /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
458 /// these events is not user-controlled, users may ignore/drop the event if either they are no
459 /// longer able to commit external confirmed funds to the HTLC transaction or the fee committed
460 /// to the HTLC transaction is greater in value than the HTLCs being claimed.
462 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
463 /// [`KeysManager::derive_channel_keys`]: crate::chain::keysinterface::KeysManager::derive_channel_keys
464 /// [`BaseSign::sign_holder_htlc_transaction`]: crate::chain::keysinterface::BaseSign::sign_holder_htlc_transaction
465 /// [`HTLCDescriptor::tx_input_witness`]: HTLCDescriptor::tx_input_witness
467 target_feerate_sat_per_1000_weight: u32,
468 htlc_descriptors: Vec<HTLCDescriptor>,
472 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
473 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
474 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
475 /// intercepts in upcoming work.
476 enum InterceptNextHop {
478 requested_next_hop_scid: u64,
482 impl_writeable_tlv_based_enum!(InterceptNextHop,
484 (0, requested_next_hop_scid, required),
488 /// An Event which you should probably take some action in response to.
490 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
491 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
492 /// written as it makes no sense to respond to it after reconnecting to peers).
493 #[derive(Clone, Debug, PartialEq, Eq)]
495 /// Used to indicate that the client should generate a funding transaction with the given
496 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
497 /// Generated in [`ChannelManager`] message handling.
498 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
499 /// counterparty can steal your funds!
501 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
502 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
503 FundingGenerationReady {
504 /// The random channel_id we picked which you'll need to pass into
505 /// [`ChannelManager::funding_transaction_generated`].
507 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
508 temporary_channel_id: [u8; 32],
509 /// The counterparty's node_id, which you'll need to pass back into
510 /// [`ChannelManager::funding_transaction_generated`].
512 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
513 counterparty_node_id: PublicKey,
514 /// The value, in satoshis, that the output should have.
515 channel_value_satoshis: u64,
516 /// The script which should be used in the transaction output.
517 output_script: Script,
518 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or a
519 /// random value for an inbound channel. This may be zero for objects serialized with LDK
520 /// versions prior to 0.0.113.
522 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
523 user_channel_id: u128,
525 /// Indicates that we've been offered a payment and it needs to be claimed via calling
526 /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
528 /// Note that if the preimage is not known, you should call
529 /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
530 /// to free up resources for this HTLC and avoid network congestion.
531 /// If you fail to call either [`ChannelManager::claim_funds`], [`ChannelManager::fail_htlc_backwards`],
532 /// or [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will be
533 /// automatically failed.
536 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
537 /// `PaymentClaimable` events may be generated for the same payment.
540 /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
542 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
543 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
544 /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
546 /// The node that will receive the payment after it has been claimed.
547 /// This is useful to identify payments 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 hash for which the preimage should be handed to the ChannelManager. Note that LDK will
554 /// not stop you from 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 /// Information for claiming this received payment, based on whether the purpose of the
559 /// payment is to pay an invoice or to send a spontaneous payment.
560 purpose: PaymentPurpose,
561 /// The `channel_id` indicating over which channel we received the payment.
562 via_channel_id: Option<[u8; 32]>,
563 /// The `user_channel_id` indicating over which channel we received the payment.
564 via_user_channel_id: Option<u128>,
566 /// Indicates a payment has been claimed and we've received money!
568 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
569 /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
570 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
571 /// [`Event::PaymentClaimable`] event.
574 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
575 /// `PaymentClaimable` events may be generated for the same payment. If you then call
576 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
577 /// multiple `PaymentClaimed` events.
579 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
581 /// The node that received the payment.
582 /// This is useful to identify payments which were received via [phantom nodes].
583 /// This field will always be filled in when the event was generated by LDK versions
584 /// 0.0.113 and above.
586 /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
587 receiver_node_id: Option<PublicKey>,
588 /// The payment hash of the claimed payment. Note that LDK will not stop you from
589 /// registering duplicate payment hashes for inbound payments.
590 payment_hash: PaymentHash,
591 /// The value, in thousandths of a satoshi, that this payment is for.
593 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
594 /// spontaneous payment.
595 purpose: PaymentPurpose,
597 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
598 /// and we got back the payment preimage for it).
600 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
601 /// event. In this situation, you SHOULD treat this payment as having succeeded.
603 /// The id returned by [`ChannelManager::send_payment`].
605 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
606 payment_id: Option<PaymentId>,
607 /// The preimage to the hash given to ChannelManager::send_payment.
608 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
609 /// store it somehow!
610 payment_preimage: PaymentPreimage,
611 /// The hash that was given to [`ChannelManager::send_payment`].
613 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
614 payment_hash: PaymentHash,
615 /// The total fee which was spent at intermediate hops in this payment, across all paths.
617 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
618 /// overpayment to the recipient node.
620 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
621 /// overstate the amount paid, though this is unlikely.
623 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
624 fee_paid_msat: Option<u64>,
626 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
627 /// provide failure information for each path attempt in the payment, including retries.
629 /// This event is provided once there are no further pending HTLCs for the payment and the
630 /// payment is no longer retryable, due either to the [`Retry`] provided or
631 /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
633 /// [`Retry`]: crate::ln::channelmanager::Retry
634 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
636 /// The id returned by [`ChannelManager::send_payment`] and used with
637 /// [`ChannelManager::abandon_payment`].
639 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
640 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
641 payment_id: PaymentId,
642 /// The hash that was given to [`ChannelManager::send_payment`].
644 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
645 payment_hash: PaymentHash,
647 /// Indicates that a path for an outbound payment was successful.
649 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
650 /// [`Event::PaymentSent`] for obtaining the payment preimage.
651 PaymentPathSuccessful {
652 /// The id returned by [`ChannelManager::send_payment`].
654 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
655 payment_id: PaymentId,
656 /// The hash that was given to [`ChannelManager::send_payment`].
658 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
659 payment_hash: Option<PaymentHash>,
660 /// The payment path that was successful.
662 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
665 /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
668 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
669 /// [`Event::PaymentFailed`].
671 /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
674 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
676 /// The id returned by [`ChannelManager::send_payment`] and used with
677 /// [`ChannelManager::abandon_payment`].
679 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
680 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
681 payment_id: Option<PaymentId>,
682 /// The hash that was given to [`ChannelManager::send_payment`].
684 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
685 payment_hash: PaymentHash,
686 /// Indicates the payment was rejected for some reason by the recipient. This implies that
687 /// the payment has failed, not just the route in question. If this is not set, the payment may
688 /// be retried via a different route.
689 payment_failed_permanently: bool,
690 /// Extra error details based on the failure type. May contain an update that needs to be
691 /// applied to the [`NetworkGraph`].
693 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
694 failure: PathFailure,
695 /// The payment path that failed.
697 /// The channel responsible for the failed payment path.
699 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
700 /// may not refer to a channel in the public network graph. These aliases may also collide
701 /// with channels in the public network graph.
703 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
704 /// retried. May be `None` for older [`Event`] serializations.
705 short_channel_id: Option<u64>,
707 error_code: Option<u16>,
709 error_data: Option<Vec<u8>>,
711 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
713 /// The id returned by [`ChannelManager::send_probe`].
715 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
716 payment_id: PaymentId,
717 /// The hash generated by [`ChannelManager::send_probe`].
719 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
720 payment_hash: PaymentHash,
721 /// The payment path that was successful.
724 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
726 /// The id returned by [`ChannelManager::send_probe`].
728 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
729 payment_id: PaymentId,
730 /// The hash generated by [`ChannelManager::send_probe`].
732 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
733 payment_hash: PaymentHash,
734 /// The payment path that failed.
736 /// The channel responsible for the failed probe.
738 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
739 /// may not refer to a channel in the public network graph. These aliases may also collide
740 /// with channels in the public network graph.
741 short_channel_id: Option<u64>,
743 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
744 /// a time in the future.
746 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
747 PendingHTLCsForwardable {
748 /// The minimum amount of time that should be waited prior to calling
749 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
750 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
751 /// now + 5*time_forwardable).
752 time_forwardable: Duration,
754 /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
755 /// you've encoded an intercept scid in the receiver's invoice route hints using
756 /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
758 /// [`ChannelManager::forward_intercepted_htlc`] or
759 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
760 /// their docs for more information.
762 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
763 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
764 /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
765 /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
767 /// An id to help LDK identify which HTLC is being forwarded or failed.
768 intercept_id: InterceptId,
769 /// The fake scid that was programmed as the next hop's scid, generated using
770 /// [`ChannelManager::get_intercept_scid`].
772 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
773 requested_next_hop_scid: u64,
774 /// The payment hash used for this HTLC.
775 payment_hash: PaymentHash,
776 /// How many msats were received on the inbound edge of this HTLC.
777 inbound_amount_msat: u64,
778 /// How many msats the payer intended to route to the next node. Depending on the reason you are
779 /// intercepting this payment, you might take a fee by forwarding less than this amount.
781 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
782 /// check that whatever fee you want has been included here or subtract it as required. Further,
783 /// LDK will not stop you from forwarding more than you received.
784 expected_outbound_amount_msat: u64,
786 /// Used to indicate that an output which you should know how to spend was confirmed on chain
787 /// and is now spendable.
788 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
789 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
790 /// somewhere and spend them when you create on-chain transactions.
792 /// The outputs which you should store as spendable by you.
793 outputs: Vec<SpendableOutputDescriptor>,
795 /// This event is generated when a payment has been successfully forwarded through us and a
796 /// forwarding fee earned.
798 /// The incoming channel between the previous node and us. This is only `None` for events
799 /// generated or serialized by versions prior to 0.0.107.
800 prev_channel_id: Option<[u8; 32]>,
801 /// The outgoing channel between the next node and us. This is only `None` for events
802 /// generated or serialized by versions prior to 0.0.107.
803 next_channel_id: Option<[u8; 32]>,
804 /// The fee, in milli-satoshis, which was earned as a result of the payment.
806 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
807 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
808 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
809 /// claimed the full value in millisatoshis from the source. In this case,
810 /// `claim_from_onchain_tx` will be set.
812 /// If the channel which sent us the payment has been force-closed, we will claim the funds
813 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
814 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
815 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
817 fee_earned_msat: Option<u64>,
818 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
820 claim_from_onchain_tx: bool,
822 /// Used to indicate that a channel with the given `channel_id` is ready to
823 /// be used. This event is emitted either when the funding transaction has been confirmed
824 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
827 /// The channel_id of the channel that is ready.
828 channel_id: [u8; 32],
829 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
830 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
831 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
832 /// `user_channel_id` will be randomized for an inbound channel.
834 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
835 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
836 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
837 user_channel_id: u128,
838 /// The node_id of the channel counterparty.
839 counterparty_node_id: PublicKey,
840 /// The features that this channel will operate with.
841 channel_type: ChannelTypeFeatures,
843 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
844 /// process of closure.
846 /// The channel_id of the channel which has been closed. Note that on-chain transactions
847 /// resolving the channel are likely still awaiting confirmation.
848 channel_id: [u8; 32],
849 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
850 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
851 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
852 /// `user_channel_id` will be randomized for inbound channels.
853 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
854 /// zero for objects serialized with LDK versions prior to 0.0.102.
856 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
857 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
858 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
859 user_channel_id: u128,
860 /// The reason the channel was closed.
861 reason: ClosureReason
863 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
864 /// inputs for another purpose.
866 /// The channel_id of the channel which has been closed.
867 channel_id: [u8; 32],
868 /// The full transaction received from the user
869 transaction: Transaction
871 /// Indicates a request to open a new channel by a peer.
873 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the
874 /// request, call [`ChannelManager::force_close_without_broadcasting_txn`].
876 /// The event is only triggered when a new open channel request is received and the
877 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
879 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
880 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
881 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
883 /// The temporary channel ID of the channel requested to be opened.
885 /// When responding to the request, the `temporary_channel_id` should be passed
886 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
887 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
889 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
890 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
891 temporary_channel_id: [u8; 32],
892 /// The node_id of the counterparty requesting to open the channel.
894 /// When responding to the request, the `counterparty_node_id` should be passed
895 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
896 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
899 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
900 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
901 counterparty_node_id: PublicKey,
902 /// The channel value of the requested channel.
903 funding_satoshis: u64,
904 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
906 /// The features that this channel will operate with. If you reject the channel, a
907 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
910 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
911 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
914 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
915 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
916 /// 0.0.107. Channels setting this type also need to get manually accepted via
917 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
918 /// or will be rejected otherwise.
920 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
921 channel_type: ChannelTypeFeatures,
923 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
926 /// Some scenarios where this event may be sent include:
927 /// * Insufficient capacity in the outbound channel
928 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
929 /// * When an unknown SCID is requested for forwarding a payment.
930 /// * Claiming an amount for an MPP payment that exceeds the HTLC total
931 /// * The HTLC has timed out
933 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
934 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
936 /// The channel over which the HTLC was received.
937 prev_channel_id: [u8; 32],
938 /// Destination of the HTLC that failed to be processed.
939 failed_next_destination: HTLCDestination,
942 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
943 /// requires confirmed external funds to be readily available to spend.
945 /// LDK does not currently generate this event. It is limited to the scope of channels with
946 /// anchor outputs, which will be introduced in a future release.
947 BumpTransaction(BumpTransactionEvent),
950 impl Writeable for Event {
951 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
953 &Event::FundingGenerationReady { .. } => {
955 // We never write out FundingGenerationReady events as, upon disconnection, peers
956 // drop any channels which have not yet exchanged funding_signed.
958 &Event::PaymentClaimable { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id } => {
960 let mut payment_secret = None;
961 let payment_preimage;
963 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
964 payment_secret = Some(secret);
965 payment_preimage = *preimage;
967 PaymentPurpose::SpontaneousPayment(preimage) => {
968 payment_preimage = Some(*preimage);
971 write_tlv_fields!(writer, {
972 (0, payment_hash, required),
973 (1, receiver_node_id, option),
974 (2, payment_secret, option),
975 (3, via_channel_id, option),
976 (4, amount_msat, required),
977 (5, via_user_channel_id, option),
978 (6, 0u64, required), // user_payment_id required for compatibility with 0.0.103 and earlier
979 (8, payment_preimage, option),
982 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
984 write_tlv_fields!(writer, {
985 (0, payment_preimage, required),
986 (1, payment_hash, required),
987 (3, payment_id, option),
988 (5, fee_paid_msat, option),
991 &Event::PaymentPathFailed {
992 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
993 ref path, ref short_channel_id,
1001 error_code.write(writer)?;
1003 error_data.write(writer)?;
1004 write_tlv_fields!(writer, {
1005 (0, payment_hash, required),
1006 (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
1007 (2, payment_failed_permanently, required),
1008 (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
1009 (5, *path, vec_type),
1010 (7, short_channel_id, option),
1011 (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
1012 (11, payment_id, option),
1013 (13, failure, required),
1016 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
1018 // Note that we now ignore these on the read end as we'll re-generate them in
1019 // ChannelManager, we write them here only for backwards compatibility.
1021 &Event::SpendableOutputs { ref outputs } => {
1023 write_tlv_fields!(writer, {
1024 (0, WithoutLength(outputs), required),
1027 &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
1029 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
1030 write_tlv_fields!(writer, {
1031 (0, intercept_id, required),
1032 (2, intercept_scid, required),
1033 (4, payment_hash, required),
1034 (6, inbound_amount_msat, required),
1035 (8, expected_outbound_amount_msat, required),
1038 &Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
1040 write_tlv_fields!(writer, {
1041 (0, fee_earned_msat, option),
1042 (1, prev_channel_id, option),
1043 (2, claim_from_onchain_tx, required),
1044 (3, next_channel_id, option),
1047 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
1049 // `user_channel_id` used to be a single u64 value. In order to remain backwards
1050 // compatible with versions prior to 0.0.113, the u128 is serialized as two
1051 // separate u64 values.
1052 let user_channel_id_low = *user_channel_id as u64;
1053 let user_channel_id_high = (*user_channel_id >> 64) as u64;
1054 write_tlv_fields!(writer, {
1055 (0, channel_id, required),
1056 (1, user_channel_id_low, required),
1057 (2, reason, required),
1058 (3, user_channel_id_high, required),
1061 &Event::DiscardFunding { ref channel_id, ref transaction } => {
1062 11u8.write(writer)?;
1063 write_tlv_fields!(writer, {
1064 (0, channel_id, required),
1065 (2, transaction, required)
1068 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
1069 13u8.write(writer)?;
1070 write_tlv_fields!(writer, {
1071 (0, payment_id, required),
1072 (2, payment_hash, option),
1073 (4, *path, vec_type)
1076 &Event::PaymentFailed { ref payment_id, ref payment_hash } => {
1077 15u8.write(writer)?;
1078 write_tlv_fields!(writer, {
1079 (0, payment_id, required),
1080 (2, payment_hash, required),
1083 &Event::OpenChannelRequest { .. } => {
1084 17u8.write(writer)?;
1085 // We never write the OpenChannelRequest events as, upon disconnection, peers
1086 // drop any channels which have not yet exchanged funding_signed.
1088 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id } => {
1089 19u8.write(writer)?;
1090 write_tlv_fields!(writer, {
1091 (0, payment_hash, required),
1092 (1, receiver_node_id, option),
1093 (2, purpose, required),
1094 (4, amount_msat, required),
1097 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
1098 21u8.write(writer)?;
1099 write_tlv_fields!(writer, {
1100 (0, payment_id, required),
1101 (2, payment_hash, required),
1102 (4, *path, vec_type)
1105 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
1106 23u8.write(writer)?;
1107 write_tlv_fields!(writer, {
1108 (0, payment_id, required),
1109 (2, payment_hash, required),
1110 (4, *path, vec_type),
1111 (6, short_channel_id, option),
1114 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
1115 25u8.write(writer)?;
1116 write_tlv_fields!(writer, {
1117 (0, prev_channel_id, required),
1118 (2, failed_next_destination, required),
1122 &Event::BumpTransaction(ref event)=> {
1123 27u8.write(writer)?;
1125 // We never write the ChannelClose|HTLCResolution events as they'll be replayed
1126 // upon restarting anyway if they remain unresolved.
1127 BumpTransactionEvent::ChannelClose { .. } => {}
1128 BumpTransactionEvent::HTLCResolution { .. } => {}
1130 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
1132 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
1133 29u8.write(writer)?;
1134 write_tlv_fields!(writer, {
1135 (0, channel_id, required),
1136 (2, user_channel_id, required),
1137 (4, counterparty_node_id, required),
1138 (6, channel_type, required),
1141 // Note that, going forward, all new events must only write data inside of
1142 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1143 // data via `write_tlv_fields`.
1148 impl MaybeReadable for Event {
1149 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1150 match Readable::read(reader)? {
1151 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
1152 // unlike all other events, thus we return immediately here.
1156 let mut payment_hash = PaymentHash([0; 32]);
1157 let mut payment_preimage = None;
1158 let mut payment_secret = None;
1159 let mut amount_msat = 0;
1160 let mut receiver_node_id = None;
1161 let mut _user_payment_id = None::<u64>; // For compatibility with 0.0.103 and earlier
1162 let mut via_channel_id = None;
1163 let mut via_user_channel_id = None;
1164 read_tlv_fields!(reader, {
1165 (0, payment_hash, required),
1166 (1, receiver_node_id, option),
1167 (2, payment_secret, option),
1168 (3, via_channel_id, option),
1169 (4, amount_msat, required),
1170 (5, via_user_channel_id, option),
1171 (6, _user_payment_id, option),
1172 (8, payment_preimage, option),
1174 let purpose = match payment_secret {
1175 Some(secret) => PaymentPurpose::InvoicePayment {
1177 payment_secret: secret
1179 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1180 None => return Err(msgs::DecodeError::InvalidValue),
1182 Ok(Some(Event::PaymentClaimable {
1188 via_user_channel_id,
1195 let mut payment_preimage = PaymentPreimage([0; 32]);
1196 let mut payment_hash = None;
1197 let mut payment_id = None;
1198 let mut fee_paid_msat = None;
1199 read_tlv_fields!(reader, {
1200 (0, payment_preimage, required),
1201 (1, payment_hash, option),
1202 (3, payment_id, option),
1203 (5, fee_paid_msat, option),
1205 if payment_hash.is_none() {
1206 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
1208 Ok(Some(Event::PaymentSent {
1211 payment_hash: payment_hash.unwrap(),
1220 let error_code = Readable::read(reader)?;
1222 let error_data = Readable::read(reader)?;
1223 let mut payment_hash = PaymentHash([0; 32]);
1224 let mut payment_failed_permanently = false;
1225 let mut network_update = None;
1226 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1227 let mut short_channel_id = None;
1228 let mut payment_id = None;
1229 let mut failure_opt = None;
1230 read_tlv_fields!(reader, {
1231 (0, payment_hash, required),
1232 (1, network_update, upgradable_option),
1233 (2, payment_failed_permanently, required),
1234 (5, path, vec_type),
1235 (7, short_channel_id, option),
1236 (11, payment_id, option),
1237 (13, failure_opt, upgradable_option),
1239 let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1240 Ok(Some(Event::PaymentPathFailed {
1243 payment_failed_permanently,
1245 path: path.unwrap(),
1258 let mut outputs = WithoutLength(Vec::new());
1259 read_tlv_fields!(reader, {
1260 (0, outputs, required),
1262 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
1267 let mut payment_hash = PaymentHash([0; 32]);
1268 let mut intercept_id = InterceptId([0; 32]);
1269 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1270 let mut inbound_amount_msat = 0;
1271 let mut expected_outbound_amount_msat = 0;
1272 read_tlv_fields!(reader, {
1273 (0, intercept_id, required),
1274 (2, requested_next_hop_scid, required),
1275 (4, payment_hash, required),
1276 (6, inbound_amount_msat, required),
1277 (8, expected_outbound_amount_msat, required),
1279 let next_scid = match requested_next_hop_scid {
1280 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1282 Ok(Some(Event::HTLCIntercepted {
1284 requested_next_hop_scid: next_scid,
1285 inbound_amount_msat,
1286 expected_outbound_amount_msat,
1292 let mut fee_earned_msat = None;
1293 let mut prev_channel_id = None;
1294 let mut claim_from_onchain_tx = false;
1295 let mut next_channel_id = None;
1296 read_tlv_fields!(reader, {
1297 (0, fee_earned_msat, option),
1298 (1, prev_channel_id, option),
1299 (2, claim_from_onchain_tx, required),
1300 (3, next_channel_id, option),
1302 Ok(Some(Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id }))
1308 let mut channel_id = [0; 32];
1309 let mut reason = UpgradableRequired(None);
1310 let mut user_channel_id_low_opt: Option<u64> = None;
1311 let mut user_channel_id_high_opt: Option<u64> = None;
1312 read_tlv_fields!(reader, {
1313 (0, channel_id, required),
1314 (1, user_channel_id_low_opt, option),
1315 (2, reason, upgradable_required),
1316 (3, user_channel_id_high_opt, option),
1319 // `user_channel_id` used to be a single u64 value. In order to remain
1320 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1321 // as two separate u64 values.
1322 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1323 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1325 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required) }))
1331 let mut channel_id = [0; 32];
1332 let mut transaction = Transaction{ version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
1333 read_tlv_fields!(reader, {
1334 (0, channel_id, required),
1335 (2, transaction, required),
1337 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1343 let mut payment_id = PaymentId([0; 32]);
1344 let mut payment_hash = None;
1345 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1346 read_tlv_fields!(reader, {
1347 (0, payment_id, required),
1348 (2, payment_hash, option),
1349 (4, path, vec_type),
1351 Ok(Some(Event::PaymentPathSuccessful {
1354 path: path.unwrap(),
1361 let mut payment_hash = PaymentHash([0; 32]);
1362 let mut payment_id = PaymentId([0; 32]);
1363 read_tlv_fields!(reader, {
1364 (0, payment_id, required),
1365 (2, payment_hash, required),
1367 Ok(Some(Event::PaymentFailed {
1375 // Value 17 is used for `Event::OpenChannelRequest`.
1380 let mut payment_hash = PaymentHash([0; 32]);
1381 let mut purpose = UpgradableRequired(None);
1382 let mut amount_msat = 0;
1383 let mut receiver_node_id = None;
1384 read_tlv_fields!(reader, {
1385 (0, payment_hash, required),
1386 (1, receiver_node_id, option),
1387 (2, purpose, upgradable_required),
1388 (4, amount_msat, required),
1390 Ok(Some(Event::PaymentClaimed {
1393 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1401 let mut payment_id = PaymentId([0; 32]);
1402 let mut payment_hash = PaymentHash([0; 32]);
1403 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1404 read_tlv_fields!(reader, {
1405 (0, payment_id, required),
1406 (2, payment_hash, required),
1407 (4, path, vec_type),
1409 Ok(Some(Event::ProbeSuccessful {
1412 path: path.unwrap(),
1419 let mut payment_id = PaymentId([0; 32]);
1420 let mut payment_hash = PaymentHash([0; 32]);
1421 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1422 let mut short_channel_id = None;
1423 read_tlv_fields!(reader, {
1424 (0, payment_id, required),
1425 (2, payment_hash, required),
1426 (4, path, vec_type),
1427 (6, short_channel_id, option),
1429 Ok(Some(Event::ProbeFailed {
1432 path: path.unwrap(),
1440 let mut prev_channel_id = [0; 32];
1441 let mut failed_next_destination_opt = UpgradableRequired(None);
1442 read_tlv_fields!(reader, {
1443 (0, prev_channel_id, required),
1444 (2, failed_next_destination_opt, upgradable_required),
1446 Ok(Some(Event::HTLCHandlingFailed {
1448 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1456 let mut channel_id = [0; 32];
1457 let mut user_channel_id: u128 = 0;
1458 let mut counterparty_node_id = RequiredWrapper(None);
1459 let mut channel_type = RequiredWrapper(None);
1460 read_tlv_fields!(reader, {
1461 (0, channel_id, required),
1462 (2, user_channel_id, required),
1463 (4, counterparty_node_id, required),
1464 (6, channel_type, required),
1467 Ok(Some(Event::ChannelReady {
1470 counterparty_node_id: counterparty_node_id.0.unwrap(),
1471 channel_type: channel_type.0.unwrap()
1476 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1477 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1479 x if x % 2 == 1 => {
1480 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1481 // which prefixes the whole thing with a length BigSize. Because the event is
1482 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1483 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1484 // exactly the number of bytes specified, ignoring them entirely.
1485 let tlv_len: BigSize = Readable::read(reader)?;
1486 FixedLengthReader::new(reader, tlv_len.0)
1487 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1490 _ => Err(msgs::DecodeError::InvalidValue)
1495 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1496 /// broadcast to most peers).
1497 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1498 #[derive(Clone, Debug)]
1499 pub enum MessageSendEvent {
1500 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1501 /// message provided to the given peer.
1503 /// The node_id of the node which should receive this message
1505 /// The message which should be sent.
1506 msg: msgs::AcceptChannel,
1508 /// Used to indicate that we've initiated a channel open and should send the open_channel
1509 /// message provided to the given peer.
1511 /// The node_id of the node which should receive this message
1513 /// The message which should be sent.
1514 msg: msgs::OpenChannel,
1516 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1517 SendFundingCreated {
1518 /// The node_id of the node which should receive this message
1520 /// The message which should be sent.
1521 msg: msgs::FundingCreated,
1523 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1525 /// The node_id of the node which should receive this message
1527 /// The message which should be sent.
1528 msg: msgs::FundingSigned,
1530 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1532 /// The node_id of the node which should receive these message(s)
1534 /// The channel_ready message which should be sent.
1535 msg: msgs::ChannelReady,
1537 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1538 SendAnnouncementSignatures {
1539 /// The node_id of the node which should receive these message(s)
1541 /// The announcement_signatures message which should be sent.
1542 msg: msgs::AnnouncementSignatures,
1544 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1545 /// message should be sent to the peer with the given node_id.
1547 /// The node_id of the node which should receive these message(s)
1549 /// The update messages which should be sent. ALL messages in the struct should be sent!
1550 updates: msgs::CommitmentUpdate,
1552 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1554 /// The node_id of the node which should receive this message
1556 /// The message which should be sent.
1557 msg: msgs::RevokeAndACK,
1559 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1561 /// The node_id of the node which should receive this message
1563 /// The message which should be sent.
1564 msg: msgs::ClosingSigned,
1566 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1568 /// The node_id of the node which should receive this message
1570 /// The message which should be sent.
1571 msg: msgs::Shutdown,
1573 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1574 SendChannelReestablish {
1575 /// The node_id of the node which should receive this message
1577 /// The message which should be sent.
1578 msg: msgs::ChannelReestablish,
1580 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1581 /// initial connection to ensure our peers know about our channels.
1582 SendChannelAnnouncement {
1583 /// The node_id of the node which should receive this message
1585 /// The channel_announcement which should be sent.
1586 msg: msgs::ChannelAnnouncement,
1587 /// The followup channel_update which should be sent.
1588 update_msg: msgs::ChannelUpdate,
1590 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1591 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1593 /// Note that after doing so, you very likely (unless you did so very recently) want to
1594 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1595 /// ensures that any nodes which see our channel_announcement also have a relevant
1596 /// node_announcement, including relevant feature flags which may be important for routing
1597 /// through or to us.
1599 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1600 BroadcastChannelAnnouncement {
1601 /// The channel_announcement which should be sent.
1602 msg: msgs::ChannelAnnouncement,
1603 /// The followup channel_update which should be sent.
1604 update_msg: Option<msgs::ChannelUpdate>,
1606 /// Used to indicate that a channel_update should be broadcast to all peers.
1607 BroadcastChannelUpdate {
1608 /// The channel_update which should be sent.
1609 msg: msgs::ChannelUpdate,
1611 /// Used to indicate that a node_announcement should be broadcast to all peers.
1612 BroadcastNodeAnnouncement {
1613 /// The node_announcement which should be sent.
1614 msg: msgs::NodeAnnouncement,
1616 /// Used to indicate that a channel_update should be sent to a single peer.
1617 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1618 /// private channel and we shouldn't be informing all of our peers of channel parameters.
1620 /// The node_id of the node which should receive this message
1622 /// The channel_update which should be sent.
1623 msg: msgs::ChannelUpdate,
1625 /// Broadcast an error downstream to be handled
1627 /// The node_id of the node which should receive this message
1629 /// The action which should be taken.
1630 action: msgs::ErrorAction
1632 /// Query a peer for channels with funding transaction UTXOs in a block range.
1633 SendChannelRangeQuery {
1634 /// The node_id of this message recipient
1636 /// The query_channel_range which should be sent.
1637 msg: msgs::QueryChannelRange,
1639 /// Request routing gossip messages from a peer for a list of channels identified by
1640 /// their short_channel_ids.
1642 /// The node_id of this message recipient
1644 /// The query_short_channel_ids which should be sent.
1645 msg: msgs::QueryShortChannelIds,
1647 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1648 /// emitted during processing of the query.
1649 SendReplyChannelRange {
1650 /// The node_id of this message recipient
1652 /// The reply_channel_range which should be sent.
1653 msg: msgs::ReplyChannelRange,
1655 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1656 /// enable receiving gossip messages from the peer.
1657 SendGossipTimestampFilter {
1658 /// The node_id of this message recipient
1660 /// The gossip_timestamp_filter which should be sent.
1661 msg: msgs::GossipTimestampFilter,
1665 /// A trait indicating an object may generate message send events
1666 pub trait MessageSendEventsProvider {
1667 /// Gets the list of pending events which were generated by previous actions, clearing the list
1669 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1672 /// A trait indicating an object may generate onion messages to send
1673 pub trait OnionMessageProvider {
1674 /// Gets the next pending onion message for the peer with the given node id.
1675 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<msgs::OnionMessage>;
1678 /// A trait indicating an object may generate events.
1680 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1682 /// Implementations of this trait may also feature an async version of event handling, as shown with
1683 /// [`ChannelManager::process_pending_events_async`] and
1684 /// [`ChainMonitor::process_pending_events_async`].
1688 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1689 /// event since the last invocation.
1691 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1692 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1693 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1694 /// relevant changes to disk *before* returning.
1696 /// Further, because an application may crash between an [`Event`] being handled and the
1697 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1698 /// effect, [`Event`]s may be replayed.
1700 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1701 /// consult the provider's documentation on the implication of processing events and how a handler
1702 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1703 /// [`ChainMonitor::process_pending_events`]).
1705 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1708 /// [`process_pending_events`]: Self::process_pending_events
1709 /// [`handle_event`]: EventHandler::handle_event
1710 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1711 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1712 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
1713 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
1714 pub trait EventsProvider {
1715 /// Processes any events generated since the last call using the given event handler.
1717 /// See the trait-level documentation for requirements.
1718 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1721 /// A trait implemented for objects handling events from [`EventsProvider`].
1723 /// An async variation also exists for implementations of [`EventsProvider`] that support async
1724 /// event handling. The async event handler should satisfy the generic bounds: `F:
1725 /// core::future::Future, H: Fn(Event) -> F`.
1726 pub trait EventHandler {
1727 /// Handles the given [`Event`].
1729 /// See [`EventsProvider`] for details that must be considered when implementing this method.
1730 fn handle_event(&self, event: Event);
1733 impl<F> EventHandler for F where F: Fn(Event) {
1734 fn handle_event(&self, event: Event) {
1739 impl<T: EventHandler> EventHandler for Arc<T> {
1740 fn handle_event(&self, event: Event) {
1741 self.deref().handle_event(event)