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
18 pub mod bump_transaction;
21 pub use bump_transaction::BumpTransactionEvent;
23 use crate::chain::keysinterface::SpendableOutputDescriptor;
24 use crate::ln::channelmanager::{InterceptId, PaymentId};
25 use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
26 use crate::ln::features::ChannelTypeFeatures;
28 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
29 use crate::routing::gossip::NetworkUpdate;
30 use crate::util::errors::APIError;
31 use crate::util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, RequiredWrapper, UpgradableRequired, WithoutLength};
32 use crate::util::string::UntrustedString;
33 use crate::routing::router::{RouteHop, RouteParameters};
35 use bitcoin::{PackedLockTime, Transaction, OutPoint};
37 use bitcoin::{Txid, TxIn, TxOut, Witness};
38 use bitcoin::blockdata::script::Script;
39 use bitcoin::hashes::Hash;
40 use bitcoin::hashes::sha256::Hash as Sha256;
41 use bitcoin::secp256k1::PublicKey;
43 use crate::prelude::*;
44 use core::time::Duration;
48 /// Some information provided on receipt of payment depends on whether the payment received is a
49 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
50 #[derive(Clone, Debug, PartialEq, Eq)]
51 pub enum PaymentPurpose {
52 /// Information for receiving a payment that we generated an invoice for.
54 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
55 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
56 /// [`ChannelManager::claim_funds`].
58 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
59 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
60 payment_preimage: Option<PaymentPreimage>,
61 /// The "payment secret". This authenticates the sender to the recipient, preventing a
62 /// number of deanonymization attacks during the routing process.
63 /// It is provided here for your reference, however its accuracy is enforced directly by
64 /// [`ChannelManager`] using the values you previously provided to
65 /// [`ChannelManager::create_inbound_payment`] or
66 /// [`ChannelManager::create_inbound_payment_for_hash`].
68 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
69 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
70 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
71 payment_secret: PaymentSecret,
73 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
74 /// (the payee) providing a preimage.
75 SpontaneousPayment(PaymentPreimage),
78 impl_writeable_tlv_based_enum!(PaymentPurpose,
79 (0, InvoicePayment) => {
80 (0, payment_preimage, option),
81 (2, payment_secret, required),
83 (2, SpontaneousPayment)
86 /// When the payment path failure took place and extra details about it. [`PathFailure::OnPath`] may
87 /// contain a [`NetworkUpdate`] that needs to be applied to the [`NetworkGraph`].
89 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
90 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
91 #[derive(Clone, Debug, Eq, PartialEq)]
92 pub enum PathFailure {
93 /// We failed to initially send the payment and no HTLC was committed to. Contains the relevant
96 /// The error surfaced from initial send.
99 /// A hop on the path failed to forward our payment.
101 /// If present, this [`NetworkUpdate`] should be applied to the [`NetworkGraph`] so that routing
102 /// decisions can take into account the update.
104 /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate
105 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
106 network_update: Option<NetworkUpdate>,
110 impl_writeable_tlv_based_enum_upgradable!(PathFailure,
112 (0, network_update, upgradable_option),
114 (2, InitialSend) => {
115 (0, err, upgradable_required),
119 #[derive(Clone, Debug, PartialEq, Eq)]
120 /// The reason the channel was closed. See individual variants more details.
121 pub enum ClosureReason {
122 /// Closure generated from receiving a peer error message.
124 /// Our counterparty may have broadcasted their latest commitment state, and we have
126 CounterpartyForceClosed {
127 /// The error which the peer sent us.
129 /// Be careful about printing the peer_msg, a well-crafted message could exploit
130 /// a security vulnerability in the terminal emulator or the logging subsystem.
131 /// To be safe, use `Display` on `UntrustedString`
133 /// [`UntrustedString`]: crate::util::string::UntrustedString
134 peer_msg: UntrustedString,
136 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
138 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
140 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
141 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
142 //TODO: split between CounterpartyInitiated/LocallyInitiated
144 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
145 /// commitment transaction came from our counterparty, but it may also have come from
146 /// a copy of our own `ChannelMonitor`.
147 CommitmentTxConfirmed,
148 /// The funding transaction failed to confirm in a timely manner on an inbound channel.
150 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
152 /// A developer-readable error message which we generated.
155 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
156 /// forget the channel entirely - we can attempt again if the peer reconnects.
158 /// This includes cases where we restarted prior to funding completion, including prior to the
159 /// initial [`ChannelMonitor`] persistence completing.
161 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
162 /// peer because of mutual incompatibility between us and our channel counterparty.
164 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
166 /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
167 /// the [`ChannelManager`] deserialized.
169 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
170 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
171 OutdatedChannelManager
174 impl core::fmt::Display for ClosureReason {
175 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
176 f.write_str("Channel closed because ")?;
178 ClosureReason::CounterpartyForceClosed { peer_msg } => {
179 f.write_fmt(format_args!("counterparty force-closed with message: {}", peer_msg))
181 ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
182 ClosureReason::CooperativeClosure => f.write_str("the channel was cooperatively closed"),
183 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
184 ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
185 ClosureReason::ProcessingError { err } => {
186 f.write_str("of an exception: ")?;
189 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
190 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
195 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
196 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
197 (1, FundingTimedOut) => {},
198 (2, HolderForceClosed) => {},
199 (6, CommitmentTxConfirmed) => {},
200 (4, CooperativeClosure) => {},
201 (8, ProcessingError) => { (1, err, required) },
202 (10, DisconnectedPeer) => {},
203 (12, OutdatedChannelManager) => {},
206 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
207 #[derive(Clone, Debug, PartialEq, Eq)]
208 pub enum HTLCDestination {
209 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
210 /// there is insufficient capacity in our outbound channel.
212 /// The `node_id` of the next node. For backwards compatibility, this field is
213 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
214 /// counterparty node information.
215 node_id: Option<PublicKey>,
216 /// The outgoing `channel_id` between us and the next node.
217 channel_id: [u8; 32],
219 /// Scenario where we are unsure of the next node to forward the HTLC to.
221 /// Short channel id we are requesting to forward an HTLC to.
222 requested_forward_scid: u64,
224 /// We couldn't forward to the outgoing scid. An example would be attempting to send a duplicate
227 /// Short channel id we are requesting to forward an HTLC to.
228 requested_forward_scid: u64
230 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
231 /// but is invalid for some reason, so we reject it.
233 /// Some of the reasons may include:
235 /// * Expected MPP amount has already been reached
236 /// * Claimable amount does not match expected amount
238 /// The payment hash of the payment we attempted to process.
239 payment_hash: PaymentHash
243 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
244 (0, NextHopChannel) => {
245 (0, node_id, required),
246 (2, channel_id, required),
248 (1, InvalidForward) => {
249 (0, requested_forward_scid, required),
251 (2, UnknownNextHop) => {
252 (0, requested_forward_scid, required),
254 (4, FailedPayment) => {
255 (0, payment_hash, required),
259 /// Will be used in [`Event::HTLCIntercepted`] to identify the next hop in the HTLC's path.
260 /// Currently only used in serialization for the sake of maintaining compatibility. More variants
261 /// will be added for general-purpose HTLC forward intercepts as well as trampoline forward
262 /// intercepts in upcoming work.
263 enum InterceptNextHop {
265 requested_next_hop_scid: u64,
269 impl_writeable_tlv_based_enum!(InterceptNextHop,
271 (0, requested_next_hop_scid, required),
275 /// An Event which you should probably take some action in response to.
277 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
278 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
279 /// written as it makes no sense to respond to it after reconnecting to peers).
280 #[derive(Clone, Debug, PartialEq, Eq)]
282 /// Used to indicate that the client should generate a funding transaction with the given
283 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
284 /// Generated in [`ChannelManager`] message handling.
285 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
286 /// counterparty can steal your funds!
288 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
289 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
290 FundingGenerationReady {
291 /// The random channel_id we picked which you'll need to pass into
292 /// [`ChannelManager::funding_transaction_generated`].
294 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
295 temporary_channel_id: [u8; 32],
296 /// The counterparty's node_id, which you'll need to pass back into
297 /// [`ChannelManager::funding_transaction_generated`].
299 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
300 counterparty_node_id: PublicKey,
301 /// The value, in satoshis, that the output should have.
302 channel_value_satoshis: u64,
303 /// The script which should be used in the transaction output.
304 output_script: Script,
305 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or a
306 /// random value for an inbound channel. This may be zero for objects serialized with LDK
307 /// versions prior to 0.0.113.
309 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
310 user_channel_id: u128,
312 /// Indicates that we've been offered a payment and it needs to be claimed via calling
313 /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`].
315 /// Note that if the preimage is not known, you should call
316 /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`]
317 /// to free up resources for this HTLC and avoid network congestion.
318 /// If you fail to call either [`ChannelManager::claim_funds`], [`ChannelManager::fail_htlc_backwards`],
319 /// or [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will be
320 /// automatically failed.
323 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
324 /// `PaymentClaimable` events may be generated for the same payment. In such a case it is
325 /// polite (and required in the lightning specification) to fail the payment the second time
326 /// and give the sender their money back rather than accepting double payment.
329 /// This event used to be called `PaymentReceived` in LDK versions 0.0.112 and earlier.
331 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
332 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
333 /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason
335 /// The node that will receive the payment after it has been claimed.
336 /// This is useful to identify payments received via [phantom nodes].
337 /// This field will always be filled in when the event was generated by LDK versions
338 /// 0.0.113 and above.
340 /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
341 receiver_node_id: Option<PublicKey>,
342 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
343 /// not stop you from registering duplicate payment hashes for inbound payments.
344 payment_hash: PaymentHash,
345 /// The value, in thousandths of a satoshi, that this payment is for.
347 /// Information for claiming this received payment, based on whether the purpose of the
348 /// payment is to pay an invoice or to send a spontaneous payment.
349 purpose: PaymentPurpose,
350 /// The `channel_id` indicating over which channel we received the payment.
351 via_channel_id: Option<[u8; 32]>,
352 /// The `user_channel_id` indicating over which channel we received the payment.
353 via_user_channel_id: Option<u128>,
354 /// The block height at which this payment will be failed back and will no longer be
355 /// eligible for claiming.
357 /// Prior to this height, a call to [`ChannelManager::claim_funds`] is guaranteed to
358 /// succeed, however you should wait for [`Event::PaymentClaimed`] to be sure.
360 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
361 claim_deadline: Option<u32>,
363 /// Indicates a payment has been claimed and we've received money!
365 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
366 /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
367 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
368 /// [`Event::PaymentClaimable`] event.
371 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
372 /// `PaymentClaimable` events may be generated for the same payment. If you then call
373 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
374 /// multiple `PaymentClaimed` events.
376 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
378 /// The node that received the payment.
379 /// This is useful to identify payments which were received via [phantom nodes].
380 /// This field will always be filled in when the event was generated by LDK versions
381 /// 0.0.113 and above.
383 /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
384 receiver_node_id: Option<PublicKey>,
385 /// The payment hash of the claimed payment. Note that LDK will not stop you from
386 /// registering duplicate payment hashes for inbound payments.
387 payment_hash: PaymentHash,
388 /// The value, in thousandths of a satoshi, that this payment is for.
390 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
391 /// spontaneous payment.
392 purpose: PaymentPurpose,
394 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
395 /// and we got back the payment preimage for it).
397 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
398 /// event. In this situation, you SHOULD treat this payment as having succeeded.
400 /// The id returned by [`ChannelManager::send_payment`].
402 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
403 payment_id: Option<PaymentId>,
404 /// The preimage to the hash given to ChannelManager::send_payment.
405 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
406 /// store it somehow!
407 payment_preimage: PaymentPreimage,
408 /// The hash that was given to [`ChannelManager::send_payment`].
410 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
411 payment_hash: PaymentHash,
412 /// The total fee which was spent at intermediate hops in this payment, across all paths.
414 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
415 /// overpayment to the recipient node.
417 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
418 /// overstate the amount paid, though this is unlikely.
420 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
421 fee_paid_msat: Option<u64>,
423 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
424 /// provide failure information for each path attempt in the payment, including retries.
426 /// This event is provided once there are no further pending HTLCs for the payment and the
427 /// payment is no longer retryable, due either to the [`Retry`] provided or
428 /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
430 /// [`Retry`]: crate::ln::channelmanager::Retry
431 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
433 /// The id returned by [`ChannelManager::send_payment`] and used with
434 /// [`ChannelManager::abandon_payment`].
436 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
437 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
438 payment_id: PaymentId,
439 /// The hash that was given to [`ChannelManager::send_payment`].
441 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
442 payment_hash: PaymentHash,
444 /// Indicates that a path for an outbound payment was successful.
446 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
447 /// [`Event::PaymentSent`] for obtaining the payment preimage.
448 PaymentPathSuccessful {
449 /// The id returned by [`ChannelManager::send_payment`].
451 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
452 payment_id: PaymentId,
453 /// The hash that was given to [`ChannelManager::send_payment`].
455 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
456 payment_hash: Option<PaymentHash>,
457 /// The payment path that was successful.
459 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
462 /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
465 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
466 /// [`Event::PaymentFailed`].
468 /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
471 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
473 /// The id returned by [`ChannelManager::send_payment`] and used with
474 /// [`ChannelManager::abandon_payment`].
476 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
477 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
478 payment_id: Option<PaymentId>,
479 /// The hash that was given to [`ChannelManager::send_payment`].
481 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
482 payment_hash: PaymentHash,
483 /// Indicates the payment was rejected for some reason by the recipient. This implies that
484 /// the payment has failed, not just the route in question. If this is not set, the payment may
485 /// be retried via a different route.
486 payment_failed_permanently: bool,
487 /// Extra error details based on the failure type. May contain an update that needs to be
488 /// applied to the [`NetworkGraph`].
490 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
491 failure: PathFailure,
492 /// The payment path that failed.
494 /// The channel responsible for the failed payment path.
496 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
497 /// may not refer to a channel in the public network graph. These aliases may also collide
498 /// with channels in the public network graph.
500 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
501 /// retried. May be `None` for older [`Event`] serializations.
502 short_channel_id: Option<u64>,
504 error_code: Option<u16>,
506 error_data: Option<Vec<u8>>,
508 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
510 /// The id returned by [`ChannelManager::send_probe`].
512 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
513 payment_id: PaymentId,
514 /// The hash generated by [`ChannelManager::send_probe`].
516 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
517 payment_hash: PaymentHash,
518 /// The payment path that was successful.
521 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
523 /// The id returned by [`ChannelManager::send_probe`].
525 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
526 payment_id: PaymentId,
527 /// The hash generated by [`ChannelManager::send_probe`].
529 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
530 payment_hash: PaymentHash,
531 /// The payment path that failed.
533 /// The channel responsible for the failed probe.
535 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
536 /// may not refer to a channel in the public network graph. These aliases may also collide
537 /// with channels in the public network graph.
538 short_channel_id: Option<u64>,
540 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
541 /// a time in the future.
543 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
544 PendingHTLCsForwardable {
545 /// The minimum amount of time that should be waited prior to calling
546 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
547 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
548 /// now + 5*time_forwardable).
549 time_forwardable: Duration,
551 /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
552 /// you've encoded an intercept scid in the receiver's invoice route hints using
553 /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
555 /// [`ChannelManager::forward_intercepted_htlc`] or
556 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
557 /// their docs for more information.
559 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
560 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
561 /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
562 /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
564 /// An id to help LDK identify which HTLC is being forwarded or failed.
565 intercept_id: InterceptId,
566 /// The fake scid that was programmed as the next hop's scid, generated using
567 /// [`ChannelManager::get_intercept_scid`].
569 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
570 requested_next_hop_scid: u64,
571 /// The payment hash used for this HTLC.
572 payment_hash: PaymentHash,
573 /// How many msats were received on the inbound edge of this HTLC.
574 inbound_amount_msat: u64,
575 /// How many msats the payer intended to route to the next node. Depending on the reason you are
576 /// intercepting this payment, you might take a fee by forwarding less than this amount.
578 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
579 /// check that whatever fee you want has been included here or subtract it as required. Further,
580 /// LDK will not stop you from forwarding more than you received.
581 expected_outbound_amount_msat: u64,
583 /// Used to indicate that an output which you should know how to spend was confirmed on chain
584 /// and is now spendable.
585 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
586 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
587 /// somewhere and spend them when you create on-chain transactions.
589 /// The outputs which you should store as spendable by you.
590 outputs: Vec<SpendableOutputDescriptor>,
592 /// This event is generated when a payment has been successfully forwarded through us and a
593 /// forwarding fee earned.
595 /// The incoming channel between the previous node and us. This is only `None` for events
596 /// generated or serialized by versions prior to 0.0.107.
597 prev_channel_id: Option<[u8; 32]>,
598 /// The outgoing channel between the next node and us. This is only `None` for events
599 /// generated or serialized by versions prior to 0.0.107.
600 next_channel_id: Option<[u8; 32]>,
601 /// The fee, in milli-satoshis, which was earned as a result of the payment.
603 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
604 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
605 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
606 /// claimed the full value in millisatoshis from the source. In this case,
607 /// `claim_from_onchain_tx` will be set.
609 /// If the channel which sent us the payment has been force-closed, we will claim the funds
610 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
611 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
612 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
614 fee_earned_msat: Option<u64>,
615 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
617 claim_from_onchain_tx: bool,
618 /// The final amount forwarded, in milli-satoshis, after the fee is deducted.
620 /// The caveat described above the `fee_earned_msat` field applies here as well.
621 outbound_amount_forwarded_msat: Option<u64>,
623 /// Used to indicate that a channel with the given `channel_id` is being opened and pending
624 /// confirmation on-chain.
626 /// This event is emitted when the funding transaction has been signed and is broadcast to the
627 /// network. For 0conf channels it will be immediately followed by the corresponding
628 /// [`Event::ChannelReady`] event.
630 /// The `channel_id` of the channel that is pending confirmation.
631 channel_id: [u8; 32],
632 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
633 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
634 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
635 /// `user_channel_id` will be randomized for an inbound channel.
637 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
638 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
639 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
640 user_channel_id: u128,
641 /// The `temporary_channel_id` this channel used to be known by during channel establishment.
643 /// Will be `None` for channels created prior to LDK version 0.0.115.
644 former_temporary_channel_id: Option<[u8; 32]>,
645 /// The `node_id` of the channel counterparty.
646 counterparty_node_id: PublicKey,
647 /// The outpoint of the channel's funding transaction.
648 funding_txo: OutPoint,
650 /// Used to indicate that a channel with the given `channel_id` is ready to
651 /// be used. This event is emitted either when the funding transaction has been confirmed
652 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
655 /// The `channel_id` of the channel that is ready.
656 channel_id: [u8; 32],
657 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
658 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
659 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
660 /// `user_channel_id` will be randomized for an inbound channel.
662 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
663 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
664 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
665 user_channel_id: u128,
666 /// The `node_id` of the channel counterparty.
667 counterparty_node_id: PublicKey,
668 /// The features that this channel will operate with.
669 channel_type: ChannelTypeFeatures,
671 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
672 /// process of closure.
674 /// The `channel_id` of the channel which has been closed. Note that on-chain transactions
675 /// resolving the channel are likely still awaiting confirmation.
676 channel_id: [u8; 32],
677 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
678 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
679 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
680 /// `user_channel_id` will be randomized for inbound channels.
681 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
682 /// zero for objects serialized with LDK versions prior to 0.0.102.
684 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
685 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
686 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
687 user_channel_id: u128,
688 /// The reason the channel was closed.
689 reason: ClosureReason
691 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
692 /// inputs for another purpose.
694 /// The channel_id of the channel which has been closed.
695 channel_id: [u8; 32],
696 /// The full transaction received from the user
697 transaction: Transaction
699 /// Indicates a request to open a new channel by a peer.
701 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the
702 /// request, call [`ChannelManager::force_close_without_broadcasting_txn`].
704 /// The event is only triggered when a new open channel request is received and the
705 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
707 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
708 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
709 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
711 /// The temporary channel ID of the channel requested to be opened.
713 /// When responding to the request, the `temporary_channel_id` should be passed
714 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
715 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
717 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
718 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
719 temporary_channel_id: [u8; 32],
720 /// The node_id of the counterparty requesting to open the channel.
722 /// When responding to the request, the `counterparty_node_id` should be passed
723 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
724 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
727 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
728 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
729 counterparty_node_id: PublicKey,
730 /// The channel value of the requested channel.
731 funding_satoshis: u64,
732 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
734 /// The features that this channel will operate with. If you reject the channel, a
735 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
738 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
739 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
742 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
743 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
744 /// 0.0.107. Channels setting this type also need to get manually accepted via
745 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
746 /// or will be rejected otherwise.
748 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
749 channel_type: ChannelTypeFeatures,
751 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
754 /// Some scenarios where this event may be sent include:
755 /// * Insufficient capacity in the outbound channel
756 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
757 /// * When an unknown SCID is requested for forwarding a payment.
758 /// * Expected MPP amount has already been reached
759 /// * The HTLC has timed out
761 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
762 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
764 /// The channel over which the HTLC was received.
765 prev_channel_id: [u8; 32],
766 /// Destination of the HTLC that failed to be processed.
767 failed_next_destination: HTLCDestination,
770 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
771 /// requires confirmed external funds to be readily available to spend.
773 /// LDK does not currently generate this event. It is limited to the scope of channels with
774 /// anchor outputs, which will be introduced in a future release.
775 BumpTransaction(BumpTransactionEvent),
778 impl Writeable for Event {
779 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
781 &Event::FundingGenerationReady { .. } => {
783 // We never write out FundingGenerationReady events as, upon disconnection, peers
784 // drop any channels which have not yet exchanged funding_signed.
786 &Event::PaymentClaimable { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id, ref via_channel_id, ref via_user_channel_id, ref claim_deadline } => {
788 let mut payment_secret = None;
789 let payment_preimage;
791 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
792 payment_secret = Some(secret);
793 payment_preimage = *preimage;
795 PaymentPurpose::SpontaneousPayment(preimage) => {
796 payment_preimage = Some(*preimage);
799 write_tlv_fields!(writer, {
800 (0, payment_hash, required),
801 (1, receiver_node_id, option),
802 (2, payment_secret, option),
803 (3, via_channel_id, option),
804 (4, amount_msat, required),
805 (5, via_user_channel_id, option),
806 (6, 0u64, required), // user_payment_id required for compatibility with 0.0.103 and earlier
807 (7, claim_deadline, option),
808 (8, payment_preimage, option),
811 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
813 write_tlv_fields!(writer, {
814 (0, payment_preimage, required),
815 (1, payment_hash, required),
816 (3, payment_id, option),
817 (5, fee_paid_msat, option),
820 &Event::PaymentPathFailed {
821 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
822 ref path, ref short_channel_id,
830 error_code.write(writer)?;
832 error_data.write(writer)?;
833 write_tlv_fields!(writer, {
834 (0, payment_hash, required),
835 (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
836 (2, payment_failed_permanently, required),
837 (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
838 (5, *path, vec_type),
839 (7, short_channel_id, option),
840 (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
841 (11, payment_id, option),
842 (13, failure, required),
845 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
847 // Note that we now ignore these on the read end as we'll re-generate them in
848 // ChannelManager, we write them here only for backwards compatibility.
850 &Event::SpendableOutputs { ref outputs } => {
852 write_tlv_fields!(writer, {
853 (0, WithoutLength(outputs), required),
856 &Event::HTLCIntercepted { requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat, intercept_id } => {
858 let intercept_scid = InterceptNextHop::FakeScid { requested_next_hop_scid };
859 write_tlv_fields!(writer, {
860 (0, intercept_id, required),
861 (2, intercept_scid, required),
862 (4, payment_hash, required),
863 (6, inbound_amount_msat, required),
864 (8, expected_outbound_amount_msat, required),
867 &Event::PaymentForwarded {
868 fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
869 next_channel_id, outbound_amount_forwarded_msat
872 write_tlv_fields!(writer, {
873 (0, fee_earned_msat, option),
874 (1, prev_channel_id, option),
875 (2, claim_from_onchain_tx, required),
876 (3, next_channel_id, option),
877 (5, outbound_amount_forwarded_msat, option),
880 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
882 // `user_channel_id` used to be a single u64 value. In order to remain backwards
883 // compatible with versions prior to 0.0.113, the u128 is serialized as two
884 // separate u64 values.
885 let user_channel_id_low = *user_channel_id as u64;
886 let user_channel_id_high = (*user_channel_id >> 64) as u64;
887 write_tlv_fields!(writer, {
888 (0, channel_id, required),
889 (1, user_channel_id_low, required),
890 (2, reason, required),
891 (3, user_channel_id_high, required),
894 &Event::DiscardFunding { ref channel_id, ref transaction } => {
896 write_tlv_fields!(writer, {
897 (0, channel_id, required),
898 (2, transaction, required)
901 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
903 write_tlv_fields!(writer, {
904 (0, payment_id, required),
905 (2, payment_hash, option),
909 &Event::PaymentFailed { ref payment_id, ref payment_hash } => {
911 write_tlv_fields!(writer, {
912 (0, payment_id, required),
913 (2, payment_hash, required),
916 &Event::OpenChannelRequest { .. } => {
918 // We never write the OpenChannelRequest events as, upon disconnection, peers
919 // drop any channels which have not yet exchanged funding_signed.
921 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id } => {
923 write_tlv_fields!(writer, {
924 (0, payment_hash, required),
925 (1, receiver_node_id, option),
926 (2, purpose, required),
927 (4, amount_msat, required),
930 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
932 write_tlv_fields!(writer, {
933 (0, payment_id, required),
934 (2, payment_hash, required),
938 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
940 write_tlv_fields!(writer, {
941 (0, payment_id, required),
942 (2, payment_hash, required),
943 (4, *path, vec_type),
944 (6, short_channel_id, option),
947 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
949 write_tlv_fields!(writer, {
950 (0, prev_channel_id, required),
951 (2, failed_next_destination, required),
955 &Event::BumpTransaction(ref event)=> {
958 // We never write the ChannelClose|HTLCResolution events as they'll be replayed
959 // upon restarting anyway if they remain unresolved.
960 BumpTransactionEvent::ChannelClose { .. } => {}
961 BumpTransactionEvent::HTLCResolution { .. } => {}
963 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
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 &Event::ChannelPending { ref channel_id, ref user_channel_id, ref former_temporary_channel_id, ref counterparty_node_id, ref funding_txo } => {
976 write_tlv_fields!(writer, {
977 (0, channel_id, required),
978 (2, user_channel_id, required),
979 (4, former_temporary_channel_id, required),
980 (6, counterparty_node_id, required),
981 (8, funding_txo, required),
984 // Note that, going forward, all new events must only write data inside of
985 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
986 // data via `write_tlv_fields`.
991 impl MaybeReadable for Event {
992 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
993 match Readable::read(reader)? {
994 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
995 // unlike all other events, thus we return immediately here.
999 let mut payment_hash = PaymentHash([0; 32]);
1000 let mut payment_preimage = None;
1001 let mut payment_secret = None;
1002 let mut amount_msat = 0;
1003 let mut receiver_node_id = None;
1004 let mut _user_payment_id = None::<u64>; // For compatibility with 0.0.103 and earlier
1005 let mut via_channel_id = None;
1006 let mut claim_deadline = None;
1007 let mut via_user_channel_id = None;
1008 read_tlv_fields!(reader, {
1009 (0, payment_hash, required),
1010 (1, receiver_node_id, option),
1011 (2, payment_secret, option),
1012 (3, via_channel_id, option),
1013 (4, amount_msat, required),
1014 (5, via_user_channel_id, option),
1015 (6, _user_payment_id, option),
1016 (7, claim_deadline, option),
1017 (8, payment_preimage, option),
1019 let purpose = match payment_secret {
1020 Some(secret) => PaymentPurpose::InvoicePayment {
1022 payment_secret: secret
1024 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1025 None => return Err(msgs::DecodeError::InvalidValue),
1027 Ok(Some(Event::PaymentClaimable {
1033 via_user_channel_id,
1041 let mut payment_preimage = PaymentPreimage([0; 32]);
1042 let mut payment_hash = None;
1043 let mut payment_id = None;
1044 let mut fee_paid_msat = None;
1045 read_tlv_fields!(reader, {
1046 (0, payment_preimage, required),
1047 (1, payment_hash, option),
1048 (3, payment_id, option),
1049 (5, fee_paid_msat, option),
1051 if payment_hash.is_none() {
1052 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
1054 Ok(Some(Event::PaymentSent {
1057 payment_hash: payment_hash.unwrap(),
1066 let error_code = Readable::read(reader)?;
1068 let error_data = Readable::read(reader)?;
1069 let mut payment_hash = PaymentHash([0; 32]);
1070 let mut payment_failed_permanently = false;
1071 let mut network_update = None;
1072 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1073 let mut short_channel_id = None;
1074 let mut payment_id = None;
1075 let mut failure_opt = None;
1076 read_tlv_fields!(reader, {
1077 (0, payment_hash, required),
1078 (1, network_update, upgradable_option),
1079 (2, payment_failed_permanently, required),
1080 (5, path, vec_type),
1081 (7, short_channel_id, option),
1082 (11, payment_id, option),
1083 (13, failure_opt, upgradable_option),
1085 let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1086 Ok(Some(Event::PaymentPathFailed {
1089 payment_failed_permanently,
1091 path: path.unwrap(),
1104 let mut outputs = WithoutLength(Vec::new());
1105 read_tlv_fields!(reader, {
1106 (0, outputs, required),
1108 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
1113 let mut payment_hash = PaymentHash([0; 32]);
1114 let mut intercept_id = InterceptId([0; 32]);
1115 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1116 let mut inbound_amount_msat = 0;
1117 let mut expected_outbound_amount_msat = 0;
1118 read_tlv_fields!(reader, {
1119 (0, intercept_id, required),
1120 (2, requested_next_hop_scid, required),
1121 (4, payment_hash, required),
1122 (6, inbound_amount_msat, required),
1123 (8, expected_outbound_amount_msat, required),
1125 let next_scid = match requested_next_hop_scid {
1126 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1128 Ok(Some(Event::HTLCIntercepted {
1130 requested_next_hop_scid: next_scid,
1131 inbound_amount_msat,
1132 expected_outbound_amount_msat,
1138 let mut fee_earned_msat = None;
1139 let mut prev_channel_id = None;
1140 let mut claim_from_onchain_tx = false;
1141 let mut next_channel_id = None;
1142 let mut outbound_amount_forwarded_msat = None;
1143 read_tlv_fields!(reader, {
1144 (0, fee_earned_msat, option),
1145 (1, prev_channel_id, option),
1146 (2, claim_from_onchain_tx, required),
1147 (3, next_channel_id, option),
1148 (5, outbound_amount_forwarded_msat, option),
1150 Ok(Some(Event::PaymentForwarded {
1151 fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id,
1152 outbound_amount_forwarded_msat
1159 let mut channel_id = [0; 32];
1160 let mut reason = UpgradableRequired(None);
1161 let mut user_channel_id_low_opt: Option<u64> = None;
1162 let mut user_channel_id_high_opt: Option<u64> = None;
1163 read_tlv_fields!(reader, {
1164 (0, channel_id, required),
1165 (1, user_channel_id_low_opt, option),
1166 (2, reason, upgradable_required),
1167 (3, user_channel_id_high_opt, option),
1170 // `user_channel_id` used to be a single u64 value. In order to remain
1171 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1172 // as two separate u64 values.
1173 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1174 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1176 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required) }))
1182 let mut channel_id = [0; 32];
1183 let mut transaction = Transaction{ version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
1184 read_tlv_fields!(reader, {
1185 (0, channel_id, required),
1186 (2, transaction, required),
1188 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1194 let mut payment_id = PaymentId([0; 32]);
1195 let mut payment_hash = None;
1196 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1197 read_tlv_fields!(reader, {
1198 (0, payment_id, required),
1199 (2, payment_hash, option),
1200 (4, path, vec_type),
1202 Ok(Some(Event::PaymentPathSuccessful {
1205 path: path.unwrap(),
1212 let mut payment_hash = PaymentHash([0; 32]);
1213 let mut payment_id = PaymentId([0; 32]);
1214 read_tlv_fields!(reader, {
1215 (0, payment_id, required),
1216 (2, payment_hash, required),
1218 Ok(Some(Event::PaymentFailed {
1226 // Value 17 is used for `Event::OpenChannelRequest`.
1231 let mut payment_hash = PaymentHash([0; 32]);
1232 let mut purpose = UpgradableRequired(None);
1233 let mut amount_msat = 0;
1234 let mut receiver_node_id = None;
1235 read_tlv_fields!(reader, {
1236 (0, payment_hash, required),
1237 (1, receiver_node_id, option),
1238 (2, purpose, upgradable_required),
1239 (4, amount_msat, required),
1241 Ok(Some(Event::PaymentClaimed {
1244 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1252 let mut payment_id = PaymentId([0; 32]);
1253 let mut payment_hash = PaymentHash([0; 32]);
1254 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1255 read_tlv_fields!(reader, {
1256 (0, payment_id, required),
1257 (2, payment_hash, required),
1258 (4, path, vec_type),
1260 Ok(Some(Event::ProbeSuccessful {
1263 path: path.unwrap(),
1270 let mut payment_id = PaymentId([0; 32]);
1271 let mut payment_hash = PaymentHash([0; 32]);
1272 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1273 let mut short_channel_id = None;
1274 read_tlv_fields!(reader, {
1275 (0, payment_id, required),
1276 (2, payment_hash, required),
1277 (4, path, vec_type),
1278 (6, short_channel_id, option),
1280 Ok(Some(Event::ProbeFailed {
1283 path: path.unwrap(),
1291 let mut prev_channel_id = [0; 32];
1292 let mut failed_next_destination_opt = UpgradableRequired(None);
1293 read_tlv_fields!(reader, {
1294 (0, prev_channel_id, required),
1295 (2, failed_next_destination_opt, upgradable_required),
1297 Ok(Some(Event::HTLCHandlingFailed {
1299 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1307 let mut channel_id = [0; 32];
1308 let mut user_channel_id: u128 = 0;
1309 let mut counterparty_node_id = RequiredWrapper(None);
1310 let mut channel_type = RequiredWrapper(None);
1311 read_tlv_fields!(reader, {
1312 (0, channel_id, required),
1313 (2, user_channel_id, required),
1314 (4, counterparty_node_id, required),
1315 (6, channel_type, required),
1318 Ok(Some(Event::ChannelReady {
1321 counterparty_node_id: counterparty_node_id.0.unwrap(),
1322 channel_type: channel_type.0.unwrap()
1329 let mut channel_id = [0; 32];
1330 let mut user_channel_id: u128 = 0;
1331 let mut former_temporary_channel_id = None;
1332 let mut counterparty_node_id = RequiredWrapper(None);
1333 let mut funding_txo = RequiredWrapper(None);
1334 read_tlv_fields!(reader, {
1335 (0, channel_id, required),
1336 (2, user_channel_id, required),
1337 (4, former_temporary_channel_id, required),
1338 (6, counterparty_node_id, required),
1339 (8, funding_txo, required),
1342 Ok(Some(Event::ChannelPending {
1345 former_temporary_channel_id,
1346 counterparty_node_id: counterparty_node_id.0.unwrap(),
1347 funding_txo: funding_txo.0.unwrap()
1352 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1353 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1355 x if x % 2 == 1 => {
1356 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1357 // which prefixes the whole thing with a length BigSize. Because the event is
1358 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1359 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1360 // exactly the number of bytes specified, ignoring them entirely.
1361 let tlv_len: BigSize = Readable::read(reader)?;
1362 FixedLengthReader::new(reader, tlv_len.0)
1363 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1366 _ => Err(msgs::DecodeError::InvalidValue)
1371 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1372 /// broadcast to most peers).
1373 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1374 #[derive(Clone, Debug)]
1375 pub enum MessageSendEvent {
1376 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1377 /// message provided to the given peer.
1379 /// The node_id of the node which should receive this message
1381 /// The message which should be sent.
1382 msg: msgs::AcceptChannel,
1384 /// Used to indicate that we've initiated a channel open and should send the open_channel
1385 /// message provided to the given peer.
1387 /// The node_id of the node which should receive this message
1389 /// The message which should be sent.
1390 msg: msgs::OpenChannel,
1392 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1393 SendFundingCreated {
1394 /// The node_id of the node which should receive this message
1396 /// The message which should be sent.
1397 msg: msgs::FundingCreated,
1399 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1401 /// The node_id of the node which should receive this message
1403 /// The message which should be sent.
1404 msg: msgs::FundingSigned,
1406 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1408 /// The node_id of the node which should receive these message(s)
1410 /// The channel_ready message which should be sent.
1411 msg: msgs::ChannelReady,
1413 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1414 SendAnnouncementSignatures {
1415 /// The node_id of the node which should receive these message(s)
1417 /// The announcement_signatures message which should be sent.
1418 msg: msgs::AnnouncementSignatures,
1420 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1421 /// message should be sent to the peer with the given node_id.
1423 /// The node_id of the node which should receive these message(s)
1425 /// The update messages which should be sent. ALL messages in the struct should be sent!
1426 updates: msgs::CommitmentUpdate,
1428 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1430 /// The node_id of the node which should receive this message
1432 /// The message which should be sent.
1433 msg: msgs::RevokeAndACK,
1435 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1437 /// The node_id of the node which should receive this message
1439 /// The message which should be sent.
1440 msg: msgs::ClosingSigned,
1442 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1444 /// The node_id of the node which should receive this message
1446 /// The message which should be sent.
1447 msg: msgs::Shutdown,
1449 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1450 SendChannelReestablish {
1451 /// The node_id of the node which should receive this message
1453 /// The message which should be sent.
1454 msg: msgs::ChannelReestablish,
1456 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1457 /// initial connection to ensure our peers know about our channels.
1458 SendChannelAnnouncement {
1459 /// The node_id of the node which should receive this message
1461 /// The channel_announcement which should be sent.
1462 msg: msgs::ChannelAnnouncement,
1463 /// The followup channel_update which should be sent.
1464 update_msg: msgs::ChannelUpdate,
1466 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1467 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1469 /// Note that after doing so, you very likely (unless you did so very recently) want to
1470 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1471 /// ensures that any nodes which see our channel_announcement also have a relevant
1472 /// node_announcement, including relevant feature flags which may be important for routing
1473 /// through or to us.
1475 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1476 BroadcastChannelAnnouncement {
1477 /// The channel_announcement which should be sent.
1478 msg: msgs::ChannelAnnouncement,
1479 /// The followup channel_update which should be sent.
1480 update_msg: Option<msgs::ChannelUpdate>,
1482 /// Used to indicate that a channel_update should be broadcast to all peers.
1483 BroadcastChannelUpdate {
1484 /// The channel_update which should be sent.
1485 msg: msgs::ChannelUpdate,
1487 /// Used to indicate that a node_announcement should be broadcast to all peers.
1488 BroadcastNodeAnnouncement {
1489 /// The node_announcement which should be sent.
1490 msg: msgs::NodeAnnouncement,
1492 /// Used to indicate that a channel_update should be sent to a single peer.
1493 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1494 /// private channel and we shouldn't be informing all of our peers of channel parameters.
1496 /// The node_id of the node which should receive this message
1498 /// The channel_update which should be sent.
1499 msg: msgs::ChannelUpdate,
1501 /// Broadcast an error downstream to be handled
1503 /// The node_id of the node which should receive this message
1505 /// The action which should be taken.
1506 action: msgs::ErrorAction
1508 /// Query a peer for channels with funding transaction UTXOs in a block range.
1509 SendChannelRangeQuery {
1510 /// The node_id of this message recipient
1512 /// The query_channel_range which should be sent.
1513 msg: msgs::QueryChannelRange,
1515 /// Request routing gossip messages from a peer for a list of channels identified by
1516 /// their short_channel_ids.
1518 /// The node_id of this message recipient
1520 /// The query_short_channel_ids which should be sent.
1521 msg: msgs::QueryShortChannelIds,
1523 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1524 /// emitted during processing of the query.
1525 SendReplyChannelRange {
1526 /// The node_id of this message recipient
1528 /// The reply_channel_range which should be sent.
1529 msg: msgs::ReplyChannelRange,
1531 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1532 /// enable receiving gossip messages from the peer.
1533 SendGossipTimestampFilter {
1534 /// The node_id of this message recipient
1536 /// The gossip_timestamp_filter which should be sent.
1537 msg: msgs::GossipTimestampFilter,
1541 /// A trait indicating an object may generate message send events
1542 pub trait MessageSendEventsProvider {
1543 /// Gets the list of pending events which were generated by previous actions, clearing the list
1545 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1548 /// A trait indicating an object may generate onion messages to send
1549 pub trait OnionMessageProvider {
1550 /// Gets the next pending onion message for the peer with the given node id.
1551 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<msgs::OnionMessage>;
1554 /// A trait indicating an object may generate events.
1556 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1558 /// Implementations of this trait may also feature an async version of event handling, as shown with
1559 /// [`ChannelManager::process_pending_events_async`] and
1560 /// [`ChainMonitor::process_pending_events_async`].
1564 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1565 /// event since the last invocation.
1567 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1568 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1569 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1570 /// relevant changes to disk *before* returning.
1572 /// Further, because an application may crash between an [`Event`] being handled and the
1573 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1574 /// effect, [`Event`]s may be replayed.
1576 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1577 /// consult the provider's documentation on the implication of processing events and how a handler
1578 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1579 /// [`ChainMonitor::process_pending_events`]).
1581 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1584 /// [`process_pending_events`]: Self::process_pending_events
1585 /// [`handle_event`]: EventHandler::handle_event
1586 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1587 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1588 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
1589 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
1590 pub trait EventsProvider {
1591 /// Processes any events generated since the last call using the given event handler.
1593 /// See the trait-level documentation for requirements.
1594 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1597 /// A trait implemented for objects handling events from [`EventsProvider`].
1599 /// An async variation also exists for implementations of [`EventsProvider`] that support async
1600 /// event handling. The async event handler should satisfy the generic bounds: `F:
1601 /// core::future::Future, H: Fn(Event) -> F`.
1602 pub trait EventHandler {
1603 /// Handles the given [`Event`].
1605 /// See [`EventsProvider`] for details that must be considered when implementing this method.
1606 fn handle_event(&self, event: Event);
1609 impl<F> EventHandler for F where F: Fn(Event) {
1610 fn handle_event(&self, event: Event) {
1615 impl<T: EventHandler> EventHandler for Arc<T> {
1616 fn handle_event(&self, event: Event) {
1617 self.deref().handle_event(event)