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::HTLCOutputInCommitment;
20 use crate::ln::channelmanager::{InterceptId, PaymentId};
21 use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
22 use crate::ln::features::ChannelTypeFeatures;
24 use crate::ln::msgs::DecodeError;
25 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
26 use crate::routing::gossip::NetworkUpdate;
27 use crate::util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, WithoutLength, OptionDeserWrapper};
28 use crate::routing::router::{RouteHop, RouteParameters};
30 use bitcoin::{PackedLockTime, Transaction};
32 use bitcoin::OutPoint;
33 use bitcoin::blockdata::script::Script;
34 use bitcoin::hashes::Hash;
35 use bitcoin::hashes::sha256::Hash as Sha256;
36 use bitcoin::secp256k1::PublicKey;
38 use crate::prelude::*;
39 use core::time::Duration;
43 /// Some information provided on receipt of payment depends on whether the payment received is a
44 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
45 #[derive(Clone, Debug)]
46 pub enum PaymentPurpose {
47 /// Information for receiving a payment that we generated an invoice for.
49 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
50 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
51 /// [`ChannelManager::claim_funds`].
53 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
54 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
55 payment_preimage: Option<PaymentPreimage>,
56 /// The "payment secret". This authenticates the sender to the recipient, preventing a
57 /// number of deanonymization attacks during the routing process.
58 /// It is provided here for your reference, however its accuracy is enforced directly by
59 /// [`ChannelManager`] using the values you previously provided to
60 /// [`ChannelManager::create_inbound_payment`] or
61 /// [`ChannelManager::create_inbound_payment_for_hash`].
63 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
64 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
65 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
66 payment_secret: PaymentSecret,
68 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
69 /// (the payee) providing a preimage.
70 SpontaneousPayment(PaymentPreimage),
73 impl_writeable_tlv_based_enum!(PaymentPurpose,
74 (0, InvoicePayment) => {
75 (0, payment_preimage, option),
76 (2, payment_secret, required),
78 (2, SpontaneousPayment)
81 #[derive(Clone, Debug, PartialEq, Eq)]
82 /// The reason the channel was closed. See individual variants more details.
83 pub enum ClosureReason {
84 /// Closure generated from receiving a peer error message.
86 /// Our counterparty may have broadcasted their latest commitment state, and we have
88 CounterpartyForceClosed {
89 /// The error which the peer sent us.
91 /// The string should be sanitized before it is used (e.g emitted to logs
92 /// or printed to stdout). Otherwise, a well crafted error message may exploit
93 /// a security vulnerability in the terminal emulator or the logging subsystem.
96 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
98 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
100 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
101 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
102 //TODO: split between CounterpartyInitiated/LocallyInitiated
104 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
105 /// commitment transaction came from our counterparty, but it may also have come from
106 /// a copy of our own `ChannelMonitor`.
107 CommitmentTxConfirmed,
108 /// The funding transaction failed to confirm in a timely manner on an inbound channel.
110 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
112 /// A developer-readable error message which we generated.
115 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
116 /// forget the channel entirely - we can attempt again if the peer reconnects.
118 /// This includes cases where we restarted prior to funding completion, including prior to the
119 /// initial [`ChannelMonitor`] persistence completing.
121 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
122 /// peer because of mutual incompatibility between us and our channel counterparty.
124 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
126 /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
127 /// the [`ChannelManager`] deserialized.
129 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
130 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
131 OutdatedChannelManager
134 impl core::fmt::Display for ClosureReason {
135 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
136 f.write_str("Channel closed because ")?;
138 ClosureReason::CounterpartyForceClosed { peer_msg } => {
139 f.write_str("counterparty force-closed with message ")?;
140 f.write_str(&peer_msg)
142 ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
143 ClosureReason::CooperativeClosure => f.write_str("the channel was cooperatively closed"),
144 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
145 ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
146 ClosureReason::ProcessingError { err } => {
147 f.write_str("of an exception: ")?;
150 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
151 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
156 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
157 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
158 (1, FundingTimedOut) => {},
159 (2, HolderForceClosed) => {},
160 (6, CommitmentTxConfirmed) => {},
161 (4, CooperativeClosure) => {},
162 (8, ProcessingError) => { (1, err, required) },
163 (10, DisconnectedPeer) => {},
164 (12, OutdatedChannelManager) => {},
167 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
168 #[derive(Clone, Debug, PartialEq, Eq)]
169 pub enum HTLCDestination {
170 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
171 /// there is insufficient capacity in our outbound channel.
173 /// The `node_id` of the next node. For backwards compatibility, this field is
174 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
175 /// counterparty node information.
176 node_id: Option<PublicKey>,
177 /// The outgoing `channel_id` between us and the next node.
178 channel_id: [u8; 32],
180 /// Scenario where we are unsure of the next node to forward the HTLC to.
182 /// Short channel id we are requesting to forward an HTLC to.
183 requested_forward_scid: u64,
185 /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
188 /// Short channel id we are requesting to forward an HTLC to.
189 requested_forward_scid: u64
191 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
192 /// but is invalid for some reason, so we reject it.
194 /// Some of the reasons may include:
196 /// * Expected MPP amount to claim does not equal HTLC total
197 /// * Claimable amount does not match expected amount
199 /// The payment hash of the payment we attempted to process.
200 payment_hash: PaymentHash
204 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
205 (0, NextHopChannel) => {
206 (0, node_id, required),
207 (2, channel_id, required),
209 (1, InvalidForward) => {
210 (0, requested_forward_scid, required),
212 (2, UnknownNextHop) => {
213 (0, requested_forward_scid, required),
215 (4, FailedPayment) => {
216 (0, payment_hash, required),
221 /// A descriptor used to sign for a commitment transaction's anchor output.
222 #[derive(Clone, Debug)]
223 pub struct AnchorDescriptor {
224 /// A unique identifier used along with `channel_value_satoshis` to re-derive the
225 /// [`InMemorySigner`] required to sign `input`.
227 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
228 pub channel_keys_id: [u8; 32],
229 /// The value in satoshis of the channel we're attempting to spend the anchor output of. This is
230 /// used along with `channel_keys_id` to re-derive the [`InMemorySigner`] required to sign
233 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
234 pub channel_value_satoshis: u64,
235 /// The transaction input's outpoint corresponding to the commitment transaction's anchor
237 pub outpoint: OutPoint,
241 /// Represents the different types of transactions, originating from LDK, to be bumped.
242 #[derive(Clone, Debug)]
243 pub enum BumpTransactionEvent {
244 /// Indicates that a channel featuring anchor outputs is to be closed by broadcasting the local
245 /// commitment transaction. Since commitment transactions have a static feerate pre-agreed upon,
246 /// they may need additional fees to be attached through a child transaction using the popular
247 /// [Child-Pays-For-Parent](https://bitcoinops.org/en/topics/cpfp) fee bumping technique. This
248 /// child transaction must include the anchor input described within `anchor_descriptor` along
249 /// with additional inputs to meet the target feerate. Failure to meet the target feerate
250 /// decreases the confirmation odds of the transaction package (which includes the commitment
251 /// and child anchor transactions), possibly resulting in a loss of funds. Once the transaction
252 /// is constructed, it must be fully signed for and broadcast by the consumer of the event
253 /// along with the `commitment_tx` enclosed. Note that the `commitment_tx` must always be
254 /// broadcast first, as the child anchor transaction depends on it.
256 /// The consumer should be able to sign for any of the additional inputs included within the
257 /// child anchor transaction. To sign its anchor input, an [`InMemorySigner`] should be
258 /// re-derived through [`KeysManager::derive_channel_keys`] with the help of
259 /// [`AnchorDescriptor::channel_keys_id`] and [`AnchorDescriptor::channel_value_satoshis`].
261 /// It is possible to receive more than one instance of this event if a valid child anchor
262 /// transaction is never broadcast or is but not with a sufficient fee to be mined. Care should
263 /// be taken by the consumer of the event to ensure any future iterations of the child anchor
264 /// transaction adhere to the [Replace-By-Fee
265 /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
266 /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
267 /// these events is not user-controlled, users may ignore/drop the event if they are no longer
268 /// able to commit external confirmed funds to the child anchor transaction.
270 /// The set of `pending_htlcs` on the commitment transaction to be broadcast can be inspected to
271 /// determine whether a significant portion of the channel's funds are allocated to HTLCs,
272 /// enabling users to make their own decisions regarding the importance of the commitment
273 /// transaction's confirmation. Note that this is not required, but simply exists as an option
274 /// for users to override LDK's behavior. On commitments with no HTLCs (indicated by those with
275 /// an empty `pending_htlcs`), confirmation of the commitment transaction can be considered to
278 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
279 /// [`KeysManager::derive_channel_keys`]: crate::chain::keysinterface::KeysManager::derive_channel_keys
281 /// The target feerate that the transaction package, which consists of the commitment
282 /// transaction and the to-be-crafted child anchor transaction, must meet.
283 package_target_feerate_sat_per_1000_weight: u32,
284 /// The channel's commitment transaction to bump the fee of. This transaction should be
285 /// broadcast along with the anchor transaction constructed as a result of consuming this
287 commitment_tx: Transaction,
288 /// The absolute fee in satoshis of the commitment transaction. This can be used along the
289 /// with weight of the commitment transaction to determine its feerate.
290 commitment_tx_fee_satoshis: u64,
291 /// The descriptor to sign the anchor input of the anchor transaction constructed as a
292 /// result of consuming this event.
293 anchor_descriptor: AnchorDescriptor,
294 /// The set of pending HTLCs on the commitment transaction that need to be resolved once the
295 /// commitment transaction confirms.
296 pending_htlcs: Vec<HTLCOutputInCommitment>,
300 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
301 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
302 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
303 /// intercepts in upcoming work.
304 enum InterceptNextHop {
306 requested_next_hop_scid: u64,
310 impl_writeable_tlv_based_enum!(InterceptNextHop,
312 (0, requested_next_hop_scid, required),
316 /// An Event which you should probably take some action in response to.
318 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
319 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
320 /// written as it makes no sense to respond to it after reconnecting to peers).
321 #[derive(Clone, Debug)]
323 /// Used to indicate that the client should generate a funding transaction with the given
324 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
325 /// Generated in [`ChannelManager`] message handling.
326 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
327 /// counterparty can steal your funds!
329 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
330 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
331 FundingGenerationReady {
332 /// The random channel_id we picked which you'll need to pass into
333 /// [`ChannelManager::funding_transaction_generated`].
335 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
336 temporary_channel_id: [u8; 32],
337 /// The counterparty's node_id, which you'll need to pass back into
338 /// [`ChannelManager::funding_transaction_generated`].
340 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
341 counterparty_node_id: PublicKey,
342 /// The value, in satoshis, that the output should have.
343 channel_value_satoshis: u64,
344 /// The script which should be used in the transaction output.
345 output_script: Script,
346 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or a
347 /// random value for an inbound channel. This may be zero for objects serialized with LDK
348 /// versions prior to 0.0.113.
350 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
351 user_channel_id: u128,
353 /// Indicates that we've been offered a payment and it needs to be claimed via calling
354 /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
356 /// Note that if the preimage is not known, you should call
357 /// [`ChannelManager::fail_htlc_backwards`] to free up resources for this HTLC and avoid
358 /// network congestion.
359 /// If you fail to call either [`ChannelManager::claim_funds`] or
360 /// [`ChannelManager::fail_htlc_backwards`] within the HTLC's timeout, the HTLC will be
361 /// automatically failed.
364 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
365 /// `PaymentClaimable` events may be generated for the same payment.
368 /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
370 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
371 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
373 /// The node that will receive the payment after it has been claimed.
374 /// This is useful to identify payments received via [phantom nodes].
375 /// This field will always be filled in when the event was generated by LDK versions
376 /// 0.0.113 and above.
378 /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
379 receiver_node_id: Option<PublicKey>,
380 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
381 /// not stop you from registering duplicate payment hashes for inbound payments.
382 payment_hash: PaymentHash,
383 /// The value, in thousandths of a satoshi, that this payment is for.
385 /// Information for claiming this received payment, based on whether the purpose of the
386 /// payment is to pay an invoice or to send a spontaneous payment.
387 purpose: PaymentPurpose,
388 /// The `channel_id` indicating over which channel we received the payment.
389 via_channel_id: Option<[u8; 32]>,
390 /// The `user_channel_id` indicating over which channel we received the payment.
391 via_user_channel_id: Option<u128>,
393 /// Indicates a payment has been claimed and we've received money!
395 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
396 /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
397 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
398 /// [`Event::PaymentClaimable`] event.
401 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
402 /// `PaymentClaimable` events may be generated for the same payment. If you then call
403 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
404 /// multiple `PaymentClaimed` events.
406 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
408 /// The node that received the payment.
409 /// This is useful to identify payments which were received via [phantom nodes].
410 /// This field will always be filled in when the event was generated by LDK versions
411 /// 0.0.113 and above.
413 /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
414 receiver_node_id: Option<PublicKey>,
415 /// The payment hash of the claimed payment. Note that LDK will not stop you from
416 /// registering duplicate payment hashes for inbound payments.
417 payment_hash: PaymentHash,
418 /// The value, in thousandths of a satoshi, that this payment is for.
420 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
421 /// spontaneous payment.
422 purpose: PaymentPurpose,
424 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
425 /// and we got back the payment preimage for it).
427 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
428 /// event. In this situation, you SHOULD treat this payment as having succeeded.
430 /// The id returned by [`ChannelManager::send_payment`] and used with
431 /// [`ChannelManager::retry_payment`].
433 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
434 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
435 payment_id: Option<PaymentId>,
436 /// The preimage to the hash given to ChannelManager::send_payment.
437 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
438 /// store it somehow!
439 payment_preimage: PaymentPreimage,
440 /// The hash that was given to [`ChannelManager::send_payment`].
442 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
443 payment_hash: PaymentHash,
444 /// The total fee which was spent at intermediate hops in this payment, across all paths.
446 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
447 /// overpayment to the recipient node.
449 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
450 /// overstate the amount paid, though this is unlikely.
452 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
453 fee_paid_msat: Option<u64>,
455 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
456 /// provide failure information for each MPP part in the payment.
458 /// This event is provided once there are no further pending HTLCs for the payment and the
459 /// payment is no longer retryable due to [`ChannelManager::abandon_payment`] having been
460 /// called for the corresponding payment.
462 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
464 /// The id returned by [`ChannelManager::send_payment`] and used with
465 /// [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`].
467 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
468 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
469 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
470 payment_id: PaymentId,
471 /// The hash that was given to [`ChannelManager::send_payment`].
473 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
474 payment_hash: PaymentHash,
476 /// Indicates that a path for an outbound payment was successful.
478 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
479 /// [`Event::PaymentSent`] for obtaining the payment preimage.
480 PaymentPathSuccessful {
481 /// The id returned by [`ChannelManager::send_payment`] and used with
482 /// [`ChannelManager::retry_payment`].
484 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
485 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
486 payment_id: PaymentId,
487 /// The hash that was given to [`ChannelManager::send_payment`].
489 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
490 payment_hash: Option<PaymentHash>,
491 /// The payment path that was successful.
493 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
496 /// Indicates an outbound HTLC we sent failed. Probably some intermediary node dropped
497 /// something. You may wish to retry with a different route.
499 /// If you have given up retrying this payment and wish to fail it, you MUST call
500 /// [`ChannelManager::abandon_payment`] at least once for a given [`PaymentId`] or memory
501 /// related to payment tracking will leak.
503 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
504 /// [`Event::PaymentFailed`] and [`all_paths_failed`].
506 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
507 /// [`all_paths_failed`]: Self::PaymentPathFailed::all_paths_failed
509 /// The id returned by [`ChannelManager::send_payment`] and used with
510 /// [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`].
512 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
513 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
514 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
515 payment_id: Option<PaymentId>,
516 /// The hash that was given to [`ChannelManager::send_payment`].
518 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
519 payment_hash: PaymentHash,
520 /// Indicates the payment was rejected for some reason by the recipient. This implies that
521 /// the payment has failed, not just the route in question. If this is not set, you may
522 /// retry the payment via a different route.
523 payment_failed_permanently: bool,
524 /// Any failure information conveyed via the Onion return packet by a node along the failed
527 /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into
528 /// account the update.
530 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
531 network_update: Option<NetworkUpdate>,
532 /// For both single-path and multi-path payments, this is set if all paths of the payment have
533 /// failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the
534 /// larger MPP payment were still in flight when this event was generated.
536 /// Note that if you are retrying individual MPP parts, using this value to determine if a
537 /// payment has fully failed is race-y. Because multiple failures can happen prior to events
538 /// being processed, you may retry in response to a first failure, with a second failure
539 /// (with `all_paths_failed` set) still pending. Then, when the second failure is processed
540 /// you will see `all_paths_failed` set even though the retry of the first failure still
541 /// has an associated in-flight HTLC. See (1) for an example of such a failure.
543 /// If you wish to retry individual MPP parts and learn when a payment has failed, you must
544 /// call [`ChannelManager::abandon_payment`] and wait for a [`Event::PaymentFailed`] event.
546 /// (1) <https://github.com/lightningdevkit/rust-lightning/issues/1164>
548 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
549 all_paths_failed: bool,
550 /// The payment path that failed.
552 /// The channel responsible for the failed payment path.
554 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
555 /// may not refer to a channel in the public network graph. These aliases may also collide
556 /// with channels in the public network graph.
558 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
559 /// retried. May be `None` for older [`Event`] serializations.
560 short_channel_id: Option<u64>,
561 /// Parameters needed to compute a new [`Route`] when retrying the failed payment path.
563 /// See [`find_route`] for details.
565 /// [`Route`]: crate::routing::router::Route
566 /// [`find_route`]: crate::routing::router::find_route
567 retry: Option<RouteParameters>,
569 error_code: Option<u16>,
571 error_data: Option<Vec<u8>>,
573 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
575 /// The id returned by [`ChannelManager::send_probe`].
577 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
578 payment_id: PaymentId,
579 /// The hash generated by [`ChannelManager::send_probe`].
581 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
582 payment_hash: PaymentHash,
583 /// The payment path that was successful.
586 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
588 /// The id returned by [`ChannelManager::send_probe`].
590 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
591 payment_id: PaymentId,
592 /// The hash generated by [`ChannelManager::send_probe`].
594 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
595 payment_hash: PaymentHash,
596 /// The payment path that failed.
598 /// The channel responsible for the failed probe.
600 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
601 /// may not refer to a channel in the public network graph. These aliases may also collide
602 /// with channels in the public network graph.
603 short_channel_id: Option<u64>,
605 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
606 /// a time in the future.
608 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
609 PendingHTLCsForwardable {
610 /// The minimum amount of time that should be waited prior to calling
611 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
612 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
613 /// now + 5*time_forwardable).
614 time_forwardable: Duration,
616 /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
617 /// you've encoded an intercept scid in the receiver's invoice route hints using
618 /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
620 /// [`ChannelManager::forward_intercepted_htlc`] or
621 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
622 /// their docs for more information.
624 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
625 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
626 /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
627 /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
629 /// An id to help LDK identify which HTLC is being forwarded or failed.
630 intercept_id: InterceptId,
631 /// The fake scid that was programmed as the next hop's scid, generated using
632 /// [`ChannelManager::get_intercept_scid`].
634 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
635 requested_next_hop_scid: u64,
636 /// The payment hash used for this HTLC.
637 payment_hash: PaymentHash,
638 /// How many msats were received on the inbound edge of this HTLC.
639 inbound_amount_msat: u64,
640 /// How many msats the payer intended to route to the next node. Depending on the reason you are
641 /// intercepting this payment, you might take a fee by forwarding less than this amount.
643 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
644 /// check that whatever fee you want has been included here or subtract it as required. Further,
645 /// LDK will not stop you from forwarding more than you received.
646 expected_outbound_amount_msat: u64,
648 /// Used to indicate that an output which you should know how to spend was confirmed on chain
649 /// and is now spendable.
650 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
651 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
652 /// somewhere and spend them when you create on-chain transactions.
654 /// The outputs which you should store as spendable by you.
655 outputs: Vec<SpendableOutputDescriptor>,
657 /// This event is generated when a payment has been successfully forwarded through us and a
658 /// forwarding fee earned.
660 /// The incoming channel between the previous node and us. This is only `None` for events
661 /// generated or serialized by versions prior to 0.0.107.
662 prev_channel_id: Option<[u8; 32]>,
663 /// The outgoing channel between the next node and us. This is only `None` for events
664 /// generated or serialized by versions prior to 0.0.107.
665 next_channel_id: Option<[u8; 32]>,
666 /// The fee, in milli-satoshis, which was earned as a result of the payment.
668 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
669 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
670 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
671 /// claimed the full value in millisatoshis from the source. In this case,
672 /// `claim_from_onchain_tx` will be set.
674 /// If the channel which sent us the payment has been force-closed, we will claim the funds
675 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
676 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
677 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
679 fee_earned_msat: Option<u64>,
680 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
682 claim_from_onchain_tx: bool,
684 /// Used to indicate that a channel with the given `channel_id` is ready to
685 /// be used. This event is emitted either when the funding transaction has been confirmed
686 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
689 /// The channel_id of the channel that is ready.
690 channel_id: [u8; 32],
691 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
692 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
693 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
694 /// `user_channel_id` will be randomized for an inbound channel.
696 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
697 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
698 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
699 user_channel_id: u128,
700 /// The node_id of the channel counterparty.
701 counterparty_node_id: PublicKey,
702 /// The features that this channel will operate with.
703 channel_type: ChannelTypeFeatures,
705 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
706 /// process of closure.
708 /// The channel_id of the channel which has been closed. Note that on-chain transactions
709 /// resolving the channel are likely still awaiting confirmation.
710 channel_id: [u8; 32],
711 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
712 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
713 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
714 /// `user_channel_id` will be randomized for inbound channels.
715 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
716 /// zero for objects serialized with LDK versions prior to 0.0.102.
718 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
719 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
720 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
721 user_channel_id: u128,
722 /// The reason the channel was closed.
723 reason: ClosureReason
725 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
726 /// inputs for another purpose.
728 /// The channel_id of the channel which has been closed.
729 channel_id: [u8; 32],
730 /// The full transaction received from the user
731 transaction: Transaction
733 /// Indicates a request to open a new channel by a peer.
735 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the
736 /// request, call [`ChannelManager::force_close_without_broadcasting_txn`].
738 /// The event is only triggered when a new open channel request is received and the
739 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
741 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
742 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
743 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
745 /// The temporary channel ID of the channel requested to be opened.
747 /// When responding to the request, the `temporary_channel_id` should be passed
748 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
749 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
751 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
752 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
753 temporary_channel_id: [u8; 32],
754 /// The node_id of the counterparty requesting to open the channel.
756 /// When responding to the request, the `counterparty_node_id` should be passed
757 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
758 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
761 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
762 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
763 counterparty_node_id: PublicKey,
764 /// The channel value of the requested channel.
765 funding_satoshis: u64,
766 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
768 /// The features that this channel will operate with. If you reject the channel, a
769 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
772 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
773 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
776 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
777 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
778 /// 0.0.107. Channels setting this type also need to get manually accepted via
779 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
780 /// or will be rejected otherwise.
782 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
783 channel_type: ChannelTypeFeatures,
785 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
788 /// Some scenarios where this event may be sent include:
789 /// * Insufficient capacity in the outbound channel
790 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
791 /// * When an unknown SCID is requested for forwarding a payment.
792 /// * Claiming an amount for an MPP payment that exceeds the HTLC total
793 /// * The HTLC has timed out
795 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
796 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
798 /// The channel over which the HTLC was received.
799 prev_channel_id: [u8; 32],
800 /// Destination of the HTLC that failed to be processed.
801 failed_next_destination: HTLCDestination,
804 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
805 /// requires confirmed external funds to be readily available to spend.
807 /// LDK does not currently generate this event. It is limited to the scope of channels with
808 /// anchor outputs, which will be introduced in a future release.
809 BumpTransaction(BumpTransactionEvent),
812 impl Writeable for Event {
813 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
815 &Event::FundingGenerationReady { .. } => {
817 // We never write out FundingGenerationReady events as, upon disconnection, peers
818 // drop any channels which have not yet exchanged funding_signed.
820 &Event::PaymentClaimable { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id } => {
822 let mut payment_secret = None;
823 let payment_preimage;
825 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
826 payment_secret = Some(secret);
827 payment_preimage = *preimage;
829 PaymentPurpose::SpontaneousPayment(preimage) => {
830 payment_preimage = Some(*preimage);
833 write_tlv_fields!(writer, {
834 (0, payment_hash, required),
835 (1, receiver_node_id, option),
836 (2, payment_secret, option),
837 (3, via_channel_id, option),
838 (4, amount_msat, required),
839 (5, via_user_channel_id, option),
840 (6, 0u64, required), // user_payment_id required for compatibility with 0.0.103 and earlier
841 (8, payment_preimage, option),
844 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
846 write_tlv_fields!(writer, {
847 (0, payment_preimage, required),
848 (1, payment_hash, required),
849 (3, payment_id, option),
850 (5, fee_paid_msat, option),
853 &Event::PaymentPathFailed {
854 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update,
855 ref all_paths_failed, ref path, ref short_channel_id, ref retry,
863 error_code.write(writer)?;
865 error_data.write(writer)?;
866 write_tlv_fields!(writer, {
867 (0, payment_hash, required),
868 (1, network_update, option),
869 (2, payment_failed_permanently, required),
870 (3, all_paths_failed, required),
871 (5, *path, vec_type),
872 (7, short_channel_id, option),
874 (11, payment_id, option),
877 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
879 // Note that we now ignore these on the read end as we'll re-generate them in
880 // ChannelManager, we write them here only for backwards compatibility.
882 &Event::SpendableOutputs { ref outputs } => {
884 write_tlv_fields!(writer, {
885 (0, WithoutLength(outputs), required),
888 &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
890 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
891 write_tlv_fields!(writer, {
892 (0, intercept_id, required),
893 (2, intercept_scid, required),
894 (4, payment_hash, required),
895 (6, inbound_amount_msat, required),
896 (8, expected_outbound_amount_msat, required),
899 &Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
901 write_tlv_fields!(writer, {
902 (0, fee_earned_msat, option),
903 (1, prev_channel_id, option),
904 (2, claim_from_onchain_tx, required),
905 (3, next_channel_id, option),
908 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
910 // `user_channel_id` used to be a single u64 value. In order to remain backwards
911 // compatible with versions prior to 0.0.113, the u128 is serialized as two
912 // separate u64 values.
913 let user_channel_id_low = *user_channel_id as u64;
914 let user_channel_id_high = (*user_channel_id >> 64) as u64;
915 write_tlv_fields!(writer, {
916 (0, channel_id, required),
917 (1, user_channel_id_low, required),
918 (2, reason, required),
919 (3, user_channel_id_high, required),
922 &Event::DiscardFunding { ref channel_id, ref transaction } => {
924 write_tlv_fields!(writer, {
925 (0, channel_id, required),
926 (2, transaction, required)
929 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
931 write_tlv_fields!(writer, {
932 (0, payment_id, required),
933 (2, payment_hash, option),
937 &Event::PaymentFailed { ref payment_id, ref payment_hash } => {
939 write_tlv_fields!(writer, {
940 (0, payment_id, required),
941 (2, payment_hash, required),
944 &Event::OpenChannelRequest { .. } => {
946 // We never write the OpenChannelRequest events as, upon disconnection, peers
947 // drop any channels which have not yet exchanged funding_signed.
949 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id } => {
951 write_tlv_fields!(writer, {
952 (0, payment_hash, required),
953 (1, receiver_node_id, option),
954 (2, purpose, required),
955 (4, amount_msat, required),
958 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
960 write_tlv_fields!(writer, {
961 (0, payment_id, required),
962 (2, payment_hash, required),
966 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
968 write_tlv_fields!(writer, {
969 (0, payment_id, required),
970 (2, payment_hash, required),
971 (4, *path, vec_type),
972 (6, short_channel_id, option),
975 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
977 write_tlv_fields!(writer, {
978 (0, prev_channel_id, required),
979 (2, failed_next_destination, required),
983 &Event::BumpTransaction(ref event)=> {
986 // We never write the ChannelClose events as they'll be replayed upon restarting
987 // anyway if the commitment transaction remains unconfirmed.
988 BumpTransactionEvent::ChannelClose { .. } => {}
991 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
993 write_tlv_fields!(writer, {
994 (0, channel_id, required),
995 (2, user_channel_id, required),
996 (4, counterparty_node_id, required),
997 (6, channel_type, required),
1000 // Note that, going forward, all new events must only write data inside of
1001 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
1002 // data via `write_tlv_fields`.
1007 impl MaybeReadable for Event {
1008 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
1009 match Readable::read(reader)? {
1010 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
1011 // unlike all other events, thus we return immediately here.
1015 let mut payment_hash = PaymentHash([0; 32]);
1016 let mut payment_preimage = None;
1017 let mut payment_secret = None;
1018 let mut amount_msat = 0;
1019 let mut receiver_node_id = None;
1020 let mut _user_payment_id = None::<u64>; // For compatibility with 0.0.103 and earlier
1021 let mut via_channel_id = None;
1022 let mut via_user_channel_id = None;
1023 read_tlv_fields!(reader, {
1024 (0, payment_hash, required),
1025 (1, receiver_node_id, option),
1026 (2, payment_secret, option),
1027 (3, via_channel_id, option),
1028 (4, amount_msat, required),
1029 (5, via_user_channel_id, option),
1030 (6, _user_payment_id, option),
1031 (8, payment_preimage, option),
1033 let purpose = match payment_secret {
1034 Some(secret) => PaymentPurpose::InvoicePayment {
1036 payment_secret: secret
1038 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1039 None => return Err(msgs::DecodeError::InvalidValue),
1041 Ok(Some(Event::PaymentClaimable {
1047 via_user_channel_id,
1054 let mut payment_preimage = PaymentPreimage([0; 32]);
1055 let mut payment_hash = None;
1056 let mut payment_id = None;
1057 let mut fee_paid_msat = None;
1058 read_tlv_fields!(reader, {
1059 (0, payment_preimage, required),
1060 (1, payment_hash, option),
1061 (3, payment_id, option),
1062 (5, fee_paid_msat, option),
1064 if payment_hash.is_none() {
1065 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
1067 Ok(Some(Event::PaymentSent {
1070 payment_hash: payment_hash.unwrap(),
1079 let error_code = Readable::read(reader)?;
1081 let error_data = Readable::read(reader)?;
1082 let mut payment_hash = PaymentHash([0; 32]);
1083 let mut payment_failed_permanently = false;
1084 let mut network_update = None;
1085 let mut all_paths_failed = Some(true);
1086 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1087 let mut short_channel_id = None;
1088 let mut retry = None;
1089 let mut payment_id = None;
1090 read_tlv_fields!(reader, {
1091 (0, payment_hash, required),
1092 (1, network_update, ignorable),
1093 (2, payment_failed_permanently, required),
1094 (3, all_paths_failed, option),
1095 (5, path, vec_type),
1096 (7, short_channel_id, option),
1098 (11, payment_id, option),
1100 Ok(Some(Event::PaymentPathFailed {
1103 payment_failed_permanently,
1105 all_paths_failed: all_paths_failed.unwrap(),
1106 path: path.unwrap(),
1120 let mut outputs = WithoutLength(Vec::new());
1121 read_tlv_fields!(reader, {
1122 (0, outputs, required),
1124 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
1129 let mut payment_hash = PaymentHash([0; 32]);
1130 let mut intercept_id = InterceptId([0; 32]);
1131 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1132 let mut inbound_amount_msat = 0;
1133 let mut expected_outbound_amount_msat = 0;
1134 read_tlv_fields!(reader, {
1135 (0, intercept_id, required),
1136 (2, requested_next_hop_scid, required),
1137 (4, payment_hash, required),
1138 (6, inbound_amount_msat, required),
1139 (8, expected_outbound_amount_msat, required),
1141 let next_scid = match requested_next_hop_scid {
1142 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1144 Ok(Some(Event::HTLCIntercepted {
1146 requested_next_hop_scid: next_scid,
1147 inbound_amount_msat,
1148 expected_outbound_amount_msat,
1154 let mut fee_earned_msat = None;
1155 let mut prev_channel_id = None;
1156 let mut claim_from_onchain_tx = false;
1157 let mut next_channel_id = None;
1158 read_tlv_fields!(reader, {
1159 (0, fee_earned_msat, option),
1160 (1, prev_channel_id, option),
1161 (2, claim_from_onchain_tx, required),
1162 (3, next_channel_id, option),
1164 Ok(Some(Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id }))
1170 let mut channel_id = [0; 32];
1171 let mut reason = None;
1172 let mut user_channel_id_low_opt: Option<u64> = None;
1173 let mut user_channel_id_high_opt: Option<u64> = None;
1174 read_tlv_fields!(reader, {
1175 (0, channel_id, required),
1176 (1, user_channel_id_low_opt, option),
1177 (2, reason, ignorable),
1178 (3, user_channel_id_high_opt, option),
1180 if reason.is_none() { return Ok(None); }
1182 // `user_channel_id` used to be a single u64 value. In order to remain
1183 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1184 // as two separate u64 values.
1185 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1186 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1188 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: reason.unwrap() }))
1194 let mut channel_id = [0; 32];
1195 let mut transaction = Transaction{ version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
1196 read_tlv_fields!(reader, {
1197 (0, channel_id, required),
1198 (2, transaction, required),
1200 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1206 let mut payment_id = PaymentId([0; 32]);
1207 let mut payment_hash = None;
1208 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1209 read_tlv_fields!(reader, {
1210 (0, payment_id, required),
1211 (2, payment_hash, option),
1212 (4, path, vec_type),
1214 Ok(Some(Event::PaymentPathSuccessful {
1217 path: path.unwrap(),
1224 let mut payment_hash = PaymentHash([0; 32]);
1225 let mut payment_id = PaymentId([0; 32]);
1226 read_tlv_fields!(reader, {
1227 (0, payment_id, required),
1228 (2, payment_hash, required),
1230 Ok(Some(Event::PaymentFailed {
1238 // Value 17 is used for `Event::OpenChannelRequest`.
1243 let mut payment_hash = PaymentHash([0; 32]);
1244 let mut purpose = None;
1245 let mut amount_msat = 0;
1246 let mut receiver_node_id = None;
1247 read_tlv_fields!(reader, {
1248 (0, payment_hash, required),
1249 (1, receiver_node_id, option),
1250 (2, purpose, ignorable),
1251 (4, amount_msat, required),
1253 if purpose.is_none() { return Ok(None); }
1254 Ok(Some(Event::PaymentClaimed {
1257 purpose: purpose.unwrap(),
1265 let mut payment_id = PaymentId([0; 32]);
1266 let mut payment_hash = PaymentHash([0; 32]);
1267 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1268 read_tlv_fields!(reader, {
1269 (0, payment_id, required),
1270 (2, payment_hash, required),
1271 (4, path, vec_type),
1273 Ok(Some(Event::ProbeSuccessful {
1276 path: path.unwrap(),
1283 let mut payment_id = PaymentId([0; 32]);
1284 let mut payment_hash = PaymentHash([0; 32]);
1285 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1286 let mut short_channel_id = None;
1287 read_tlv_fields!(reader, {
1288 (0, payment_id, required),
1289 (2, payment_hash, required),
1290 (4, path, vec_type),
1291 (6, short_channel_id, option),
1293 Ok(Some(Event::ProbeFailed {
1296 path: path.unwrap(),
1304 let mut prev_channel_id = [0; 32];
1305 let mut failed_next_destination_opt = None;
1306 read_tlv_fields!(reader, {
1307 (0, prev_channel_id, required),
1308 (2, failed_next_destination_opt, ignorable),
1310 if let Some(failed_next_destination) = failed_next_destination_opt {
1311 Ok(Some(Event::HTLCHandlingFailed {
1313 failed_next_destination,
1316 // If we fail to read a `failed_next_destination` assume it's because
1317 // `MaybeReadable::read` returned `Ok(None)`, though it's also possible we
1318 // were simply missing the field.
1327 let mut channel_id = [0; 32];
1328 let mut user_channel_id: u128 = 0;
1329 let mut counterparty_node_id = OptionDeserWrapper(None);
1330 let mut channel_type = OptionDeserWrapper(None);
1331 read_tlv_fields!(reader, {
1332 (0, channel_id, required),
1333 (2, user_channel_id, required),
1334 (4, counterparty_node_id, required),
1335 (6, channel_type, required),
1338 Ok(Some(Event::ChannelReady {
1341 counterparty_node_id: counterparty_node_id.0.unwrap(),
1342 channel_type: channel_type.0.unwrap()
1347 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1348 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1350 x if x % 2 == 1 => {
1351 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1352 // which prefixes the whole thing with a length BigSize. Because the event is
1353 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1354 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1355 // exactly the number of bytes specified, ignoring them entirely.
1356 let tlv_len: BigSize = Readable::read(reader)?;
1357 FixedLengthReader::new(reader, tlv_len.0)
1358 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1361 _ => Err(msgs::DecodeError::InvalidValue)
1366 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1367 /// broadcast to most peers).
1368 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1369 #[derive(Clone, Debug)]
1370 pub enum MessageSendEvent {
1371 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1372 /// message provided to the given peer.
1374 /// The node_id of the node which should receive this message
1376 /// The message which should be sent.
1377 msg: msgs::AcceptChannel,
1379 /// Used to indicate that we've initiated a channel open and should send the open_channel
1380 /// message provided to the given peer.
1382 /// The node_id of the node which should receive this message
1384 /// The message which should be sent.
1385 msg: msgs::OpenChannel,
1387 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1388 SendFundingCreated {
1389 /// The node_id of the node which should receive this message
1391 /// The message which should be sent.
1392 msg: msgs::FundingCreated,
1394 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1396 /// The node_id of the node which should receive this message
1398 /// The message which should be sent.
1399 msg: msgs::FundingSigned,
1401 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1403 /// The node_id of the node which should receive these message(s)
1405 /// The channel_ready message which should be sent.
1406 msg: msgs::ChannelReady,
1408 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1409 SendAnnouncementSignatures {
1410 /// The node_id of the node which should receive these message(s)
1412 /// The announcement_signatures message which should be sent.
1413 msg: msgs::AnnouncementSignatures,
1415 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1416 /// message should be sent to the peer with the given node_id.
1418 /// The node_id of the node which should receive these message(s)
1420 /// The update messages which should be sent. ALL messages in the struct should be sent!
1421 updates: msgs::CommitmentUpdate,
1423 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1425 /// The node_id of the node which should receive this message
1427 /// The message which should be sent.
1428 msg: msgs::RevokeAndACK,
1430 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1432 /// The node_id of the node which should receive this message
1434 /// The message which should be sent.
1435 msg: msgs::ClosingSigned,
1437 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1439 /// The node_id of the node which should receive this message
1441 /// The message which should be sent.
1442 msg: msgs::Shutdown,
1444 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1445 SendChannelReestablish {
1446 /// The node_id of the node which should receive this message
1448 /// The message which should be sent.
1449 msg: msgs::ChannelReestablish,
1451 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1452 /// initial connection to ensure our peers know about our channels.
1453 SendChannelAnnouncement {
1454 /// The node_id of the node which should receive this message
1456 /// The channel_announcement which should be sent.
1457 msg: msgs::ChannelAnnouncement,
1458 /// The followup channel_update which should be sent.
1459 update_msg: msgs::ChannelUpdate,
1461 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1462 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1464 /// Note that after doing so, you very likely (unless you did so very recently) want to
1465 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1466 /// ensures that any nodes which see our channel_announcement also have a relevant
1467 /// node_announcement, including relevant feature flags which may be important for routing
1468 /// through or to us.
1470 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1471 BroadcastChannelAnnouncement {
1472 /// The channel_announcement which should be sent.
1473 msg: msgs::ChannelAnnouncement,
1474 /// The followup channel_update which should be sent.
1475 update_msg: msgs::ChannelUpdate,
1477 /// Used to indicate that a channel_update should be broadcast to all peers.
1478 BroadcastChannelUpdate {
1479 /// The channel_update which should be sent.
1480 msg: msgs::ChannelUpdate,
1482 /// Used to indicate that a channel_update should be sent to a single peer.
1483 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1484 /// private channel and we shouldn't be informing all of our peers of channel parameters.
1486 /// The node_id of the node which should receive this message
1488 /// The channel_update which should be sent.
1489 msg: msgs::ChannelUpdate,
1491 /// Broadcast an error downstream to be handled
1493 /// The node_id of the node which should receive this message
1495 /// The action which should be taken.
1496 action: msgs::ErrorAction
1498 /// Query a peer for channels with funding transaction UTXOs in a block range.
1499 SendChannelRangeQuery {
1500 /// The node_id of this message recipient
1502 /// The query_channel_range which should be sent.
1503 msg: msgs::QueryChannelRange,
1505 /// Request routing gossip messages from a peer for a list of channels identified by
1506 /// their short_channel_ids.
1508 /// The node_id of this message recipient
1510 /// The query_short_channel_ids which should be sent.
1511 msg: msgs::QueryShortChannelIds,
1513 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1514 /// emitted during processing of the query.
1515 SendReplyChannelRange {
1516 /// The node_id of this message recipient
1518 /// The reply_channel_range which should be sent.
1519 msg: msgs::ReplyChannelRange,
1521 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1522 /// enable receiving gossip messages from the peer.
1523 SendGossipTimestampFilter {
1524 /// The node_id of this message recipient
1526 /// The gossip_timestamp_filter which should be sent.
1527 msg: msgs::GossipTimestampFilter,
1531 /// A trait indicating an object may generate message send events
1532 pub trait MessageSendEventsProvider {
1533 /// Gets the list of pending events which were generated by previous actions, clearing the list
1535 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1538 /// A trait indicating an object may generate onion messages to send
1539 pub trait OnionMessageProvider {
1540 /// Gets the next pending onion message for the peer with the given node id.
1541 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<msgs::OnionMessage>;
1544 /// A trait indicating an object may generate events.
1546 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1548 /// Implementations of this trait may also feature an async version of event handling, as shown with
1549 /// [`ChannelManager::process_pending_events_async`] and
1550 /// [`ChainMonitor::process_pending_events_async`].
1554 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1555 /// event since the last invocation.
1557 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1558 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1559 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1560 /// relevant changes to disk *before* returning.
1562 /// Further, because an application may crash between an [`Event`] being handled and the
1563 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1564 /// effect, [`Event`]s may be replayed.
1566 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1567 /// consult the provider's documentation on the implication of processing events and how a handler
1568 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1569 /// [`ChainMonitor::process_pending_events`]).
1571 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1574 /// [`process_pending_events`]: Self::process_pending_events
1575 /// [`handle_event`]: EventHandler::handle_event
1576 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1577 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1578 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
1579 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
1580 pub trait EventsProvider {
1581 /// Processes any events generated since the last call using the given event handler.
1583 /// See the trait-level documentation for requirements.
1584 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1587 /// A trait implemented for objects handling events from [`EventsProvider`].
1589 /// An async variation also exists for implementations of [`EventsProvider`] that support async
1590 /// event handling. The async event handler should satisfy the generic bounds: `F:
1591 /// core::future::Future, H: Fn(Event) -> F`.
1592 pub trait EventHandler {
1593 /// Handles the given [`Event`].
1595 /// See [`EventsProvider`] for details that must be considered when implementing this method.
1596 fn handle_event(&self, event: Event);
1599 impl<F> EventHandler for F where F: Fn(Event) {
1600 fn handle_event(&self, event: Event) {
1605 impl<T: EventHandler> EventHandler for Arc<T> {
1606 fn handle_event(&self, event: Event) {
1607 self.deref().handle_event(event)