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 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
186 /// but is invalid for some reason, so we reject it.
188 /// Some of the reasons may include:
190 /// * Expected MPP amount to claim does not equal HTLC total
191 /// * Claimable amount does not match expected amount
193 /// The payment hash of the payment we attempted to process.
194 payment_hash: PaymentHash
198 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
199 (0, NextHopChannel) => {
200 (0, node_id, required),
201 (2, channel_id, required),
203 (2, UnknownNextHop) => {
204 (0, requested_forward_scid, required),
206 (4, FailedPayment) => {
207 (0, payment_hash, required),
212 /// A descriptor used to sign for a commitment transaction's anchor output.
213 #[derive(Clone, Debug)]
214 pub struct AnchorDescriptor {
215 /// A unique identifier used along with `channel_value_satoshis` to re-derive the
216 /// [`InMemorySigner`] required to sign `input`.
218 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
219 pub channel_keys_id: [u8; 32],
220 /// The value in satoshis of the channel we're attempting to spend the anchor output of. This is
221 /// used along with `channel_keys_id` to re-derive the [`InMemorySigner`] required to sign
224 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
225 pub channel_value_satoshis: u64,
226 /// The transaction input's outpoint corresponding to the commitment transaction's anchor
228 pub outpoint: OutPoint,
232 /// Represents the different types of transactions, originating from LDK, to be bumped.
233 #[derive(Clone, Debug)]
234 pub enum BumpTransactionEvent {
235 /// Indicates that a channel featuring anchor outputs is to be closed by broadcasting the local
236 /// commitment transaction. Since commitment transactions have a static feerate pre-agreed upon,
237 /// they may need additional fees to be attached through a child transaction using the popular
238 /// [Child-Pays-For-Parent](https://bitcoinops.org/en/topics/cpfp) fee bumping technique. This
239 /// child transaction must include the anchor input described within `anchor_descriptor` along
240 /// with additional inputs to meet the target feerate. Failure to meet the target feerate
241 /// decreases the confirmation odds of the transaction package (which includes the commitment
242 /// and child anchor transactions), possibly resulting in a loss of funds. Once the transaction
243 /// is constructed, it must be fully signed for and broadcasted by the consumer of the event
244 /// along with the `commitment_tx` enclosed. Note that the `commitment_tx` must always be
245 /// broadcast first, as the child anchor transaction depends on it.
247 /// The consumer should be able to sign for any of the additional inputs included within the
248 /// child anchor transaction. To sign its anchor input, an [`InMemorySigner`] should be
249 /// re-derived through [`KeysManager::derive_channel_keys`] with the help of
250 /// [`AnchorDescriptor::channel_keys_id`] and [`AnchorDescriptor::channel_value_satoshis`].
252 /// It is possible to receive more than one instance of this event if a valid child anchor
253 /// transaction is never broadcast or is but not with a sufficient fee to be mined. Care should
254 /// be taken by the consumer of the event to ensure any future iterations of the child anchor
255 /// transaction adhere to the [Replace-By-Fee
256 /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
257 /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
258 /// these events is not user-controlled, users may ignore/drop the event if they are no longer
259 /// able to commit external confirmed funds to the child anchor transaction.
261 /// The set of `pending_htlcs` on the commitment transaction to be broadcast can be inspected to
262 /// determine whether a significant portion of the channel's funds are allocated to HTLCs,
263 /// enabling users to make their own decisions regarding the importance of the commitment
264 /// transaction's confirmation. Note that this is not required, but simply exists as an option
265 /// for users to override LDK's behavior. On commitments with no HTLCs (indicated by those with
266 /// an empty `pending_htlcs`), confirmation of the commitment transaction can be considered to
269 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
270 /// [`KeysManager::derive_channel_keys`]: crate::chain::keysinterface::KeysManager::derive_channel_keys
272 /// The target feerate that the transaction package, which consists of the commitment
273 /// transaction and the to-be-crafted child anchor transaction, must meet.
274 package_target_feerate_sat_per_1000_weight: u32,
275 /// The channel's commitment transaction to bump the fee of. This transaction should be
276 /// broadcast along with the anchor transaction constructed as a result of consuming this
278 commitment_tx: Transaction,
279 /// The absolute fee in satoshis of the commitment transaction. This can be used along the
280 /// with weight of the commitment transaction to determine its feerate.
281 commitment_tx_fee_satoshis: u64,
282 /// The descriptor to sign the anchor input of the anchor transaction constructed as a
283 /// result of consuming this event.
284 anchor_descriptor: AnchorDescriptor,
285 /// The set of pending HTLCs on the commitment transaction that need to be resolved once the
286 /// commitment transaction confirms.
287 pending_htlcs: Vec<HTLCOutputInCommitment>,
291 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
292 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
293 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
294 /// intercepts in upcoming work.
295 enum InterceptNextHop {
297 requested_next_hop_scid: u64,
301 impl_writeable_tlv_based_enum!(InterceptNextHop,
303 (0, requested_next_hop_scid, required),
307 /// An Event which you should probably take some action in response to.
309 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
310 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
311 /// written as it makes no sense to respond to it after reconnecting to peers).
312 #[derive(Clone, Debug)]
314 /// Used to indicate that the client should generate a funding transaction with the given
315 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
316 /// Generated in [`ChannelManager`] message handling.
317 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
318 /// counterparty can steal your funds!
320 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
321 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
322 FundingGenerationReady {
323 /// The random channel_id we picked which you'll need to pass into
324 /// [`ChannelManager::funding_transaction_generated`].
326 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
327 temporary_channel_id: [u8; 32],
328 /// The counterparty's node_id, which you'll need to pass back into
329 /// [`ChannelManager::funding_transaction_generated`].
331 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
332 counterparty_node_id: PublicKey,
333 /// The value, in satoshis, that the output should have.
334 channel_value_satoshis: u64,
335 /// The script which should be used in the transaction output.
336 output_script: Script,
337 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or a
338 /// random value for an inbound channel. This may be zero for objects serialized with LDK
339 /// versions prior to 0.0.113.
341 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
342 user_channel_id: u128,
344 /// Indicates we've received (an offer of) money! Just gotta dig out that payment preimage and
345 /// feed it to [`ChannelManager::claim_funds`] to get it....
347 /// Note that if the preimage is not known, you should call
348 /// [`ChannelManager::fail_htlc_backwards`] to free up resources for this HTLC and avoid
349 /// network congestion.
350 /// If you fail to call either [`ChannelManager::claim_funds`] or
351 /// [`ChannelManager::fail_htlc_backwards`] within the HTLC's timeout, the HTLC will be
352 /// automatically failed.
355 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
356 /// `PaymentReceived` events may be generated for the same payment.
358 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
359 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
361 /// The node that received the payment.
362 /// This is useful to identify payments which were received via [phantom node payments].
363 /// This field will always be filled in when the event was generated by LDK versions
364 /// 0.0.113 and above.
366 /// [phantom node payments]: crate::chain::keysinterface::PhantomKeysManager
367 receiver_node_id: Option<PublicKey>,
368 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
369 /// not stop you from registering duplicate payment hashes for inbound payments.
370 payment_hash: PaymentHash,
371 /// The value, in thousandths of a satoshi, that this payment is for.
373 /// Information for claiming this received payment, based on whether the purpose of the
374 /// payment is to pay an invoice or to send a spontaneous payment.
375 purpose: PaymentPurpose,
376 /// The `channel_id` indicating over which channel we received the payment.
377 via_channel_id: Option<[u8; 32]>,
378 /// The `user_channel_id` indicating over which channel we received the payment.
379 via_user_channel_id: Option<u128>,
381 /// Indicates a payment has been claimed and we've received money!
383 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
384 /// to an [`Event::PaymentReceived`]. However, if we previously crashed during a
385 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
386 /// [`Event::PaymentReceived`] event.
389 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
390 /// `PaymentReceived` events may be generated for the same payment. If you then call
391 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentReceived`] you may get
392 /// multiple `PaymentClaimed` events.
394 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
396 /// The node that received the payment.
397 /// This is useful to identify payments which were received via [phantom node payments].
398 /// This field will always be filled in when the event was generated by LDK versions
399 /// 0.0.113 and above.
401 /// [phantom node payments]: crate::chain::keysinterface::PhantomKeysManager
402 receiver_node_id: Option<PublicKey>,
403 /// The payment hash of the claimed payment. Note that LDK will not stop you from
404 /// registering duplicate payment hashes for inbound payments.
405 payment_hash: PaymentHash,
406 /// The value, in thousandths of a satoshi, that this payment is for.
408 /// The purpose of this claimed payment, i.e. whether the payment was for an invoice or a
409 /// spontaneous payment.
410 purpose: PaymentPurpose,
412 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
413 /// and we got back the payment preimage for it).
415 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
416 /// event. In this situation, you SHOULD treat this payment as having succeeded.
418 /// The id returned by [`ChannelManager::send_payment`] and used with
419 /// [`ChannelManager::retry_payment`].
421 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
422 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
423 payment_id: Option<PaymentId>,
424 /// The preimage to the hash given to ChannelManager::send_payment.
425 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
426 /// store it somehow!
427 payment_preimage: PaymentPreimage,
428 /// The hash that was given to [`ChannelManager::send_payment`].
430 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
431 payment_hash: PaymentHash,
432 /// The total fee which was spent at intermediate hops in this payment, across all paths.
434 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
435 /// overpayment to the recipient node.
437 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
438 /// overstate the amount paid, though this is unlikely.
440 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
441 fee_paid_msat: Option<u64>,
443 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
444 /// provide failure information for each MPP part in the payment.
446 /// This event is provided once there are no further pending HTLCs for the payment and the
447 /// payment is no longer retryable due to [`ChannelManager::abandon_payment`] having been
448 /// called for the corresponding payment.
450 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
452 /// The id returned by [`ChannelManager::send_payment`] and used with
453 /// [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`].
455 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
456 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
457 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
458 payment_id: PaymentId,
459 /// The hash that was given to [`ChannelManager::send_payment`].
461 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
462 payment_hash: PaymentHash,
464 /// Indicates that a path for an outbound payment was successful.
466 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
467 /// [`Event::PaymentSent`] for obtaining the payment preimage.
468 PaymentPathSuccessful {
469 /// The id returned by [`ChannelManager::send_payment`] and used with
470 /// [`ChannelManager::retry_payment`].
472 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
473 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
474 payment_id: PaymentId,
475 /// The hash that was given to [`ChannelManager::send_payment`].
477 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
478 payment_hash: Option<PaymentHash>,
479 /// The payment path that was successful.
481 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
484 /// Indicates an outbound HTLC we sent failed. Probably some intermediary node dropped
485 /// something. You may wish to retry with a different route.
487 /// If you have given up retrying this payment and wish to fail it, you MUST call
488 /// [`ChannelManager::abandon_payment`] at least once for a given [`PaymentId`] or memory
489 /// related to payment tracking will leak.
491 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
492 /// [`Event::PaymentFailed`] and [`all_paths_failed`].
494 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
495 /// [`all_paths_failed`]: Self::PaymentPathFailed::all_paths_failed
497 /// The id returned by [`ChannelManager::send_payment`] and used with
498 /// [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`].
500 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
501 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
502 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
503 payment_id: Option<PaymentId>,
504 /// The hash that was given to [`ChannelManager::send_payment`].
506 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
507 payment_hash: PaymentHash,
508 /// Indicates the payment was rejected for some reason by the recipient. This implies that
509 /// the payment has failed, not just the route in question. If this is not set, you may
510 /// retry the payment via a different route.
511 payment_failed_permanently: bool,
512 /// Any failure information conveyed via the Onion return packet by a node along the failed
515 /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into
516 /// account the update.
518 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
519 network_update: Option<NetworkUpdate>,
520 /// For both single-path and multi-path payments, this is set if all paths of the payment have
521 /// failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the
522 /// larger MPP payment were still in flight when this event was generated.
524 /// Note that if you are retrying individual MPP parts, using this value to determine if a
525 /// payment has fully failed is race-y. Because multiple failures can happen prior to events
526 /// being processed, you may retry in response to a first failure, with a second failure
527 /// (with `all_paths_failed` set) still pending. Then, when the second failure is processed
528 /// you will see `all_paths_failed` set even though the retry of the first failure still
529 /// has an associated in-flight HTLC. See (1) for an example of such a failure.
531 /// If you wish to retry individual MPP parts and learn when a payment has failed, you must
532 /// call [`ChannelManager::abandon_payment`] and wait for a [`Event::PaymentFailed`] event.
534 /// (1) <https://github.com/lightningdevkit/rust-lightning/issues/1164>
536 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
537 all_paths_failed: bool,
538 /// The payment path that failed.
540 /// The channel responsible for the failed payment path.
542 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
543 /// may not refer to a channel in the public network graph. These aliases may also collide
544 /// with channels in the public network graph.
546 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
547 /// retried. May be `None` for older [`Event`] serializations.
548 short_channel_id: Option<u64>,
549 /// Parameters needed to compute a new [`Route`] when retrying the failed payment path.
551 /// See [`find_route`] for details.
553 /// [`Route`]: crate::routing::router::Route
554 /// [`find_route`]: crate::routing::router::find_route
555 retry: Option<RouteParameters>,
557 error_code: Option<u16>,
559 error_data: Option<Vec<u8>>,
561 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
563 /// The id returned by [`ChannelManager::send_probe`].
565 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
566 payment_id: PaymentId,
567 /// The hash generated by [`ChannelManager::send_probe`].
569 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
570 payment_hash: PaymentHash,
571 /// The payment path that was successful.
574 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
576 /// The id returned by [`ChannelManager::send_probe`].
578 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
579 payment_id: PaymentId,
580 /// The hash generated by [`ChannelManager::send_probe`].
582 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
583 payment_hash: PaymentHash,
584 /// The payment path that failed.
586 /// The channel responsible for the failed probe.
588 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
589 /// may not refer to a channel in the public network graph. These aliases may also collide
590 /// with channels in the public network graph.
591 short_channel_id: Option<u64>,
593 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
594 /// a time in the future.
596 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
597 PendingHTLCsForwardable {
598 /// The minimum amount of time that should be waited prior to calling
599 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
600 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
601 /// now + 5*time_forwardable).
602 time_forwardable: Duration,
604 /// Used to indicate that we've intercepted an HTLC forward.
606 /// An id to help LDK identify which HTLC is being forwarded or failed.
607 intercept_id: InterceptId,
608 /// The fake scid that was programmed as the next hop's scid.
609 requested_next_hop_scid: u64,
610 /// The payment hash used for this HTLC.
611 payment_hash: PaymentHash,
612 /// How many msats were received on the inbound edge of this HTLC.
613 inbound_amount_msat: u64,
614 /// How many msats the payer intended to route to the next node. Depending on the reason you are
615 /// intercepting this payment, you might take a fee by forwarding less than this amount.
617 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
618 /// check that whatever fee you want has been included here or subtract it as required. Further,
619 /// LDK will not stop you from forwarding more than you received.
620 expected_outbound_amount_msat: u64,
622 /// Used to indicate that an output which you should know how to spend was confirmed on chain
623 /// and is now spendable.
624 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
625 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
626 /// somewhere and spend them when you create on-chain transactions.
628 /// The outputs which you should store as spendable by you.
629 outputs: Vec<SpendableOutputDescriptor>,
631 /// This event is generated when a payment has been successfully forwarded through us and a
632 /// forwarding fee earned.
634 /// The incoming channel between the previous node and us. This is only `None` for events
635 /// generated or serialized by versions prior to 0.0.107.
636 prev_channel_id: Option<[u8; 32]>,
637 /// The outgoing channel between the next node and us. This is only `None` for events
638 /// generated or serialized by versions prior to 0.0.107.
639 next_channel_id: Option<[u8; 32]>,
640 /// The fee, in milli-satoshis, which was earned as a result of the payment.
642 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
643 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
644 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
645 /// claimed the full value in millisatoshis from the source. In this case,
646 /// `claim_from_onchain_tx` will be set.
648 /// If the channel which sent us the payment has been force-closed, we will claim the funds
649 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
650 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
651 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
653 fee_earned_msat: Option<u64>,
654 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
656 claim_from_onchain_tx: bool,
658 /// Used to indicate that a channel with the given `channel_id` is ready to
659 /// be used. This event is emitted either when the funding transaction has been confirmed
660 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
663 /// The channel_id of the channel that is ready.
664 channel_id: [u8; 32],
665 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
666 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
667 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
668 /// `user_channel_id` will be randomized for an inbound channel.
670 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
671 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
672 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
673 user_channel_id: u128,
674 /// The node_id of the channel counterparty.
675 counterparty_node_id: PublicKey,
676 /// The features that this channel will operate with.
677 channel_type: ChannelTypeFeatures,
679 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
680 /// process of closure.
682 /// The channel_id of the channel which has been closed. Note that on-chain transactions
683 /// resolving the channel are likely still awaiting confirmation.
684 channel_id: [u8; 32],
685 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
686 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
687 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
688 /// `user_channel_id` will be randomized for inbound channels.
689 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
690 /// zero for objects serialized with LDK versions prior to 0.0.102.
692 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
693 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
694 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
695 user_channel_id: u128,
696 /// The reason the channel was closed.
697 reason: ClosureReason
699 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
700 /// inputs for another purpose.
702 /// The channel_id of the channel which has been closed.
703 channel_id: [u8; 32],
704 /// The full transaction received from the user
705 transaction: Transaction
707 /// Indicates a request to open a new channel by a peer.
709 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the
710 /// request, call [`ChannelManager::force_close_without_broadcasting_txn`].
712 /// The event is only triggered when a new open channel request is received and the
713 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
715 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
716 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
717 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
719 /// The temporary channel ID of the channel requested to be opened.
721 /// When responding to the request, the `temporary_channel_id` should be passed
722 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
723 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
725 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
726 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
727 temporary_channel_id: [u8; 32],
728 /// The node_id of the counterparty requesting to open the channel.
730 /// When responding to the request, the `counterparty_node_id` should be passed
731 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
732 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
735 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
736 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
737 counterparty_node_id: PublicKey,
738 /// The channel value of the requested channel.
739 funding_satoshis: u64,
740 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
742 /// The features that this channel will operate with. If you reject the channel, a
743 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
746 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
747 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
750 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
751 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
752 /// 0.0.107. Channels setting this type also need to get manually accepted via
753 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
754 /// or will be rejected otherwise.
756 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
757 channel_type: ChannelTypeFeatures,
759 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
762 /// Some scenarios where this event may be sent include:
763 /// * Insufficient capacity in the outbound channel
764 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
765 /// * When an unknown SCID is requested for forwarding a payment.
766 /// * Claiming an amount for an MPP payment that exceeds the HTLC total
767 /// * The HTLC has timed out
769 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
770 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
772 /// The channel over which the HTLC was received.
773 prev_channel_id: [u8; 32],
774 /// Destination of the HTLC that failed to be processed.
775 failed_next_destination: HTLCDestination,
778 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
779 /// requires confirmed external funds to be readily available to spend.
781 /// LDK does not currently generate this event. It is limited to the scope of channels with
782 /// anchor outputs, which will be introduced in a future release.
783 BumpTransaction(BumpTransactionEvent),
786 impl Writeable for Event {
787 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
789 &Event::FundingGenerationReady { .. } => {
791 // We never write out FundingGenerationReady events as, upon disconnection, peers
792 // drop any channels which have not yet exchanged funding_signed.
794 &Event::PaymentReceived { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id } => {
796 let mut payment_secret = None;
797 let payment_preimage;
799 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
800 payment_secret = Some(secret);
801 payment_preimage = *preimage;
803 PaymentPurpose::SpontaneousPayment(preimage) => {
804 payment_preimage = Some(*preimage);
807 write_tlv_fields!(writer, {
808 (0, payment_hash, required),
809 (1, receiver_node_id, option),
810 (2, payment_secret, option),
811 (3, via_channel_id, option),
812 (4, amount_msat, required),
813 (5, via_user_channel_id, option),
814 (6, 0u64, required), // user_payment_id required for compatibility with 0.0.103 and earlier
815 (8, payment_preimage, option),
818 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
820 write_tlv_fields!(writer, {
821 (0, payment_preimage, required),
822 (1, payment_hash, required),
823 (3, payment_id, option),
824 (5, fee_paid_msat, option),
827 &Event::PaymentPathFailed {
828 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update,
829 ref all_paths_failed, ref path, ref short_channel_id, ref retry,
837 error_code.write(writer)?;
839 error_data.write(writer)?;
840 write_tlv_fields!(writer, {
841 (0, payment_hash, required),
842 (1, network_update, option),
843 (2, payment_failed_permanently, required),
844 (3, all_paths_failed, required),
845 (5, *path, vec_type),
846 (7, short_channel_id, option),
848 (11, payment_id, option),
851 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
853 // Note that we now ignore these on the read end as we'll re-generate them in
854 // ChannelManager, we write them here only for backwards compatibility.
856 &Event::SpendableOutputs { ref outputs } => {
858 write_tlv_fields!(writer, {
859 (0, WithoutLength(outputs), required),
862 &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
864 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
865 write_tlv_fields!(writer, {
866 (0, intercept_id, required),
867 (2, intercept_scid, required),
868 (4, payment_hash, required),
869 (6, inbound_amount_msat, required),
870 (8, expected_outbound_amount_msat, required),
873 &Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
875 write_tlv_fields!(writer, {
876 (0, fee_earned_msat, option),
877 (1, prev_channel_id, option),
878 (2, claim_from_onchain_tx, required),
879 (3, next_channel_id, option),
882 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
884 // `user_channel_id` used to be a single u64 value. In order to remain backwards
885 // compatible with versions prior to 0.0.113, the u128 is serialized as two
886 // separate u64 values.
887 let user_channel_id_low = *user_channel_id as u64;
888 let user_channel_id_high = (*user_channel_id >> 64) as u64;
889 write_tlv_fields!(writer, {
890 (0, channel_id, required),
891 (1, user_channel_id_low, required),
892 (2, reason, required),
893 (3, user_channel_id_high, required),
896 &Event::DiscardFunding { ref channel_id, ref transaction } => {
898 write_tlv_fields!(writer, {
899 (0, channel_id, required),
900 (2, transaction, required)
903 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
905 write_tlv_fields!(writer, {
906 (0, payment_id, required),
907 (2, payment_hash, option),
911 &Event::PaymentFailed { ref payment_id, ref payment_hash } => {
913 write_tlv_fields!(writer, {
914 (0, payment_id, required),
915 (2, payment_hash, required),
918 &Event::OpenChannelRequest { .. } => {
920 // We never write the OpenChannelRequest events as, upon disconnection, peers
921 // drop any channels which have not yet exchanged funding_signed.
923 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id } => {
925 write_tlv_fields!(writer, {
926 (0, payment_hash, required),
927 (1, receiver_node_id, option),
928 (2, purpose, required),
929 (4, amount_msat, required),
932 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
934 write_tlv_fields!(writer, {
935 (0, payment_id, required),
936 (2, payment_hash, required),
940 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
942 write_tlv_fields!(writer, {
943 (0, payment_id, required),
944 (2, payment_hash, required),
945 (4, *path, vec_type),
946 (6, short_channel_id, option),
949 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
951 write_tlv_fields!(writer, {
952 (0, prev_channel_id, required),
953 (2, failed_next_destination, required),
957 &Event::BumpTransaction(ref event)=> {
960 // We never write the ChannelClose events as they'll be replayed upon restarting
961 // anyway if the commitment transaction remains unconfirmed.
962 BumpTransactionEvent::ChannelClose { .. } => {}
965 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
967 write_tlv_fields!(writer, {
968 (0, channel_id, required),
969 (2, user_channel_id, required),
970 (4, counterparty_node_id, required),
971 (6, channel_type, required),
974 // Note that, going forward, all new events must only write data inside of
975 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
976 // data via `write_tlv_fields`.
981 impl MaybeReadable for Event {
982 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
983 match Readable::read(reader)? {
984 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
985 // unlike all other events, thus we return immediately here.
989 let mut payment_hash = PaymentHash([0; 32]);
990 let mut payment_preimage = None;
991 let mut payment_secret = None;
992 let mut amount_msat = 0;
993 let mut receiver_node_id = None;
994 let mut _user_payment_id = None::<u64>; // For compatibility with 0.0.103 and earlier
995 let mut via_channel_id = None;
996 let mut via_user_channel_id = None;
997 read_tlv_fields!(reader, {
998 (0, payment_hash, required),
999 (1, receiver_node_id, option),
1000 (2, payment_secret, option),
1001 (3, via_channel_id, option),
1002 (4, amount_msat, required),
1003 (5, via_user_channel_id, option),
1004 (6, _user_payment_id, option),
1005 (8, payment_preimage, option),
1007 let purpose = match payment_secret {
1008 Some(secret) => PaymentPurpose::InvoicePayment {
1010 payment_secret: secret
1012 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1013 None => return Err(msgs::DecodeError::InvalidValue),
1015 Ok(Some(Event::PaymentReceived {
1021 via_user_channel_id,
1028 let mut payment_preimage = PaymentPreimage([0; 32]);
1029 let mut payment_hash = None;
1030 let mut payment_id = None;
1031 let mut fee_paid_msat = None;
1032 read_tlv_fields!(reader, {
1033 (0, payment_preimage, required),
1034 (1, payment_hash, option),
1035 (3, payment_id, option),
1036 (5, fee_paid_msat, option),
1038 if payment_hash.is_none() {
1039 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
1041 Ok(Some(Event::PaymentSent {
1044 payment_hash: payment_hash.unwrap(),
1053 let error_code = Readable::read(reader)?;
1055 let error_data = Readable::read(reader)?;
1056 let mut payment_hash = PaymentHash([0; 32]);
1057 let mut payment_failed_permanently = false;
1058 let mut network_update = None;
1059 let mut all_paths_failed = Some(true);
1060 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1061 let mut short_channel_id = None;
1062 let mut retry = None;
1063 let mut payment_id = None;
1064 read_tlv_fields!(reader, {
1065 (0, payment_hash, required),
1066 (1, network_update, ignorable),
1067 (2, payment_failed_permanently, required),
1068 (3, all_paths_failed, option),
1069 (5, path, vec_type),
1070 (7, short_channel_id, option),
1072 (11, payment_id, option),
1074 Ok(Some(Event::PaymentPathFailed {
1077 payment_failed_permanently,
1079 all_paths_failed: all_paths_failed.unwrap(),
1080 path: path.unwrap(),
1094 let mut outputs = WithoutLength(Vec::new());
1095 read_tlv_fields!(reader, {
1096 (0, outputs, required),
1098 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
1103 let mut payment_hash = PaymentHash([0; 32]);
1104 let mut intercept_id = InterceptId([0; 32]);
1105 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1106 let mut inbound_amount_msat = 0;
1107 let mut expected_outbound_amount_msat = 0;
1108 read_tlv_fields!(reader, {
1109 (0, intercept_id, required),
1110 (2, requested_next_hop_scid, required),
1111 (4, payment_hash, required),
1112 (6, inbound_amount_msat, required),
1113 (8, expected_outbound_amount_msat, required),
1115 let next_scid = match requested_next_hop_scid {
1116 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1118 Ok(Some(Event::HTLCIntercepted {
1120 requested_next_hop_scid: next_scid,
1121 inbound_amount_msat,
1122 expected_outbound_amount_msat,
1128 let mut fee_earned_msat = None;
1129 let mut prev_channel_id = None;
1130 let mut claim_from_onchain_tx = false;
1131 let mut next_channel_id = None;
1132 read_tlv_fields!(reader, {
1133 (0, fee_earned_msat, option),
1134 (1, prev_channel_id, option),
1135 (2, claim_from_onchain_tx, required),
1136 (3, next_channel_id, option),
1138 Ok(Some(Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id }))
1144 let mut channel_id = [0; 32];
1145 let mut reason = None;
1146 let mut user_channel_id_low_opt: Option<u64> = None;
1147 let mut user_channel_id_high_opt: Option<u64> = None;
1148 read_tlv_fields!(reader, {
1149 (0, channel_id, required),
1150 (1, user_channel_id_low_opt, option),
1151 (2, reason, ignorable),
1152 (3, user_channel_id_high_opt, option),
1154 if reason.is_none() { return Ok(None); }
1156 // `user_channel_id` used to be a single u64 value. In order to remain
1157 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1158 // as two separate u64 values.
1159 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1160 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1162 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: reason.unwrap() }))
1168 let mut channel_id = [0; 32];
1169 let mut transaction = Transaction{ version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
1170 read_tlv_fields!(reader, {
1171 (0, channel_id, required),
1172 (2, transaction, required),
1174 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1180 let mut payment_id = PaymentId([0; 32]);
1181 let mut payment_hash = None;
1182 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1183 read_tlv_fields!(reader, {
1184 (0, payment_id, required),
1185 (2, payment_hash, option),
1186 (4, path, vec_type),
1188 Ok(Some(Event::PaymentPathSuccessful {
1191 path: path.unwrap(),
1198 let mut payment_hash = PaymentHash([0; 32]);
1199 let mut payment_id = PaymentId([0; 32]);
1200 read_tlv_fields!(reader, {
1201 (0, payment_id, required),
1202 (2, payment_hash, required),
1204 Ok(Some(Event::PaymentFailed {
1212 // Value 17 is used for `Event::OpenChannelRequest`.
1217 let mut payment_hash = PaymentHash([0; 32]);
1218 let mut purpose = None;
1219 let mut amount_msat = 0;
1220 let mut receiver_node_id = None;
1221 read_tlv_fields!(reader, {
1222 (0, payment_hash, required),
1223 (1, receiver_node_id, option),
1224 (2, purpose, ignorable),
1225 (4, amount_msat, required),
1227 if purpose.is_none() { return Ok(None); }
1228 Ok(Some(Event::PaymentClaimed {
1231 purpose: purpose.unwrap(),
1239 let mut payment_id = PaymentId([0; 32]);
1240 let mut payment_hash = PaymentHash([0; 32]);
1241 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1242 read_tlv_fields!(reader, {
1243 (0, payment_id, required),
1244 (2, payment_hash, required),
1245 (4, path, vec_type),
1247 Ok(Some(Event::ProbeSuccessful {
1250 path: path.unwrap(),
1257 let mut payment_id = PaymentId([0; 32]);
1258 let mut payment_hash = PaymentHash([0; 32]);
1259 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1260 let mut short_channel_id = None;
1261 read_tlv_fields!(reader, {
1262 (0, payment_id, required),
1263 (2, payment_hash, required),
1264 (4, path, vec_type),
1265 (6, short_channel_id, option),
1267 Ok(Some(Event::ProbeFailed {
1270 path: path.unwrap(),
1278 let mut prev_channel_id = [0; 32];
1279 let mut failed_next_destination_opt = None;
1280 read_tlv_fields!(reader, {
1281 (0, prev_channel_id, required),
1282 (2, failed_next_destination_opt, ignorable),
1284 if let Some(failed_next_destination) = failed_next_destination_opt {
1285 Ok(Some(Event::HTLCHandlingFailed {
1287 failed_next_destination,
1290 // If we fail to read a `failed_next_destination` assume it's because
1291 // `MaybeReadable::read` returned `Ok(None)`, though it's also possible we
1292 // were simply missing the field.
1301 let mut channel_id = [0; 32];
1302 let mut user_channel_id: u128 = 0;
1303 let mut counterparty_node_id = OptionDeserWrapper(None);
1304 let mut channel_type = OptionDeserWrapper(None);
1305 read_tlv_fields!(reader, {
1306 (0, channel_id, required),
1307 (2, user_channel_id, required),
1308 (4, counterparty_node_id, required),
1309 (6, channel_type, required),
1312 Ok(Some(Event::ChannelReady {
1315 counterparty_node_id: counterparty_node_id.0.unwrap(),
1316 channel_type: channel_type.0.unwrap()
1321 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1322 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1324 x if x % 2 == 1 => {
1325 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1326 // which prefixes the whole thing with a length BigSize. Because the event is
1327 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1328 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1329 // exactly the number of bytes specified, ignoring them entirely.
1330 let tlv_len: BigSize = Readable::read(reader)?;
1331 FixedLengthReader::new(reader, tlv_len.0)
1332 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1335 _ => Err(msgs::DecodeError::InvalidValue)
1340 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1341 /// broadcast to most peers).
1342 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1343 #[derive(Clone, Debug)]
1344 pub enum MessageSendEvent {
1345 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1346 /// message provided to the given peer.
1348 /// The node_id of the node which should receive this message
1350 /// The message which should be sent.
1351 msg: msgs::AcceptChannel,
1353 /// Used to indicate that we've initiated a channel open and should send the open_channel
1354 /// message provided to the given peer.
1356 /// The node_id of the node which should receive this message
1358 /// The message which should be sent.
1359 msg: msgs::OpenChannel,
1361 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1362 SendFundingCreated {
1363 /// The node_id of the node which should receive this message
1365 /// The message which should be sent.
1366 msg: msgs::FundingCreated,
1368 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1370 /// The node_id of the node which should receive this message
1372 /// The message which should be sent.
1373 msg: msgs::FundingSigned,
1375 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1377 /// The node_id of the node which should receive these message(s)
1379 /// The channel_ready message which should be sent.
1380 msg: msgs::ChannelReady,
1382 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1383 SendAnnouncementSignatures {
1384 /// The node_id of the node which should receive these message(s)
1386 /// The announcement_signatures message which should be sent.
1387 msg: msgs::AnnouncementSignatures,
1389 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1390 /// message should be sent to the peer with the given node_id.
1392 /// The node_id of the node which should receive these message(s)
1394 /// The update messages which should be sent. ALL messages in the struct should be sent!
1395 updates: msgs::CommitmentUpdate,
1397 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1399 /// The node_id of the node which should receive this message
1401 /// The message which should be sent.
1402 msg: msgs::RevokeAndACK,
1404 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1406 /// The node_id of the node which should receive this message
1408 /// The message which should be sent.
1409 msg: msgs::ClosingSigned,
1411 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1413 /// The node_id of the node which should receive this message
1415 /// The message which should be sent.
1416 msg: msgs::Shutdown,
1418 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1419 SendChannelReestablish {
1420 /// The node_id of the node which should receive this message
1422 /// The message which should be sent.
1423 msg: msgs::ChannelReestablish,
1425 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1426 /// initial connection to ensure our peers know about our channels.
1427 SendChannelAnnouncement {
1428 /// The node_id of the node which should receive this message
1430 /// The channel_announcement which should be sent.
1431 msg: msgs::ChannelAnnouncement,
1432 /// The followup channel_update which should be sent.
1433 update_msg: msgs::ChannelUpdate,
1435 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1436 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1438 /// Note that after doing so, you very likely (unless you did so very recently) want to
1439 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1440 /// ensures that any nodes which see our channel_announcement also have a relevant
1441 /// node_announcement, including relevant feature flags which may be important for routing
1442 /// through or to us.
1444 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1445 BroadcastChannelAnnouncement {
1446 /// The channel_announcement which should be sent.
1447 msg: msgs::ChannelAnnouncement,
1448 /// The followup channel_update which should be sent.
1449 update_msg: msgs::ChannelUpdate,
1451 /// Used to indicate that a channel_update should be broadcast to all peers.
1452 BroadcastChannelUpdate {
1453 /// The channel_update which should be sent.
1454 msg: msgs::ChannelUpdate,
1456 /// Used to indicate that a channel_update should be sent to a single peer.
1457 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1458 /// private channel and we shouldn't be informing all of our peers of channel parameters.
1460 /// The node_id of the node which should receive this message
1462 /// The channel_update which should be sent.
1463 msg: msgs::ChannelUpdate,
1465 /// Broadcast an error downstream to be handled
1467 /// The node_id of the node which should receive this message
1469 /// The action which should be taken.
1470 action: msgs::ErrorAction
1472 /// Query a peer for channels with funding transaction UTXOs in a block range.
1473 SendChannelRangeQuery {
1474 /// The node_id of this message recipient
1476 /// The query_channel_range which should be sent.
1477 msg: msgs::QueryChannelRange,
1479 /// Request routing gossip messages from a peer for a list of channels identified by
1480 /// their short_channel_ids.
1482 /// The node_id of this message recipient
1484 /// The query_short_channel_ids which should be sent.
1485 msg: msgs::QueryShortChannelIds,
1487 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1488 /// emitted during processing of the query.
1489 SendReplyChannelRange {
1490 /// The node_id of this message recipient
1492 /// The reply_channel_range which should be sent.
1493 msg: msgs::ReplyChannelRange,
1495 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1496 /// enable receiving gossip messages from the peer.
1497 SendGossipTimestampFilter {
1498 /// The node_id of this message recipient
1500 /// The gossip_timestamp_filter which should be sent.
1501 msg: msgs::GossipTimestampFilter,
1505 /// A trait indicating an object may generate message send events
1506 pub trait MessageSendEventsProvider {
1507 /// Gets the list of pending events which were generated by previous actions, clearing the list
1509 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1512 /// A trait indicating an object may generate onion messages to send
1513 pub trait OnionMessageProvider {
1514 /// Gets the next pending onion message for the peer with the given node id.
1515 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<msgs::OnionMessage>;
1518 /// A trait indicating an object may generate events.
1520 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1522 /// Implementations of this trait may also feature an async version of event handling, as shown with
1523 /// [`ChannelManager::process_pending_events_async`] and
1524 /// [`ChainMonitor::process_pending_events_async`].
1528 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1529 /// event since the last invocation.
1531 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1532 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1533 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1534 /// relevant changes to disk *before* returning.
1536 /// Further, because an application may crash between an [`Event`] being handled and the
1537 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1538 /// effect, [`Event`]s may be replayed.
1540 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1541 /// consult the provider's documentation on the implication of processing events and how a handler
1542 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1543 /// [`ChainMonitor::process_pending_events`]).
1545 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1548 /// [`process_pending_events`]: Self::process_pending_events
1549 /// [`handle_event`]: EventHandler::handle_event
1550 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1551 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1552 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
1553 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
1554 pub trait EventsProvider {
1555 /// Processes any events generated since the last call using the given event handler.
1557 /// See the trait-level documentation for requirements.
1558 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1561 /// A trait implemented for objects handling events from [`EventsProvider`].
1563 /// An async variation also exists for implementations of [`EventsProvider`] that support async
1564 /// event handling. The async event handler should satisfy the generic bounds: `F:
1565 /// core::future::Future, H: Fn(Event) -> F`.
1566 pub trait EventHandler {
1567 /// Handles the given [`Event`].
1569 /// See [`EventsProvider`] for details that must be considered when implementing this method.
1570 fn handle_event(&self, event: Event);
1573 impl<F> EventHandler for F where F: Fn(Event) {
1574 fn handle_event(&self, event: Event) {
1579 impl<T: EventHandler> EventHandler for Arc<T> {
1580 fn handle_event(&self, event: Event) {
1581 self.deref().handle_event(event)