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, RecipientOnionFields};
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 fields in the onion which were received with each HTLC. Only fields which were
346 /// identical in each HTLC involved in the payment will be included here.
348 /// Payments received on LDK versions prior to 0.0.115 will have this field unset.
349 onion_fields: Option<RecipientOnionFields>,
350 /// The value, in thousandths of a satoshi, that this payment is for.
352 /// Information for claiming this received payment, based on whether the purpose of the
353 /// payment is to pay an invoice or to send a spontaneous payment.
354 purpose: PaymentPurpose,
355 /// The `channel_id` indicating over which channel we received the payment.
356 via_channel_id: Option<[u8; 32]>,
357 /// The `user_channel_id` indicating over which channel we received the payment.
358 via_user_channel_id: Option<u128>,
359 /// The block height at which this payment will be failed back and will no longer be
360 /// eligible for claiming.
362 /// Prior to this height, a call to [`ChannelManager::claim_funds`] is guaranteed to
363 /// succeed, however you should wait for [`Event::PaymentClaimed`] to be sure.
365 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
366 claim_deadline: Option<u32>,
368 /// Indicates a payment has been claimed and we've received money!
370 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
371 /// to an [`Event::PaymentClaimable`]. However, if we previously crashed during a
372 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
373 /// [`Event::PaymentClaimable`] event.
376 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
377 /// `PaymentClaimable` events may be generated for the same payment. If you then call
378 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentClaimable`] you may get
379 /// multiple `PaymentClaimed` events.
381 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
383 /// The node that received the payment.
384 /// This is useful to identify payments which were received via [phantom nodes].
385 /// This field will always be filled in when the event was generated by LDK versions
386 /// 0.0.113 and above.
388 /// [phantom nodes]: crate::chain::keysinterface::PhantomKeysManager
389 receiver_node_id: Option<PublicKey>,
390 /// The payment hash of the claimed payment. Note that LDK will not stop you from
391 /// registering duplicate payment hashes for inbound payments.
392 payment_hash: PaymentHash,
393 /// The value, in thousandths of a satoshi, that this payment is for.
395 /// The purpose of the claimed payment, i.e. whether the payment was for an invoice or a
396 /// spontaneous payment.
397 purpose: PaymentPurpose,
399 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
400 /// and we got back the payment preimage for it).
402 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
403 /// event. In this situation, you SHOULD treat this payment as having succeeded.
405 /// The `payment_id` passed to [`ChannelManager::send_payment`].
407 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
408 payment_id: Option<PaymentId>,
409 /// The preimage to the hash given to ChannelManager::send_payment.
410 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
411 /// store it somehow!
412 payment_preimage: PaymentPreimage,
413 /// The hash that was given to [`ChannelManager::send_payment`].
415 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
416 payment_hash: PaymentHash,
417 /// The total fee which was spent at intermediate hops in this payment, across all paths.
419 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
420 /// overpayment to the recipient node.
422 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
423 /// overstate the amount paid, though this is unlikely.
425 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
426 fee_paid_msat: Option<u64>,
428 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
429 /// provide failure information for each path attempt in the payment, including retries.
431 /// This event is provided once there are no further pending HTLCs for the payment and the
432 /// payment is no longer retryable, due either to the [`Retry`] provided or
433 /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment.
435 /// [`Retry`]: crate::ln::channelmanager::Retry
436 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
438 /// The `payment_id` passed to [`ChannelManager::send_payment`].
440 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
441 payment_id: PaymentId,
442 /// The hash that was given to [`ChannelManager::send_payment`].
444 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
445 payment_hash: PaymentHash,
447 /// Indicates that a path for an outbound payment was successful.
449 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
450 /// [`Event::PaymentSent`] for obtaining the payment preimage.
451 PaymentPathSuccessful {
452 /// The `payment_id` passed to [`ChannelManager::send_payment`].
454 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
455 payment_id: PaymentId,
456 /// The hash that was given to [`ChannelManager::send_payment`].
458 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
459 payment_hash: Option<PaymentHash>,
460 /// The payment path that was successful.
462 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
465 /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to
468 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
469 /// [`Event::PaymentFailed`].
471 /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have
474 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
476 /// The `payment_id` passed to [`ChannelManager::send_payment`].
478 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
479 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
480 payment_id: Option<PaymentId>,
481 /// The hash that was given to [`ChannelManager::send_payment`].
483 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
484 payment_hash: PaymentHash,
485 /// Indicates the payment was rejected for some reason by the recipient. This implies that
486 /// the payment has failed, not just the route in question. If this is not set, the payment may
487 /// be retried via a different route.
488 payment_failed_permanently: bool,
489 /// Extra error details based on the failure type. May contain an update that needs to be
490 /// applied to the [`NetworkGraph`].
492 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
493 failure: PathFailure,
494 /// The payment path that failed.
496 /// The channel responsible for the failed payment path.
498 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
499 /// may not refer to a channel in the public network graph. These aliases may also collide
500 /// with channels in the public network graph.
502 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
503 /// retried. May be `None` for older [`Event`] serializations.
504 short_channel_id: Option<u64>,
506 error_code: Option<u16>,
508 error_data: Option<Vec<u8>>,
510 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
512 /// The id returned by [`ChannelManager::send_probe`].
514 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
515 payment_id: PaymentId,
516 /// The hash generated by [`ChannelManager::send_probe`].
518 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
519 payment_hash: PaymentHash,
520 /// The payment path that was successful.
523 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
525 /// The id returned by [`ChannelManager::send_probe`].
527 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
528 payment_id: PaymentId,
529 /// The hash generated by [`ChannelManager::send_probe`].
531 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
532 payment_hash: PaymentHash,
533 /// The payment path that failed.
535 /// The channel responsible for the failed probe.
537 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
538 /// may not refer to a channel in the public network graph. These aliases may also collide
539 /// with channels in the public network graph.
540 short_channel_id: Option<u64>,
542 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
543 /// a time in the future.
545 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
546 PendingHTLCsForwardable {
547 /// The minimum amount of time that should be waited prior to calling
548 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
549 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
550 /// now + 5*time_forwardable).
551 time_forwardable: Duration,
553 /// Used to indicate that we've intercepted an HTLC forward. This event will only be generated if
554 /// you've encoded an intercept scid in the receiver's invoice route hints using
555 /// [`ChannelManager::get_intercept_scid`] and have set [`UserConfig::accept_intercept_htlcs`].
557 /// [`ChannelManager::forward_intercepted_htlc`] or
558 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to this event. See
559 /// their docs for more information.
561 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
562 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
563 /// [`ChannelManager::forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
564 /// [`ChannelManager::fail_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::fail_intercepted_htlc
566 /// An id to help LDK identify which HTLC is being forwarded or failed.
567 intercept_id: InterceptId,
568 /// The fake scid that was programmed as the next hop's scid, generated using
569 /// [`ChannelManager::get_intercept_scid`].
571 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
572 requested_next_hop_scid: u64,
573 /// The payment hash used for this HTLC.
574 payment_hash: PaymentHash,
575 /// How many msats were received on the inbound edge of this HTLC.
576 inbound_amount_msat: u64,
577 /// How many msats the payer intended to route to the next node. Depending on the reason you are
578 /// intercepting this payment, you might take a fee by forwarding less than this amount.
580 /// Note that LDK will NOT check that expected fees were factored into this value. You MUST
581 /// check that whatever fee you want has been included here or subtract it as required. Further,
582 /// LDK will not stop you from forwarding more than you received.
583 expected_outbound_amount_msat: u64,
585 /// Used to indicate that an output which you should know how to spend was confirmed on chain
586 /// and is now spendable.
587 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
588 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
589 /// somewhere and spend them when you create on-chain transactions.
591 /// The outputs which you should store as spendable by you.
592 outputs: Vec<SpendableOutputDescriptor>,
594 /// This event is generated when a payment has been successfully forwarded through us and a
595 /// forwarding fee earned.
597 /// The incoming channel between the previous node and us. This is only `None` for events
598 /// generated or serialized by versions prior to 0.0.107.
599 prev_channel_id: Option<[u8; 32]>,
600 /// The outgoing channel between the next node and us. This is only `None` for events
601 /// generated or serialized by versions prior to 0.0.107.
602 next_channel_id: Option<[u8; 32]>,
603 /// The fee, in milli-satoshis, which was earned as a result of the payment.
605 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
606 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
607 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
608 /// claimed the full value in millisatoshis from the source. In this case,
609 /// `claim_from_onchain_tx` will be set.
611 /// If the channel which sent us the payment has been force-closed, we will claim the funds
612 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
613 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
614 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
616 fee_earned_msat: Option<u64>,
617 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
619 claim_from_onchain_tx: bool,
620 /// The final amount forwarded, in milli-satoshis, after the fee is deducted.
622 /// The caveat described above the `fee_earned_msat` field applies here as well.
623 outbound_amount_forwarded_msat: Option<u64>,
625 /// Used to indicate that a channel with the given `channel_id` is being opened and pending
626 /// confirmation on-chain.
628 /// This event is emitted when the funding transaction has been signed and is broadcast to the
629 /// network. For 0conf channels it will be immediately followed by the corresponding
630 /// [`Event::ChannelReady`] event.
632 /// The `channel_id` of the channel that is pending confirmation.
633 channel_id: [u8; 32],
634 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
635 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
636 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
637 /// `user_channel_id` will be randomized for an inbound channel.
639 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
640 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
641 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
642 user_channel_id: u128,
643 /// The `temporary_channel_id` this channel used to be known by during channel establishment.
645 /// Will be `None` for channels created prior to LDK version 0.0.115.
646 former_temporary_channel_id: Option<[u8; 32]>,
647 /// The `node_id` of the channel counterparty.
648 counterparty_node_id: PublicKey,
649 /// The outpoint of the channel's funding transaction.
650 funding_txo: OutPoint,
652 /// Used to indicate that a channel with the given `channel_id` is ready to
653 /// be used. This event is emitted either when the funding transaction has been confirmed
654 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
657 /// The `channel_id` of the channel that is ready.
658 channel_id: [u8; 32],
659 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
660 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
661 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
662 /// `user_channel_id` will be randomized for an inbound channel.
664 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
665 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
666 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
667 user_channel_id: u128,
668 /// The `node_id` of the channel counterparty.
669 counterparty_node_id: PublicKey,
670 /// The features that this channel will operate with.
671 channel_type: ChannelTypeFeatures,
673 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
674 /// process of closure.
676 /// The `channel_id` of the channel which has been closed. Note that on-chain transactions
677 /// resolving the channel are likely still awaiting confirmation.
678 channel_id: [u8; 32],
679 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
680 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
681 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
682 /// `user_channel_id` will be randomized for inbound channels.
683 /// This may be zero for inbound channels serialized prior to 0.0.113 and will always be
684 /// zero for objects serialized with LDK versions prior to 0.0.102.
686 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
687 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
688 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
689 user_channel_id: u128,
690 /// The reason the channel was closed.
691 reason: ClosureReason
693 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
694 /// inputs for another purpose.
696 /// The channel_id of the channel which has been closed.
697 channel_id: [u8; 32],
698 /// The full transaction received from the user
699 transaction: Transaction
701 /// Indicates a request to open a new channel by a peer.
703 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the
704 /// request, call [`ChannelManager::force_close_without_broadcasting_txn`].
706 /// The event is only triggered when a new open channel request is received and the
707 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
709 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
710 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
711 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
713 /// The temporary channel ID of the channel requested to be opened.
715 /// When responding to the request, the `temporary_channel_id` should be passed
716 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
717 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
719 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
720 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
721 temporary_channel_id: [u8; 32],
722 /// The node_id of the counterparty requesting to open the channel.
724 /// When responding to the request, the `counterparty_node_id` should be passed
725 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
726 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
729 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
730 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
731 counterparty_node_id: PublicKey,
732 /// The channel value of the requested channel.
733 funding_satoshis: u64,
734 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
736 /// The features that this channel will operate with. If you reject the channel, a
737 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
740 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
741 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
744 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
745 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
746 /// 0.0.107. Channels setting this type also need to get manually accepted via
747 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
748 /// or will be rejected otherwise.
750 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
751 channel_type: ChannelTypeFeatures,
753 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
756 /// Some scenarios where this event may be sent include:
757 /// * Insufficient capacity in the outbound channel
758 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
759 /// * When an unknown SCID is requested for forwarding a payment.
760 /// * Expected MPP amount has already been reached
761 /// * The HTLC has timed out
763 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
764 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
766 /// The channel over which the HTLC was received.
767 prev_channel_id: [u8; 32],
768 /// Destination of the HTLC that failed to be processed.
769 failed_next_destination: HTLCDestination,
772 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
773 /// requires confirmed external funds to be readily available to spend.
775 /// LDK does not currently generate this event. It is limited to the scope of channels with
776 /// anchor outputs, which will be introduced in a future release.
777 BumpTransaction(BumpTransactionEvent),
780 impl Writeable for Event {
781 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
783 &Event::FundingGenerationReady { .. } => {
785 // We never write out FundingGenerationReady events as, upon disconnection, peers
786 // drop any channels which have not yet exchanged funding_signed.
788 &Event::PaymentClaimable { ref payment_hash, ref amount_msat, ref purpose,
789 ref receiver_node_id, ref via_channel_id, ref via_user_channel_id,
790 ref claim_deadline, ref onion_fields
793 let mut payment_secret = None;
794 let payment_preimage;
796 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
797 payment_secret = Some(secret);
798 payment_preimage = *preimage;
800 PaymentPurpose::SpontaneousPayment(preimage) => {
801 payment_preimage = Some(*preimage);
804 write_tlv_fields!(writer, {
805 (0, payment_hash, required),
806 (1, receiver_node_id, option),
807 (2, payment_secret, option),
808 (3, via_channel_id, option),
809 (4, amount_msat, required),
810 (5, via_user_channel_id, option),
811 (6, 0u64, required), // user_payment_id required for compatibility with 0.0.103 and earlier
812 (7, claim_deadline, option),
813 (8, payment_preimage, option),
814 (9, onion_fields, option),
817 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
819 write_tlv_fields!(writer, {
820 (0, payment_preimage, required),
821 (1, payment_hash, required),
822 (3, payment_id, option),
823 (5, fee_paid_msat, option),
826 &Event::PaymentPathFailed {
827 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure,
828 ref path, ref short_channel_id,
836 error_code.write(writer)?;
838 error_data.write(writer)?;
839 write_tlv_fields!(writer, {
840 (0, payment_hash, required),
841 (1, None::<NetworkUpdate>, option), // network_update in LDK versions prior to 0.0.114
842 (2, payment_failed_permanently, required),
843 (3, false, required), // all_paths_failed in LDK versions prior to 0.0.114
844 (5, *path, vec_type),
845 (7, short_channel_id, option),
846 (9, None::<RouteParameters>, option), // retry in LDK versions prior to 0.0.115
847 (11, payment_id, option),
848 (13, failure, required),
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 {
874 fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
875 next_channel_id, outbound_amount_forwarded_msat
878 write_tlv_fields!(writer, {
879 (0, fee_earned_msat, option),
880 (1, prev_channel_id, option),
881 (2, claim_from_onchain_tx, required),
882 (3, next_channel_id, option),
883 (5, outbound_amount_forwarded_msat, option),
886 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
888 // `user_channel_id` used to be a single u64 value. In order to remain backwards
889 // compatible with versions prior to 0.0.113, the u128 is serialized as two
890 // separate u64 values.
891 let user_channel_id_low = *user_channel_id as u64;
892 let user_channel_id_high = (*user_channel_id >> 64) as u64;
893 write_tlv_fields!(writer, {
894 (0, channel_id, required),
895 (1, user_channel_id_low, required),
896 (2, reason, required),
897 (3, user_channel_id_high, required),
900 &Event::DiscardFunding { ref channel_id, ref transaction } => {
902 write_tlv_fields!(writer, {
903 (0, channel_id, required),
904 (2, transaction, required)
907 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
909 write_tlv_fields!(writer, {
910 (0, payment_id, required),
911 (2, payment_hash, option),
915 &Event::PaymentFailed { ref payment_id, ref payment_hash } => {
917 write_tlv_fields!(writer, {
918 (0, payment_id, required),
919 (2, payment_hash, required),
922 &Event::OpenChannelRequest { .. } => {
924 // We never write the OpenChannelRequest events as, upon disconnection, peers
925 // drop any channels which have not yet exchanged funding_signed.
927 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose, ref receiver_node_id } => {
929 write_tlv_fields!(writer, {
930 (0, payment_hash, required),
931 (1, receiver_node_id, option),
932 (2, purpose, required),
933 (4, amount_msat, required),
936 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
938 write_tlv_fields!(writer, {
939 (0, payment_id, required),
940 (2, payment_hash, required),
944 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
946 write_tlv_fields!(writer, {
947 (0, payment_id, required),
948 (2, payment_hash, required),
949 (4, *path, vec_type),
950 (6, short_channel_id, option),
953 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
955 write_tlv_fields!(writer, {
956 (0, prev_channel_id, required),
957 (2, failed_next_destination, required),
961 &Event::BumpTransaction(ref event)=> {
964 // We never write the ChannelClose|HTLCResolution events as they'll be replayed
965 // upon restarting anyway if they remain unresolved.
966 BumpTransactionEvent::ChannelClose { .. } => {}
967 BumpTransactionEvent::HTLCResolution { .. } => {}
969 write_tlv_fields!(writer, {}); // Write a length field for forwards compat
971 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
973 write_tlv_fields!(writer, {
974 (0, channel_id, required),
975 (2, user_channel_id, required),
976 (4, counterparty_node_id, required),
977 (6, channel_type, required),
980 &Event::ChannelPending { ref channel_id, ref user_channel_id, ref former_temporary_channel_id, ref counterparty_node_id, ref funding_txo } => {
982 write_tlv_fields!(writer, {
983 (0, channel_id, required),
984 (2, user_channel_id, required),
985 (4, former_temporary_channel_id, required),
986 (6, counterparty_node_id, required),
987 (8, funding_txo, required),
990 // Note that, going forward, all new events must only write data inside of
991 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
992 // data via `write_tlv_fields`.
997 impl MaybeReadable for Event {
998 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
999 match Readable::read(reader)? {
1000 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
1001 // unlike all other events, thus we return immediately here.
1005 let mut payment_hash = PaymentHash([0; 32]);
1006 let mut payment_preimage = None;
1007 let mut payment_secret = None;
1008 let mut amount_msat = 0;
1009 let mut receiver_node_id = None;
1010 let mut _user_payment_id = None::<u64>; // For compatibility with 0.0.103 and earlier
1011 let mut via_channel_id = None;
1012 let mut claim_deadline = None;
1013 let mut via_user_channel_id = None;
1014 let mut onion_fields = None;
1015 read_tlv_fields!(reader, {
1016 (0, payment_hash, required),
1017 (1, receiver_node_id, option),
1018 (2, payment_secret, option),
1019 (3, via_channel_id, option),
1020 (4, amount_msat, required),
1021 (5, via_user_channel_id, option),
1022 (6, _user_payment_id, option),
1023 (7, claim_deadline, option),
1024 (8, payment_preimage, option),
1025 (9, onion_fields, option),
1027 let purpose = match payment_secret {
1028 Some(secret) => PaymentPurpose::InvoicePayment {
1030 payment_secret: secret
1032 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
1033 None => return Err(msgs::DecodeError::InvalidValue),
1035 Ok(Some(Event::PaymentClaimable {
1041 via_user_channel_id,
1050 let mut payment_preimage = PaymentPreimage([0; 32]);
1051 let mut payment_hash = None;
1052 let mut payment_id = None;
1053 let mut fee_paid_msat = None;
1054 read_tlv_fields!(reader, {
1055 (0, payment_preimage, required),
1056 (1, payment_hash, option),
1057 (3, payment_id, option),
1058 (5, fee_paid_msat, option),
1060 if payment_hash.is_none() {
1061 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
1063 Ok(Some(Event::PaymentSent {
1066 payment_hash: payment_hash.unwrap(),
1075 let error_code = Readable::read(reader)?;
1077 let error_data = Readable::read(reader)?;
1078 let mut payment_hash = PaymentHash([0; 32]);
1079 let mut payment_failed_permanently = false;
1080 let mut network_update = None;
1081 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1082 let mut short_channel_id = None;
1083 let mut payment_id = None;
1084 let mut failure_opt = None;
1085 read_tlv_fields!(reader, {
1086 (0, payment_hash, required),
1087 (1, network_update, upgradable_option),
1088 (2, payment_failed_permanently, required),
1089 (5, path, vec_type),
1090 (7, short_channel_id, option),
1091 (11, payment_id, option),
1092 (13, failure_opt, upgradable_option),
1094 let failure = failure_opt.unwrap_or_else(|| PathFailure::OnPath { network_update });
1095 Ok(Some(Event::PaymentPathFailed {
1098 payment_failed_permanently,
1100 path: path.unwrap(),
1113 let mut outputs = WithoutLength(Vec::new());
1114 read_tlv_fields!(reader, {
1115 (0, outputs, required),
1117 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
1122 let mut payment_hash = PaymentHash([0; 32]);
1123 let mut intercept_id = InterceptId([0; 32]);
1124 let mut requested_next_hop_scid = InterceptNextHop::FakeScid { requested_next_hop_scid: 0 };
1125 let mut inbound_amount_msat = 0;
1126 let mut expected_outbound_amount_msat = 0;
1127 read_tlv_fields!(reader, {
1128 (0, intercept_id, required),
1129 (2, requested_next_hop_scid, required),
1130 (4, payment_hash, required),
1131 (6, inbound_amount_msat, required),
1132 (8, expected_outbound_amount_msat, required),
1134 let next_scid = match requested_next_hop_scid {
1135 InterceptNextHop::FakeScid { requested_next_hop_scid: scid } => scid
1137 Ok(Some(Event::HTLCIntercepted {
1139 requested_next_hop_scid: next_scid,
1140 inbound_amount_msat,
1141 expected_outbound_amount_msat,
1147 let mut fee_earned_msat = None;
1148 let mut prev_channel_id = None;
1149 let mut claim_from_onchain_tx = false;
1150 let mut next_channel_id = None;
1151 let mut outbound_amount_forwarded_msat = None;
1152 read_tlv_fields!(reader, {
1153 (0, fee_earned_msat, option),
1154 (1, prev_channel_id, option),
1155 (2, claim_from_onchain_tx, required),
1156 (3, next_channel_id, option),
1157 (5, outbound_amount_forwarded_msat, option),
1159 Ok(Some(Event::PaymentForwarded {
1160 fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id,
1161 outbound_amount_forwarded_msat
1168 let mut channel_id = [0; 32];
1169 let mut reason = UpgradableRequired(None);
1170 let mut user_channel_id_low_opt: Option<u64> = None;
1171 let mut user_channel_id_high_opt: Option<u64> = None;
1172 read_tlv_fields!(reader, {
1173 (0, channel_id, required),
1174 (1, user_channel_id_low_opt, option),
1175 (2, reason, upgradable_required),
1176 (3, user_channel_id_high_opt, option),
1179 // `user_channel_id` used to be a single u64 value. In order to remain
1180 // backwards compatible with versions prior to 0.0.113, the u128 is serialized
1181 // as two separate u64 values.
1182 let user_channel_id = (user_channel_id_low_opt.unwrap_or(0) as u128) +
1183 ((user_channel_id_high_opt.unwrap_or(0) as u128) << 64);
1185 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: _init_tlv_based_struct_field!(reason, upgradable_required) }))
1191 let mut channel_id = [0; 32];
1192 let mut transaction = Transaction{ version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
1193 read_tlv_fields!(reader, {
1194 (0, channel_id, required),
1195 (2, transaction, required),
1197 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1203 let mut payment_id = PaymentId([0; 32]);
1204 let mut payment_hash = None;
1205 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1206 read_tlv_fields!(reader, {
1207 (0, payment_id, required),
1208 (2, payment_hash, option),
1209 (4, path, vec_type),
1211 Ok(Some(Event::PaymentPathSuccessful {
1214 path: path.unwrap(),
1221 let mut payment_hash = PaymentHash([0; 32]);
1222 let mut payment_id = PaymentId([0; 32]);
1223 read_tlv_fields!(reader, {
1224 (0, payment_id, required),
1225 (2, payment_hash, required),
1227 Ok(Some(Event::PaymentFailed {
1235 // Value 17 is used for `Event::OpenChannelRequest`.
1240 let mut payment_hash = PaymentHash([0; 32]);
1241 let mut purpose = UpgradableRequired(None);
1242 let mut amount_msat = 0;
1243 let mut receiver_node_id = None;
1244 read_tlv_fields!(reader, {
1245 (0, payment_hash, required),
1246 (1, receiver_node_id, option),
1247 (2, purpose, upgradable_required),
1248 (4, amount_msat, required),
1250 Ok(Some(Event::PaymentClaimed {
1253 purpose: _init_tlv_based_struct_field!(purpose, upgradable_required),
1261 let mut payment_id = PaymentId([0; 32]);
1262 let mut payment_hash = PaymentHash([0; 32]);
1263 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1264 read_tlv_fields!(reader, {
1265 (0, payment_id, required),
1266 (2, payment_hash, required),
1267 (4, path, vec_type),
1269 Ok(Some(Event::ProbeSuccessful {
1272 path: path.unwrap(),
1279 let mut payment_id = PaymentId([0; 32]);
1280 let mut payment_hash = PaymentHash([0; 32]);
1281 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1282 let mut short_channel_id = None;
1283 read_tlv_fields!(reader, {
1284 (0, payment_id, required),
1285 (2, payment_hash, required),
1286 (4, path, vec_type),
1287 (6, short_channel_id, option),
1289 Ok(Some(Event::ProbeFailed {
1292 path: path.unwrap(),
1300 let mut prev_channel_id = [0; 32];
1301 let mut failed_next_destination_opt = UpgradableRequired(None);
1302 read_tlv_fields!(reader, {
1303 (0, prev_channel_id, required),
1304 (2, failed_next_destination_opt, upgradable_required),
1306 Ok(Some(Event::HTLCHandlingFailed {
1308 failed_next_destination: _init_tlv_based_struct_field!(failed_next_destination_opt, upgradable_required),
1316 let mut channel_id = [0; 32];
1317 let mut user_channel_id: u128 = 0;
1318 let mut counterparty_node_id = RequiredWrapper(None);
1319 let mut channel_type = RequiredWrapper(None);
1320 read_tlv_fields!(reader, {
1321 (0, channel_id, required),
1322 (2, user_channel_id, required),
1323 (4, counterparty_node_id, required),
1324 (6, channel_type, required),
1327 Ok(Some(Event::ChannelReady {
1330 counterparty_node_id: counterparty_node_id.0.unwrap(),
1331 channel_type: channel_type.0.unwrap()
1338 let mut channel_id = [0; 32];
1339 let mut user_channel_id: u128 = 0;
1340 let mut former_temporary_channel_id = None;
1341 let mut counterparty_node_id = RequiredWrapper(None);
1342 let mut funding_txo = RequiredWrapper(None);
1343 read_tlv_fields!(reader, {
1344 (0, channel_id, required),
1345 (2, user_channel_id, required),
1346 (4, former_temporary_channel_id, required),
1347 (6, counterparty_node_id, required),
1348 (8, funding_txo, required),
1351 Ok(Some(Event::ChannelPending {
1354 former_temporary_channel_id,
1355 counterparty_node_id: counterparty_node_id.0.unwrap(),
1356 funding_txo: funding_txo.0.unwrap()
1361 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1362 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1364 x if x % 2 == 1 => {
1365 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1366 // which prefixes the whole thing with a length BigSize. Because the event is
1367 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1368 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1369 // exactly the number of bytes specified, ignoring them entirely.
1370 let tlv_len: BigSize = Readable::read(reader)?;
1371 FixedLengthReader::new(reader, tlv_len.0)
1372 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1375 _ => Err(msgs::DecodeError::InvalidValue)
1380 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1381 /// broadcast to most peers).
1382 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1383 #[derive(Clone, Debug)]
1384 pub enum MessageSendEvent {
1385 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1386 /// message provided to the given peer.
1388 /// The node_id of the node which should receive this message
1390 /// The message which should be sent.
1391 msg: msgs::AcceptChannel,
1393 /// Used to indicate that we've initiated a channel open and should send the open_channel
1394 /// message provided to the given peer.
1396 /// The node_id of the node which should receive this message
1398 /// The message which should be sent.
1399 msg: msgs::OpenChannel,
1401 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1402 SendFundingCreated {
1403 /// The node_id of the node which should receive this message
1405 /// The message which should be sent.
1406 msg: msgs::FundingCreated,
1408 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1410 /// The node_id of the node which should receive this message
1412 /// The message which should be sent.
1413 msg: msgs::FundingSigned,
1415 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1417 /// The node_id of the node which should receive these message(s)
1419 /// The channel_ready message which should be sent.
1420 msg: msgs::ChannelReady,
1422 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1423 SendAnnouncementSignatures {
1424 /// The node_id of the node which should receive these message(s)
1426 /// The announcement_signatures message which should be sent.
1427 msg: msgs::AnnouncementSignatures,
1429 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1430 /// message should be sent to the peer with the given node_id.
1432 /// The node_id of the node which should receive these message(s)
1434 /// The update messages which should be sent. ALL messages in the struct should be sent!
1435 updates: msgs::CommitmentUpdate,
1437 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1439 /// The node_id of the node which should receive this message
1441 /// The message which should be sent.
1442 msg: msgs::RevokeAndACK,
1444 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1446 /// The node_id of the node which should receive this message
1448 /// The message which should be sent.
1449 msg: msgs::ClosingSigned,
1451 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1453 /// The node_id of the node which should receive this message
1455 /// The message which should be sent.
1456 msg: msgs::Shutdown,
1458 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1459 SendChannelReestablish {
1460 /// The node_id of the node which should receive this message
1462 /// The message which should be sent.
1463 msg: msgs::ChannelReestablish,
1465 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1466 /// initial connection to ensure our peers know about our channels.
1467 SendChannelAnnouncement {
1468 /// The node_id of the node which should receive this message
1470 /// The channel_announcement which should be sent.
1471 msg: msgs::ChannelAnnouncement,
1472 /// The followup channel_update which should be sent.
1473 update_msg: msgs::ChannelUpdate,
1475 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1476 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1478 /// Note that after doing so, you very likely (unless you did so very recently) want to
1479 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1480 /// ensures that any nodes which see our channel_announcement also have a relevant
1481 /// node_announcement, including relevant feature flags which may be important for routing
1482 /// through or to us.
1484 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1485 BroadcastChannelAnnouncement {
1486 /// The channel_announcement which should be sent.
1487 msg: msgs::ChannelAnnouncement,
1488 /// The followup channel_update which should be sent.
1489 update_msg: Option<msgs::ChannelUpdate>,
1491 /// Used to indicate that a channel_update should be broadcast to all peers.
1492 BroadcastChannelUpdate {
1493 /// The channel_update which should be sent.
1494 msg: msgs::ChannelUpdate,
1496 /// Used to indicate that a node_announcement should be broadcast to all peers.
1497 BroadcastNodeAnnouncement {
1498 /// The node_announcement which should be sent.
1499 msg: msgs::NodeAnnouncement,
1501 /// Used to indicate that a channel_update should be sent to a single peer.
1502 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1503 /// private channel and we shouldn't be informing all of our peers of channel parameters.
1505 /// The node_id of the node which should receive this message
1507 /// The channel_update which should be sent.
1508 msg: msgs::ChannelUpdate,
1510 /// Broadcast an error downstream to be handled
1512 /// The node_id of the node which should receive this message
1514 /// The action which should be taken.
1515 action: msgs::ErrorAction
1517 /// Query a peer for channels with funding transaction UTXOs in a block range.
1518 SendChannelRangeQuery {
1519 /// The node_id of this message recipient
1521 /// The query_channel_range which should be sent.
1522 msg: msgs::QueryChannelRange,
1524 /// Request routing gossip messages from a peer for a list of channels identified by
1525 /// their short_channel_ids.
1527 /// The node_id of this message recipient
1529 /// The query_short_channel_ids which should be sent.
1530 msg: msgs::QueryShortChannelIds,
1532 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1533 /// emitted during processing of the query.
1534 SendReplyChannelRange {
1535 /// The node_id of this message recipient
1537 /// The reply_channel_range which should be sent.
1538 msg: msgs::ReplyChannelRange,
1540 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1541 /// enable receiving gossip messages from the peer.
1542 SendGossipTimestampFilter {
1543 /// The node_id of this message recipient
1545 /// The gossip_timestamp_filter which should be sent.
1546 msg: msgs::GossipTimestampFilter,
1550 /// A trait indicating an object may generate message send events
1551 pub trait MessageSendEventsProvider {
1552 /// Gets the list of pending events which were generated by previous actions, clearing the list
1554 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1557 /// A trait indicating an object may generate onion messages to send
1558 pub trait OnionMessageProvider {
1559 /// Gets the next pending onion message for the peer with the given node id.
1560 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<msgs::OnionMessage>;
1563 /// A trait indicating an object may generate events.
1565 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1567 /// Implementations of this trait may also feature an async version of event handling, as shown with
1568 /// [`ChannelManager::process_pending_events_async`] and
1569 /// [`ChainMonitor::process_pending_events_async`].
1573 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1574 /// event since the last invocation.
1576 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1577 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1578 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1579 /// relevant changes to disk *before* returning.
1581 /// Further, because an application may crash between an [`Event`] being handled and the
1582 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1583 /// effect, [`Event`]s may be replayed.
1585 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1586 /// consult the provider's documentation on the implication of processing events and how a handler
1587 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1588 /// [`ChainMonitor::process_pending_events`]).
1590 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1593 /// [`process_pending_events`]: Self::process_pending_events
1594 /// [`handle_event`]: EventHandler::handle_event
1595 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1596 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1597 /// [`ChannelManager::process_pending_events_async`]: crate::ln::channelmanager::ChannelManager::process_pending_events_async
1598 /// [`ChainMonitor::process_pending_events_async`]: crate::chain::chainmonitor::ChainMonitor::process_pending_events_async
1599 pub trait EventsProvider {
1600 /// Processes any events generated since the last call using the given event handler.
1602 /// See the trait-level documentation for requirements.
1603 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1606 /// A trait implemented for objects handling events from [`EventsProvider`].
1608 /// An async variation also exists for implementations of [`EventsProvider`] that support async
1609 /// event handling. The async event handler should satisfy the generic bounds: `F:
1610 /// core::future::Future, H: Fn(Event) -> F`.
1611 pub trait EventHandler {
1612 /// Handles the given [`Event`].
1614 /// See [`EventsProvider`] for details that must be considered when implementing this method.
1615 fn handle_event(&self, event: Event);
1618 impl<F> EventHandler for F where F: Fn(Event) {
1619 fn handle_event(&self, event: Event) {
1624 impl<T: EventHandler> EventHandler for Arc<T> {
1625 fn handle_event(&self, event: Event) {
1626 self.deref().handle_event(event)