1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Events are returned from various bits in the library which indicate some action must be taken
13 //! Because we don't have a built-in runtime, it's up to the client to call events at a time in the
14 //! future, as well as generate and broadcast funding transactions handle payment preimages and a
17 use crate::chain::keysinterface::SpendableOutputDescriptor;
19 use crate::ln::chan_utils::HTLCOutputInCommitment;
20 use crate::ln::channelmanager::PaymentId;
21 use crate::ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
22 use crate::ln::features::ChannelTypeFeatures;
24 use crate::ln::msgs::DecodeError;
25 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
26 use crate::routing::gossip::NetworkUpdate;
27 use crate::util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, WithoutLength, OptionDeserWrapper};
28 use crate::routing::router::{RouteHop, RouteParameters};
30 use bitcoin::{PackedLockTime, Transaction};
32 use bitcoin::OutPoint;
33 use bitcoin::blockdata::script::Script;
34 use bitcoin::hashes::Hash;
35 use bitcoin::hashes::sha256::Hash as Sha256;
36 use bitcoin::secp256k1::PublicKey;
38 use crate::prelude::*;
39 use core::time::Duration;
43 /// Some information provided on receipt of payment depends on whether the payment received is a
44 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
45 #[derive(Clone, Debug)]
46 pub enum PaymentPurpose {
47 /// Information for receiving a payment that we generated an invoice for.
49 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
50 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
51 /// [`ChannelManager::claim_funds`].
53 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
54 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
55 payment_preimage: Option<PaymentPreimage>,
56 /// The "payment secret". This authenticates the sender to the recipient, preventing a
57 /// number of deanonymization attacks during the routing process.
58 /// It is provided here for your reference, however its accuracy is enforced directly by
59 /// [`ChannelManager`] using the values you previously provided to
60 /// [`ChannelManager::create_inbound_payment`] or
61 /// [`ChannelManager::create_inbound_payment_for_hash`].
63 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
64 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
65 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
66 payment_secret: PaymentSecret,
68 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
69 /// (the payee) providing a preimage.
70 SpontaneousPayment(PaymentPreimage),
73 impl_writeable_tlv_based_enum!(PaymentPurpose,
74 (0, InvoicePayment) => {
75 (0, payment_preimage, option),
76 (2, payment_secret, required),
78 (2, SpontaneousPayment)
81 #[derive(Clone, Debug, PartialEq, Eq)]
82 /// The reason the channel was closed. See individual variants more details.
83 pub enum ClosureReason {
84 /// Closure generated from receiving a peer error message.
86 /// Our counterparty may have broadcasted their latest commitment state, and we have
88 CounterpartyForceClosed {
89 /// The error which the peer sent us.
91 /// The string should be sanitized before it is used (e.g emitted to logs
92 /// or printed to stdout). Otherwise, a well crafted error message may exploit
93 /// a security vulnerability in the terminal emulator or the logging subsystem.
96 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
98 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
100 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
101 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
102 //TODO: split between CounterpartyInitiated/LocallyInitiated
104 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
105 /// commitment transaction came from our counterparty, but it may also have come from
106 /// a copy of our own `ChannelMonitor`.
107 CommitmentTxConfirmed,
108 /// The funding transaction failed to confirm in a timely manner on an inbound channel.
110 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
112 /// A developer-readable error message which we generated.
115 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
116 /// forget the channel entirely - we can attempt again if the peer reconnects.
118 /// This includes cases where we restarted prior to funding completion, including prior to the
119 /// initial [`ChannelMonitor`] persistence completing.
121 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
122 /// peer because of mutual incompatibility between us and our channel counterparty.
124 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
126 /// Closure generated from `ChannelManager::read` if the [`ChannelMonitor`] is newer than
127 /// the [`ChannelManager`] deserialized.
129 /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
130 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
131 OutdatedChannelManager
134 impl core::fmt::Display for ClosureReason {
135 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
136 f.write_str("Channel closed because ")?;
138 ClosureReason::CounterpartyForceClosed { peer_msg } => {
139 f.write_str("counterparty force-closed with message ")?;
140 f.write_str(&peer_msg)
142 ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
143 ClosureReason::CooperativeClosure => f.write_str("the channel was cooperatively closed"),
144 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
145 ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
146 ClosureReason::ProcessingError { err } => {
147 f.write_str("of an exception: ")?;
150 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
151 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
156 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
157 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
158 (1, FundingTimedOut) => {},
159 (2, HolderForceClosed) => {},
160 (6, CommitmentTxConfirmed) => {},
161 (4, CooperativeClosure) => {},
162 (8, ProcessingError) => { (1, err, required) },
163 (10, DisconnectedPeer) => {},
164 (12, OutdatedChannelManager) => {},
167 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
168 #[derive(Clone, Debug, PartialEq, Eq)]
169 pub enum HTLCDestination {
170 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
171 /// there is insufficient capacity in our outbound channel.
173 /// The `node_id` of the next node. For backwards compatibility, this field is
174 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
175 /// counterparty node information.
176 node_id: Option<PublicKey>,
177 /// The outgoing `channel_id` between us and the next node.
178 channel_id: [u8; 32],
180 /// Scenario where we are unsure of the next node to forward the HTLC to.
182 /// Short channel id we are requesting to forward an HTLC to.
183 requested_forward_scid: u64,
185 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
186 /// but is invalid for some reason, so we reject it.
188 /// Some of the reasons may include:
190 /// * Expected MPP amount to claim does not equal HTLC total
191 /// * Claimable amount does not match expected amount
193 /// The payment hash of the payment we attempted to process.
194 payment_hash: PaymentHash
198 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
199 (0, NextHopChannel) => {
200 (0, node_id, required),
201 (2, channel_id, required),
203 (2, UnknownNextHop) => {
204 (0, requested_forward_scid, required),
206 (4, FailedPayment) => {
207 (0, payment_hash, required),
212 /// A descriptor used to sign for a commitment transaction's anchor output.
213 #[derive(Clone, Debug)]
214 pub struct AnchorDescriptor {
215 /// A unique identifier used along with `channel_value_satoshis` to re-derive the
216 /// [`InMemorySigner`] required to sign `input`.
218 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
219 pub channel_keys_id: [u8; 32],
220 /// The value in satoshis of the channel we're attempting to spend the anchor output of. This is
221 /// used along with `channel_keys_id` to re-derive the [`InMemorySigner`] required to sign
224 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
225 pub channel_value_satoshis: u64,
226 /// The transaction input's outpoint corresponding to the commitment transaction's anchor
228 pub outpoint: OutPoint,
232 /// Represents the different types of transactions, originating from LDK, to be bumped.
233 #[derive(Clone, Debug)]
234 pub enum BumpTransactionEvent {
235 /// Indicates that a channel featuring anchor outputs is to be closed by broadcasting the local
236 /// commitment transaction. Since commitment transactions have a static feerate pre-agreed upon,
237 /// they may need additional fees to be attached through a child transaction using the popular
238 /// [Child-Pays-For-Parent](https://bitcoinops.org/en/topics/cpfp) fee bumping technique. This
239 /// child transaction must include the anchor input described within `anchor_descriptor` along
240 /// with additional inputs to meet the target feerate. Failure to meet the target feerate
241 /// decreases the confirmation odds of the transaction package (which includes the commitment
242 /// and child anchor transactions), possibly resulting in a loss of funds. Once the transaction
243 /// is constructed, it must be fully signed for and broadcasted by the consumer of the event
244 /// along with the `commitment_tx` enclosed. Note that the `commitment_tx` must always be
245 /// broadcast first, as the child anchor transaction depends on it.
247 /// The consumer should be able to sign for any of the additional inputs included within the
248 /// child anchor transaction. To sign its anchor input, an [`InMemorySigner`] should be
249 /// re-derived through [`KeysManager::derive_channel_keys`] with the help of
250 /// [`AnchorDescriptor::channel_keys_id`] and [`AnchorDescriptor::channel_value_satoshis`].
252 /// It is possible to receive more than one instance of this event if a valid child anchor
253 /// transaction is never broadcast or is but not with a sufficient fee to be mined. Care should
254 /// be taken by the consumer of the event to ensure any future iterations of the child anchor
255 /// transaction adhere to the [Replace-By-Fee
256 /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
257 /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
258 /// these events is not user-controlled, users may ignore/drop the event if they are no longer
259 /// able to commit external confirmed funds to the child anchor transaction.
261 /// The set of `pending_htlcs` on the commitment transaction to be broadcast can be inspected to
262 /// determine whether a significant portion of the channel's funds are allocated to HTLCs,
263 /// enabling users to make their own decisions regarding the importance of the commitment
264 /// transaction's confirmation. Note that this is not required, but simply exists as an option
265 /// for users to override LDK's behavior. On commitments with no HTLCs (indicated by those with
266 /// an empty `pending_htlcs`), confirmation of the commitment transaction can be considered to
269 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
270 /// [`KeysManager::derive_channel_keys`]: crate::chain::keysinterface::KeysManager::derive_channel_keys
272 /// The target feerate that the transaction package, which consists of the commitment
273 /// transaction and the to-be-crafted child anchor transaction, must meet.
274 package_target_feerate_sat_per_1000_weight: u32,
275 /// The channel's commitment transaction to bump the fee of. This transaction should be
276 /// broadcast along with the anchor transaction constructed as a result of consuming this
278 commitment_tx: Transaction,
279 /// The absolute fee in satoshis of the commitment transaction. This can be used along the
280 /// with weight of the commitment transaction to determine its feerate.
281 commitment_tx_fee_satoshis: u64,
282 /// The descriptor to sign the anchor input of the anchor transaction constructed as a
283 /// result of consuming this event.
284 anchor_descriptor: AnchorDescriptor,
285 /// The set of pending HTLCs on the commitment transaction that need to be resolved once the
286 /// commitment transaction confirms.
287 pending_htlcs: Vec<HTLCOutputInCommitment>,
291 /// An Event which you should probably take some action in response to.
293 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
294 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
295 /// written as it makes no sense to respond to it after reconnecting to peers).
296 #[derive(Clone, Debug)]
298 /// Used to indicate that the client should generate a funding transaction with the given
299 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
300 /// Generated in [`ChannelManager`] message handling.
301 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
302 /// counterparty can steal your funds!
304 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
305 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
306 FundingGenerationReady {
307 /// The random channel_id we picked which you'll need to pass into
308 /// [`ChannelManager::funding_transaction_generated`].
310 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
311 temporary_channel_id: [u8; 32],
312 /// The counterparty's node_id, which you'll need to pass back into
313 /// [`ChannelManager::funding_transaction_generated`].
315 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
316 counterparty_node_id: PublicKey,
317 /// The value, in satoshis, that the output should have.
318 channel_value_satoshis: u64,
319 /// The script which should be used in the transaction output.
320 output_script: Script,
321 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or 0 for
322 /// an inbound channel.
324 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
325 user_channel_id: u64,
327 /// Indicates we've received (an offer of) money! Just gotta dig out that payment preimage and
328 /// feed it to [`ChannelManager::claim_funds`] to get it....
330 /// Note that if the preimage is not known, you should call
331 /// [`ChannelManager::fail_htlc_backwards`] to free up resources for this HTLC and avoid
332 /// network congestion.
333 /// If you fail to call either [`ChannelManager::claim_funds`] or
334 /// [`ChannelManager::fail_htlc_backwards`] within the HTLC's timeout, the HTLC will be
335 /// automatically failed.
338 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
339 /// `PaymentReceived` events may be generated for the same payment.
341 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
342 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
344 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
345 /// not stop you from registering duplicate payment hashes for inbound payments.
346 payment_hash: PaymentHash,
347 /// The value, in thousandths of a satoshi, that this payment is for.
349 /// Information for claiming this received payment, based on whether the purpose of the
350 /// payment is to pay an invoice or to send a spontaneous payment.
351 purpose: PaymentPurpose,
353 /// Indicates a payment has been claimed and we've received money!
355 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
356 /// to an [`Event::PaymentReceived`]. However, if we previously crashed during a
357 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
358 /// [`Event::PaymentReceived`] event.
361 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
362 /// `PaymentReceived` events may be generated for the same payment. If you then call
363 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentReceived`] you may get
364 /// multiple `PaymentClaimed` events.
366 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
368 /// The payment hash of the claimed payment. Note that LDK will not stop you from
369 /// registering duplicate payment hashes for inbound payments.
370 payment_hash: PaymentHash,
371 /// The value, in thousandths of a satoshi, that this payment is for.
373 /// The purpose of this claimed payment, i.e. whether the payment was for an invoice or a
374 /// spontaneous payment.
375 purpose: PaymentPurpose,
377 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
378 /// and we got back the payment preimage for it).
380 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
381 /// event. In this situation, you SHOULD treat this payment as having succeeded.
383 /// The id returned by [`ChannelManager::send_payment`] and used with
384 /// [`ChannelManager::retry_payment`].
386 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
387 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
388 payment_id: Option<PaymentId>,
389 /// The preimage to the hash given to ChannelManager::send_payment.
390 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
391 /// store it somehow!
392 payment_preimage: PaymentPreimage,
393 /// The hash that was given to [`ChannelManager::send_payment`].
395 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
396 payment_hash: PaymentHash,
397 /// The total fee which was spent at intermediate hops in this payment, across all paths.
399 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
400 /// overpayment to the recipient node.
402 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
403 /// overstate the amount paid, though this is unlikely.
405 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
406 fee_paid_msat: Option<u64>,
408 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
409 /// provide failure information for each MPP part in the payment.
411 /// This event is provided once there are no further pending HTLCs for the payment and the
412 /// payment is no longer retryable due to [`ChannelManager::abandon_payment`] having been
413 /// called for the corresponding payment.
415 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
417 /// The id returned by [`ChannelManager::send_payment`] and used with
418 /// [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`].
420 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
421 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
422 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
423 payment_id: PaymentId,
424 /// The hash that was given to [`ChannelManager::send_payment`].
426 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
427 payment_hash: PaymentHash,
429 /// Indicates that a path for an outbound payment was successful.
431 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
432 /// [`Event::PaymentSent`] for obtaining the payment preimage.
433 PaymentPathSuccessful {
434 /// The id returned by [`ChannelManager::send_payment`] and used with
435 /// [`ChannelManager::retry_payment`].
437 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
438 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
439 payment_id: PaymentId,
440 /// The hash that was given to [`ChannelManager::send_payment`].
442 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
443 payment_hash: Option<PaymentHash>,
444 /// The payment path that was successful.
446 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
449 /// Indicates an outbound HTLC we sent failed. Probably some intermediary node dropped
450 /// something. You may wish to retry with a different route.
452 /// If you have given up retrying this payment and wish to fail it, you MUST call
453 /// [`ChannelManager::abandon_payment`] at least once for a given [`PaymentId`] or memory
454 /// related to payment tracking will leak.
456 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
457 /// [`Event::PaymentFailed`] and [`all_paths_failed`].
459 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
460 /// [`all_paths_failed`]: Self::PaymentPathFailed::all_paths_failed
462 /// The id returned by [`ChannelManager::send_payment`] and used with
463 /// [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`].
465 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
466 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
467 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
468 payment_id: Option<PaymentId>,
469 /// The hash that was given to [`ChannelManager::send_payment`].
471 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
472 payment_hash: PaymentHash,
473 /// Indicates the payment was rejected for some reason by the recipient. This implies that
474 /// the payment has failed, not just the route in question. If this is not set, you may
475 /// retry the payment via a different route.
476 payment_failed_permanently: bool,
477 /// Any failure information conveyed via the Onion return packet by a node along the failed
480 /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into
481 /// account the update.
483 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
484 network_update: Option<NetworkUpdate>,
485 /// For both single-path and multi-path payments, this is set if all paths of the payment have
486 /// failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the
487 /// larger MPP payment were still in flight when this event was generated.
489 /// Note that if you are retrying individual MPP parts, using this value to determine if a
490 /// payment has fully failed is race-y. Because multiple failures can happen prior to events
491 /// being processed, you may retry in response to a first failure, with a second failure
492 /// (with `all_paths_failed` set) still pending. Then, when the second failure is processed
493 /// you will see `all_paths_failed` set even though the retry of the first failure still
494 /// has an associated in-flight HTLC. See (1) for an example of such a failure.
496 /// If you wish to retry individual MPP parts and learn when a payment has failed, you must
497 /// call [`ChannelManager::abandon_payment`] and wait for a [`Event::PaymentFailed`] event.
499 /// (1) <https://github.com/lightningdevkit/rust-lightning/issues/1164>
501 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
502 all_paths_failed: bool,
503 /// The payment path that failed.
505 /// The channel responsible for the failed payment path.
507 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
508 /// may not refer to a channel in the public network graph. These aliases may also collide
509 /// with channels in the public network graph.
511 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
512 /// retried. May be `None` for older [`Event`] serializations.
513 short_channel_id: Option<u64>,
514 /// Parameters needed to compute a new [`Route`] when retrying the failed payment path.
516 /// See [`find_route`] for details.
518 /// [`Route`]: crate::routing::router::Route
519 /// [`find_route`]: crate::routing::router::find_route
520 retry: Option<RouteParameters>,
522 error_code: Option<u16>,
524 error_data: Option<Vec<u8>>,
526 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
528 /// The id returned by [`ChannelManager::send_probe`].
530 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
531 payment_id: PaymentId,
532 /// The hash generated by [`ChannelManager::send_probe`].
534 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
535 payment_hash: PaymentHash,
536 /// The payment path that was successful.
539 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
541 /// The id returned by [`ChannelManager::send_probe`].
543 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
544 payment_id: PaymentId,
545 /// The hash generated by [`ChannelManager::send_probe`].
547 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
548 payment_hash: PaymentHash,
549 /// The payment path that failed.
551 /// The channel responsible for the failed probe.
553 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
554 /// may not refer to a channel in the public network graph. These aliases may also collide
555 /// with channels in the public network graph.
556 short_channel_id: Option<u64>,
558 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
559 /// a time in the future.
561 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
562 PendingHTLCsForwardable {
563 /// The minimum amount of time that should be waited prior to calling
564 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
565 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
566 /// now + 5*time_forwardable).
567 time_forwardable: Duration,
569 /// Used to indicate that an output which you should know how to spend was confirmed on chain
570 /// and is now spendable.
571 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
572 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
573 /// somewhere and spend them when you create on-chain transactions.
575 /// The outputs which you should store as spendable by you.
576 outputs: Vec<SpendableOutputDescriptor>,
578 /// This event is generated when a payment has been successfully forwarded through us and a
579 /// forwarding fee earned.
581 /// The incoming channel between the previous node and us. This is only `None` for events
582 /// generated or serialized by versions prior to 0.0.107.
583 prev_channel_id: Option<[u8; 32]>,
584 /// The outgoing channel between the next node and us. This is only `None` for events
585 /// generated or serialized by versions prior to 0.0.107.
586 next_channel_id: Option<[u8; 32]>,
587 /// The fee, in milli-satoshis, which was earned as a result of the payment.
589 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
590 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
591 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
592 /// claimed the full value in millisatoshis from the source. In this case,
593 /// `claim_from_onchain_tx` will be set.
595 /// If the channel which sent us the payment has been force-closed, we will claim the funds
596 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
597 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
598 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
600 fee_earned_msat: Option<u64>,
601 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
603 claim_from_onchain_tx: bool,
605 /// Used to indicate that a channel with the given `channel_id` is ready to
606 /// be used. This event is emitted either when the funding transaction has been confirmed
607 /// on-chain, or, in case of a 0conf channel, when both parties have confirmed the channel
610 /// The channel_id of the channel that is ready.
611 channel_id: [u8; 32],
612 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
613 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
614 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
615 /// `user_channel_id` will be 0 for an inbound channel.
617 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
618 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
619 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
620 user_channel_id: u64,
621 /// The node_id of the channel counterparty.
622 counterparty_node_id: PublicKey,
623 /// The features that this channel will operate with.
624 channel_type: ChannelTypeFeatures,
626 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
627 /// process of closure.
629 /// The channel_id of the channel which has been closed. Note that on-chain transactions
630 /// resolving the channel are likely still awaiting 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 0 for an inbound channel.
636 /// This will always be zero for objects serialized with LDK versions prior to 0.0.102.
638 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
639 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
640 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
641 user_channel_id: u64,
642 /// The reason the channel was closed.
643 reason: ClosureReason
645 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
646 /// inputs for another purpose.
648 /// The channel_id of the channel which has been closed.
649 channel_id: [u8; 32],
650 /// The full transaction received from the user
651 transaction: Transaction
653 /// Indicates a request to open a new channel by a peer.
655 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the
656 /// request, call [`ChannelManager::force_close_without_broadcasting_txn`].
658 /// The event is only triggered when a new open channel request is received and the
659 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
661 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
662 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
663 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
665 /// The temporary channel ID of the channel requested to be opened.
667 /// When responding to the request, the `temporary_channel_id` should be passed
668 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
669 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
671 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
672 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
673 temporary_channel_id: [u8; 32],
674 /// The node_id of the counterparty requesting to open the channel.
676 /// When responding to the request, the `counterparty_node_id` should be passed
677 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
678 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
681 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
682 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
683 counterparty_node_id: PublicKey,
684 /// The channel value of the requested channel.
685 funding_satoshis: u64,
686 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
688 /// The features that this channel will operate with. If you reject the channel, a
689 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
692 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
693 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
696 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
697 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
698 /// 0.0.107. Channels setting this type also need to get manually accepted via
699 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
700 /// or will be rejected otherwise.
702 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
703 channel_type: ChannelTypeFeatures,
705 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
708 /// Some scenarios where this event may be sent include:
709 /// * Insufficient capacity in the outbound channel
710 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
711 /// * When an unknown SCID is requested for forwarding a payment.
712 /// * Claiming an amount for an MPP payment that exceeds the HTLC total
713 /// * The HTLC has timed out
715 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
716 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
718 /// The channel over which the HTLC was received.
719 prev_channel_id: [u8; 32],
720 /// Destination of the HTLC that failed to be processed.
721 failed_next_destination: HTLCDestination,
724 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
725 /// requires confirmed external funds to be readily available to spend.
727 /// LDK does not currently generate this event. It is limited to the scope of channels with
728 /// anchor outputs, which will be introduced in a future release.
729 BumpTransaction(BumpTransactionEvent),
732 impl Writeable for Event {
733 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
735 &Event::FundingGenerationReady { .. } => {
737 // We never write out FundingGenerationReady events as, upon disconnection, peers
738 // drop any channels which have not yet exchanged funding_signed.
740 &Event::PaymentReceived { ref payment_hash, ref amount_msat, ref purpose } => {
742 let mut payment_secret = None;
743 let payment_preimage;
745 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
746 payment_secret = Some(secret);
747 payment_preimage = *preimage;
749 PaymentPurpose::SpontaneousPayment(preimage) => {
750 payment_preimage = Some(*preimage);
753 write_tlv_fields!(writer, {
754 (0, payment_hash, required),
755 (2, payment_secret, option),
756 (4, amount_msat, required),
757 (6, 0u64, required), // user_payment_id required for compatibility with 0.0.103 and earlier
758 (8, payment_preimage, option),
761 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
763 write_tlv_fields!(writer, {
764 (0, payment_preimage, required),
765 (1, payment_hash, required),
766 (3, payment_id, option),
767 (5, fee_paid_msat, option),
770 &Event::PaymentPathFailed {
771 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update,
772 ref all_paths_failed, ref path, ref short_channel_id, ref retry,
780 error_code.write(writer)?;
782 error_data.write(writer)?;
783 write_tlv_fields!(writer, {
784 (0, payment_hash, required),
785 (1, network_update, option),
786 (2, payment_failed_permanently, required),
787 (3, all_paths_failed, required),
788 (5, *path, vec_type),
789 (7, short_channel_id, option),
791 (11, payment_id, option),
794 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
796 // Note that we now ignore these on the read end as we'll re-generate them in
797 // ChannelManager, we write them here only for backwards compatibility.
799 &Event::SpendableOutputs { ref outputs } => {
801 write_tlv_fields!(writer, {
802 (0, WithoutLength(outputs), required),
805 &Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
807 write_tlv_fields!(writer, {
808 (0, fee_earned_msat, option),
809 (1, prev_channel_id, option),
810 (2, claim_from_onchain_tx, required),
811 (3, next_channel_id, option),
814 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
816 write_tlv_fields!(writer, {
817 (0, channel_id, required),
818 (1, user_channel_id, required),
819 (2, reason, required)
822 &Event::DiscardFunding { ref channel_id, ref transaction } => {
824 write_tlv_fields!(writer, {
825 (0, channel_id, required),
826 (2, transaction, required)
829 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
831 write_tlv_fields!(writer, {
832 (0, payment_id, required),
833 (2, payment_hash, option),
837 &Event::PaymentFailed { ref payment_id, ref payment_hash } => {
839 write_tlv_fields!(writer, {
840 (0, payment_id, required),
841 (2, payment_hash, required),
844 &Event::OpenChannelRequest { .. } => {
846 // We never write the OpenChannelRequest events as, upon disconnection, peers
847 // drop any channels which have not yet exchanged funding_signed.
849 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose } => {
851 write_tlv_fields!(writer, {
852 (0, payment_hash, required),
853 (2, purpose, required),
854 (4, amount_msat, required),
857 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
859 write_tlv_fields!(writer, {
860 (0, payment_id, required),
861 (2, payment_hash, required),
865 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
867 write_tlv_fields!(writer, {
868 (0, payment_id, required),
869 (2, payment_hash, required),
870 (4, *path, vec_type),
871 (6, short_channel_id, option),
874 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
876 write_tlv_fields!(writer, {
877 (0, prev_channel_id, required),
878 (2, failed_next_destination, required),
882 &Event::BumpTransaction(ref event)=> {
885 // We never write the ChannelClose events as they'll be replayed upon restarting
886 // anyway if the commitment transaction remains unconfirmed.
887 BumpTransactionEvent::ChannelClose { .. } => {}
890 &Event::ChannelReady { ref channel_id, ref user_channel_id, ref counterparty_node_id, ref channel_type } => {
892 write_tlv_fields!(writer, {
893 (0, channel_id, required),
894 (2, user_channel_id, required),
895 (4, counterparty_node_id, required),
896 (6, channel_type, required),
899 // Note that, going forward, all new events must only write data inside of
900 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
901 // data via `write_tlv_fields`.
906 impl MaybeReadable for Event {
907 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
908 match Readable::read(reader)? {
909 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
910 // unlike all other events, thus we return immediately here.
914 let mut payment_hash = PaymentHash([0; 32]);
915 let mut payment_preimage = None;
916 let mut payment_secret = None;
917 let mut amount_msat = 0;
918 let mut _user_payment_id = None::<u64>; // For compatibility with 0.0.103 and earlier
919 read_tlv_fields!(reader, {
920 (0, payment_hash, required),
921 (2, payment_secret, option),
922 (4, amount_msat, required),
923 (6, _user_payment_id, option),
924 (8, payment_preimage, option),
926 let purpose = match payment_secret {
927 Some(secret) => PaymentPurpose::InvoicePayment {
929 payment_secret: secret
931 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
932 None => return Err(msgs::DecodeError::InvalidValue),
934 Ok(Some(Event::PaymentReceived {
944 let mut payment_preimage = PaymentPreimage([0; 32]);
945 let mut payment_hash = None;
946 let mut payment_id = None;
947 let mut fee_paid_msat = None;
948 read_tlv_fields!(reader, {
949 (0, payment_preimage, required),
950 (1, payment_hash, option),
951 (3, payment_id, option),
952 (5, fee_paid_msat, option),
954 if payment_hash.is_none() {
955 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
957 Ok(Some(Event::PaymentSent {
960 payment_hash: payment_hash.unwrap(),
969 let error_code = Readable::read(reader)?;
971 let error_data = Readable::read(reader)?;
972 let mut payment_hash = PaymentHash([0; 32]);
973 let mut payment_failed_permanently = false;
974 let mut network_update = None;
975 let mut all_paths_failed = Some(true);
976 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
977 let mut short_channel_id = None;
978 let mut retry = None;
979 let mut payment_id = None;
980 read_tlv_fields!(reader, {
981 (0, payment_hash, required),
982 (1, network_update, ignorable),
983 (2, payment_failed_permanently, required),
984 (3, all_paths_failed, option),
986 (7, short_channel_id, option),
988 (11, payment_id, option),
990 Ok(Some(Event::PaymentPathFailed {
993 payment_failed_permanently,
995 all_paths_failed: all_paths_failed.unwrap(),
1010 let mut outputs = WithoutLength(Vec::new());
1011 read_tlv_fields!(reader, {
1012 (0, outputs, required),
1014 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
1020 let mut fee_earned_msat = None;
1021 let mut prev_channel_id = None;
1022 let mut claim_from_onchain_tx = false;
1023 let mut next_channel_id = None;
1024 read_tlv_fields!(reader, {
1025 (0, fee_earned_msat, option),
1026 (1, prev_channel_id, option),
1027 (2, claim_from_onchain_tx, required),
1028 (3, next_channel_id, option),
1030 Ok(Some(Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id }))
1036 let mut channel_id = [0; 32];
1037 let mut reason = None;
1038 let mut user_channel_id_opt = None;
1039 read_tlv_fields!(reader, {
1040 (0, channel_id, required),
1041 (1, user_channel_id_opt, option),
1042 (2, reason, ignorable),
1044 if reason.is_none() { return Ok(None); }
1045 let user_channel_id = if let Some(id) = user_channel_id_opt { id } else { 0 };
1046 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: reason.unwrap() }))
1052 let mut channel_id = [0; 32];
1053 let mut transaction = Transaction{ version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
1054 read_tlv_fields!(reader, {
1055 (0, channel_id, required),
1056 (2, transaction, required),
1058 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1064 let mut payment_id = PaymentId([0; 32]);
1065 let mut payment_hash = None;
1066 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1067 read_tlv_fields!(reader, {
1068 (0, payment_id, required),
1069 (2, payment_hash, option),
1070 (4, path, vec_type),
1072 Ok(Some(Event::PaymentPathSuccessful {
1075 path: path.unwrap(),
1082 let mut payment_hash = PaymentHash([0; 32]);
1083 let mut payment_id = PaymentId([0; 32]);
1084 read_tlv_fields!(reader, {
1085 (0, payment_id, required),
1086 (2, payment_hash, required),
1088 Ok(Some(Event::PaymentFailed {
1096 // Value 17 is used for `Event::OpenChannelRequest`.
1101 let mut payment_hash = PaymentHash([0; 32]);
1102 let mut purpose = None;
1103 let mut amount_msat = 0;
1104 read_tlv_fields!(reader, {
1105 (0, payment_hash, required),
1106 (2, purpose, ignorable),
1107 (4, amount_msat, required),
1109 if purpose.is_none() { return Ok(None); }
1110 Ok(Some(Event::PaymentClaimed {
1112 purpose: purpose.unwrap(),
1120 let mut payment_id = PaymentId([0; 32]);
1121 let mut payment_hash = PaymentHash([0; 32]);
1122 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1123 read_tlv_fields!(reader, {
1124 (0, payment_id, required),
1125 (2, payment_hash, required),
1126 (4, path, vec_type),
1128 Ok(Some(Event::ProbeSuccessful {
1131 path: path.unwrap(),
1138 let mut payment_id = PaymentId([0; 32]);
1139 let mut payment_hash = PaymentHash([0; 32]);
1140 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1141 let mut short_channel_id = None;
1142 read_tlv_fields!(reader, {
1143 (0, payment_id, required),
1144 (2, payment_hash, required),
1145 (4, path, vec_type),
1146 (6, short_channel_id, option),
1148 Ok(Some(Event::ProbeFailed {
1151 path: path.unwrap(),
1159 let mut prev_channel_id = [0; 32];
1160 let mut failed_next_destination_opt = None;
1161 read_tlv_fields!(reader, {
1162 (0, prev_channel_id, required),
1163 (2, failed_next_destination_opt, ignorable),
1165 if let Some(failed_next_destination) = failed_next_destination_opt {
1166 Ok(Some(Event::HTLCHandlingFailed {
1168 failed_next_destination,
1171 // If we fail to read a `failed_next_destination` assume it's because
1172 // `MaybeReadable::read` returned `Ok(None)`, though it's also possible we
1173 // were simply missing the field.
1182 let mut channel_id = [0; 32];
1183 let mut user_channel_id: u64 = 0;
1184 let mut counterparty_node_id = OptionDeserWrapper(None);
1185 let mut channel_type = OptionDeserWrapper(None);
1186 read_tlv_fields!(reader, {
1187 (0, channel_id, required),
1188 (2, user_channel_id, required),
1189 (4, counterparty_node_id, required),
1190 (6, channel_type, required),
1193 Ok(Some(Event::ChannelReady {
1196 counterparty_node_id: counterparty_node_id.0.unwrap(),
1197 channel_type: channel_type.0.unwrap()
1202 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1203 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1205 x if x % 2 == 1 => {
1206 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1207 // which prefixes the whole thing with a length BigSize. Because the event is
1208 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1209 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1210 // exactly the number of bytes specified, ignoring them entirely.
1211 let tlv_len: BigSize = Readable::read(reader)?;
1212 FixedLengthReader::new(reader, tlv_len.0)
1213 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1216 _ => Err(msgs::DecodeError::InvalidValue)
1221 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1222 /// broadcast to most peers).
1223 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1224 #[derive(Clone, Debug)]
1225 pub enum MessageSendEvent {
1226 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1227 /// message provided to the given peer.
1229 /// The node_id of the node which should receive this message
1231 /// The message which should be sent.
1232 msg: msgs::AcceptChannel,
1234 /// Used to indicate that we've initiated a channel open and should send the open_channel
1235 /// message provided to the given peer.
1237 /// The node_id of the node which should receive this message
1239 /// The message which should be sent.
1240 msg: msgs::OpenChannel,
1242 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1243 SendFundingCreated {
1244 /// The node_id of the node which should receive this message
1246 /// The message which should be sent.
1247 msg: msgs::FundingCreated,
1249 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1251 /// The node_id of the node which should receive this message
1253 /// The message which should be sent.
1254 msg: msgs::FundingSigned,
1256 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1258 /// The node_id of the node which should receive these message(s)
1260 /// The channel_ready message which should be sent.
1261 msg: msgs::ChannelReady,
1263 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1264 SendAnnouncementSignatures {
1265 /// The node_id of the node which should receive these message(s)
1267 /// The announcement_signatures message which should be sent.
1268 msg: msgs::AnnouncementSignatures,
1270 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1271 /// message should be sent to the peer with the given node_id.
1273 /// The node_id of the node which should receive these message(s)
1275 /// The update messages which should be sent. ALL messages in the struct should be sent!
1276 updates: msgs::CommitmentUpdate,
1278 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1280 /// The node_id of the node which should receive this message
1282 /// The message which should be sent.
1283 msg: msgs::RevokeAndACK,
1285 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1287 /// The node_id of the node which should receive this message
1289 /// The message which should be sent.
1290 msg: msgs::ClosingSigned,
1292 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1294 /// The node_id of the node which should receive this message
1296 /// The message which should be sent.
1297 msg: msgs::Shutdown,
1299 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1300 SendChannelReestablish {
1301 /// The node_id of the node which should receive this message
1303 /// The message which should be sent.
1304 msg: msgs::ChannelReestablish,
1306 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1307 /// initial connection to ensure our peers know about our channels.
1308 SendChannelAnnouncement {
1309 /// The node_id of the node which should receive this message
1311 /// The channel_announcement which should be sent.
1312 msg: msgs::ChannelAnnouncement,
1313 /// The followup channel_update which should be sent.
1314 update_msg: msgs::ChannelUpdate,
1316 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1317 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1319 /// Note that after doing so, you very likely (unless you did so very recently) want to
1320 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1321 /// ensures that any nodes which see our channel_announcement also have a relevant
1322 /// node_announcement, including relevant feature flags which may be important for routing
1323 /// through or to us.
1325 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1326 BroadcastChannelAnnouncement {
1327 /// The channel_announcement which should be sent.
1328 msg: msgs::ChannelAnnouncement,
1329 /// The followup channel_update which should be sent.
1330 update_msg: msgs::ChannelUpdate,
1332 /// Used to indicate that a channel_update should be broadcast to all peers.
1333 BroadcastChannelUpdate {
1334 /// The channel_update which should be sent.
1335 msg: msgs::ChannelUpdate,
1337 /// Used to indicate that a channel_update should be sent to a single peer.
1338 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1339 /// private channel and we shouldn't be informing all of our peers of channel parameters.
1341 /// The node_id of the node which should receive this message
1343 /// The channel_update which should be sent.
1344 msg: msgs::ChannelUpdate,
1346 /// Broadcast an error downstream to be handled
1348 /// The node_id of the node which should receive this message
1350 /// The action which should be taken.
1351 action: msgs::ErrorAction
1353 /// Query a peer for channels with funding transaction UTXOs in a block range.
1354 SendChannelRangeQuery {
1355 /// The node_id of this message recipient
1357 /// The query_channel_range which should be sent.
1358 msg: msgs::QueryChannelRange,
1360 /// Request routing gossip messages from a peer for a list of channels identified by
1361 /// their short_channel_ids.
1363 /// The node_id of this message recipient
1365 /// The query_short_channel_ids which should be sent.
1366 msg: msgs::QueryShortChannelIds,
1368 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1369 /// emitted during processing of the query.
1370 SendReplyChannelRange {
1371 /// The node_id of this message recipient
1373 /// The reply_channel_range which should be sent.
1374 msg: msgs::ReplyChannelRange,
1376 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1377 /// enable receiving gossip messages from the peer.
1378 SendGossipTimestampFilter {
1379 /// The node_id of this message recipient
1381 /// The gossip_timestamp_filter which should be sent.
1382 msg: msgs::GossipTimestampFilter,
1386 /// A trait indicating an object may generate message send events
1387 pub trait MessageSendEventsProvider {
1388 /// Gets the list of pending events which were generated by previous actions, clearing the list
1390 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1393 /// A trait indicating an object may generate onion messages to send
1394 pub trait OnionMessageProvider {
1395 /// Gets the next pending onion message for the peer with the given node id.
1396 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<msgs::OnionMessage>;
1399 /// A trait indicating an object may generate events.
1401 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1405 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1406 /// event since the last invocation.
1408 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1409 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1410 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1411 /// relevant changes to disk *before* returning.
1413 /// Further, because an application may crash between an [`Event`] being handled and the
1414 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1415 /// effect, [`Event`]s may be replayed.
1417 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1418 /// consult the provider's documentation on the implication of processing events and how a handler
1419 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1420 /// [`ChainMonitor::process_pending_events`]).
1422 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1425 /// [`process_pending_events`]: Self::process_pending_events
1426 /// [`handle_event`]: EventHandler::handle_event
1427 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1428 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1429 pub trait EventsProvider {
1430 /// Processes any events generated since the last call using the given event handler.
1432 /// See the trait-level documentation for requirements.
1433 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1436 /// A trait implemented for objects handling events from [`EventsProvider`].
1437 pub trait EventHandler {
1438 /// Handles the given [`Event`].
1440 /// See [`EventsProvider`] for details that must be considered when implementing this method.
1441 fn handle_event(&self, event: &Event);
1444 impl<F> EventHandler for F where F: Fn(&Event) {
1445 fn handle_event(&self, event: &Event) {
1450 impl<T: EventHandler> EventHandler for Arc<T> {
1451 fn handle_event(&self, event: &Event) {
1452 self.deref().handle_event(event)