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 chain::keysinterface::SpendableOutputDescriptor;
18 use ln::chan_utils::HTLCOutputInCommitment;
19 use ln::channelmanager::PaymentId;
20 use ln::channel::FUNDING_CONF_DEADLINE_BLOCKS;
21 use ln::features::ChannelTypeFeatures;
23 use ln::msgs::DecodeError;
24 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
25 use routing::gossip::NetworkUpdate;
26 use util::ser::{BigSize, FixedLengthReader, Writeable, Writer, MaybeReadable, Readable, VecReadWrapper, VecWriteWrapper};
27 use routing::router::{RouteHop, RouteParameters};
29 use bitcoin::{PackedLockTime, Transaction, OutPoint};
30 use bitcoin::blockdata::script::Script;
31 use bitcoin::hashes::Hash;
32 use bitcoin::hashes::sha256::Hash as Sha256;
33 use bitcoin::secp256k1::PublicKey;
36 use core::time::Duration;
40 /// Some information provided on receipt of payment depends on whether the payment received is a
41 /// spontaneous payment or a "conventional" lightning payment that's paying an invoice.
42 #[derive(Clone, Debug)]
43 pub enum PaymentPurpose {
44 /// Information for receiving a payment that we generated an invoice for.
46 /// The preimage to the payment_hash, if the payment hash (and secret) were fetched via
47 /// [`ChannelManager::create_inbound_payment`]. If provided, this can be handed directly to
48 /// [`ChannelManager::claim_funds`].
50 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
51 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
52 payment_preimage: Option<PaymentPreimage>,
53 /// The "payment secret". This authenticates the sender to the recipient, preventing a
54 /// number of deanonymization attacks during the routing process.
55 /// It is provided here for your reference, however its accuracy is enforced directly by
56 /// [`ChannelManager`] using the values you previously provided to
57 /// [`ChannelManager::create_inbound_payment`] or
58 /// [`ChannelManager::create_inbound_payment_for_hash`].
60 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
61 /// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
62 /// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
63 payment_secret: PaymentSecret,
65 /// Because this is a spontaneous payment, the payer generated their own preimage rather than us
66 /// (the payee) providing a preimage.
67 SpontaneousPayment(PaymentPreimage),
70 impl_writeable_tlv_based_enum!(PaymentPurpose,
71 (0, InvoicePayment) => {
72 (0, payment_preimage, option),
73 (2, payment_secret, required),
75 (2, SpontaneousPayment)
78 #[derive(Clone, Debug, PartialEq, Eq)]
79 /// The reason the channel was closed. See individual variants more details.
80 pub enum ClosureReason {
81 /// Closure generated from receiving a peer error message.
83 /// Our counterparty may have broadcasted their latest commitment state, and we have
85 CounterpartyForceClosed {
86 /// The error which the peer sent us.
88 /// The string should be sanitized before it is used (e.g emitted to logs
89 /// or printed to stdout). Otherwise, a well crafted error message may exploit
90 /// a security vulnerability in the terminal emulator or the logging subsystem.
93 /// Closure generated from [`ChannelManager::force_close_channel`], called by the user.
95 /// [`ChannelManager::force_close_channel`]: crate::ln::channelmanager::ChannelManager::force_close_channel.
97 /// The channel was closed after negotiating a cooperative close and we've now broadcasted
98 /// the cooperative close transaction. Note the shutdown may have been initiated by us.
99 //TODO: split between CounterpartyInitiated/LocallyInitiated
101 /// A commitment transaction was confirmed on chain, closing the channel. Most likely this
102 /// commitment transaction came from our counterparty, but it may also have come from
103 /// a copy of our own `ChannelMonitor`.
104 CommitmentTxConfirmed,
105 /// The funding transaction failed to confirm in a timely manner on an inbound channel.
107 /// Closure generated from processing an event, likely a HTLC forward/relay/reception.
109 /// A developer-readable error message which we generated.
112 /// The peer disconnected prior to funding completing. In this case the spec mandates that we
113 /// forget the channel entirely - we can attempt again if the peer reconnects.
115 /// In LDK versions prior to 0.0.107 this could also occur if we were unable to connect to the
116 /// peer because of mutual incompatibility between us and our channel counterparty.
118 /// Closure generated from `ChannelManager::read` if the ChannelMonitor is newer than
119 /// the ChannelManager deserialized.
120 OutdatedChannelManager
123 impl core::fmt::Display for ClosureReason {
124 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
125 f.write_str("Channel closed because ")?;
127 ClosureReason::CounterpartyForceClosed { peer_msg } => {
128 f.write_str("counterparty force-closed with message ")?;
129 f.write_str(&peer_msg)
131 ClosureReason::HolderForceClosed => f.write_str("user manually force-closed the channel"),
132 ClosureReason::CooperativeClosure => f.write_str("the channel was cooperatively closed"),
133 ClosureReason::CommitmentTxConfirmed => f.write_str("commitment or closing transaction was confirmed on chain."),
134 ClosureReason::FundingTimedOut => write!(f, "funding transaction failed to confirm within {} blocks", FUNDING_CONF_DEADLINE_BLOCKS),
135 ClosureReason::ProcessingError { err } => {
136 f.write_str("of an exception: ")?;
139 ClosureReason::DisconnectedPeer => f.write_str("the peer disconnected prior to the channel being funded"),
140 ClosureReason::OutdatedChannelManager => f.write_str("the ChannelManager read from disk was stale compared to ChannelMonitor(s)"),
145 impl_writeable_tlv_based_enum_upgradable!(ClosureReason,
146 (0, CounterpartyForceClosed) => { (1, peer_msg, required) },
147 (1, FundingTimedOut) => {},
148 (2, HolderForceClosed) => {},
149 (6, CommitmentTxConfirmed) => {},
150 (4, CooperativeClosure) => {},
151 (8, ProcessingError) => { (1, err, required) },
152 (10, DisconnectedPeer) => {},
153 (12, OutdatedChannelManager) => {},
156 /// Intended destination of a failed HTLC as indicated in [`Event::HTLCHandlingFailed`].
157 #[derive(Clone, Debug, PartialEq, Eq)]
158 pub enum HTLCDestination {
159 /// We tried forwarding to a channel but failed to do so. An example of such an instance is when
160 /// there is insufficient capacity in our outbound channel.
162 /// The `node_id` of the next node. For backwards compatibility, this field is
163 /// marked as optional, versions prior to 0.0.110 may not always be able to provide
164 /// counterparty node information.
165 node_id: Option<PublicKey>,
166 /// The outgoing `channel_id` between us and the next node.
167 channel_id: [u8; 32],
169 /// Scenario where we are unsure of the next node to forward the HTLC to.
171 /// Short channel id we are requesting to forward an HTLC to.
172 requested_forward_scid: u64,
174 /// Failure scenario where an HTLC may have been forwarded to be intended for us,
175 /// but is invalid for some reason, so we reject it.
177 /// Some of the reasons may include:
179 /// * Expected MPP amount to claim does not equal HTLC total
180 /// * Claimable amount does not match expected amount
182 /// The payment hash of the payment we attempted to process.
183 payment_hash: PaymentHash
187 impl_writeable_tlv_based_enum_upgradable!(HTLCDestination,
188 (0, NextHopChannel) => {
189 (0, node_id, required),
190 (2, channel_id, required),
192 (2, UnknownNextHop) => {
193 (0, requested_forward_scid, required),
195 (4, FailedPayment) => {
196 (0, payment_hash, required),
200 /// A descriptor used to sign for a commitment transaction's anchor output.
201 #[derive(Clone, Debug)]
202 pub struct AnchorDescriptor {
203 /// A unique identifier used along with `channel_value_satoshis` to re-derive the
204 /// [`InMemorySigner`] required to sign `input`.
206 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
207 pub channel_keys_id: [u8; 32],
208 /// The value in satoshis of the channel we're attempting to spend the anchor output of. This is
209 /// used along with `channel_keys_id` to re-derive the [`InMemorySigner`] required to sign
212 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
213 pub channel_value_satoshis: u64,
214 /// The transaction input's outpoint corresponding to the commitment transaction's anchor
216 pub outpoint: OutPoint,
219 /// Represents the different types of transactions, originating from LDK, to be bumped.
220 #[derive(Clone, Debug)]
221 pub enum BumpTransactionEvent {
222 /// Indicates that a channel featuring anchor outputs is to be closed by broadcasting the local
223 /// commitment transaction. Since commitment transactions have a static feerate pre-agreed upon,
224 /// they may need additional fees to be attached through a child transaction using the popular
225 /// [Child-Pays-For-Parent](https://bitcoinops.org/en/topics/cpfp) fee bumping technique. This
226 /// child transaction must include the anchor input described within `anchor_descriptor` along
227 /// with additional inputs to meet the target feerate. Failure to meet the target feerate
228 /// decreases the confirmation odds of the transaction package (which includes the commitment
229 /// and child anchor transactions), possibly resulting in a loss of funds. Once the transaction
230 /// is constructed, it must be fully signed for and broadcasted by the consumer of the event
231 /// along with the `commitment_tx` enclosed. Note that the `commitment_tx` must always be
232 /// broadcast first, as the child anchor transaction depends on it.
234 /// The consumer should be able to sign for any of the additional inputs included within the
235 /// child anchor transaction. To sign its anchor input, an [`InMemorySigner`] should be
236 /// re-derived through [`KeysManager::derive_channel_keys`] with the help of
237 /// [`AnchorDescriptor::channel_keys_id`] and [`AnchorDescriptor::channel_value_satoshis`].
239 /// It is possible to receive more than one instance of this event if a valid child anchor
240 /// transaction is never broadcast or is but not with a sufficient fee to be mined. Care should
241 /// be taken by the consumer of the event to ensure any future iterations of the child anchor
242 /// transaction adhere to the [Replace-By-Fee
243 /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
244 /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
245 /// these events is not user-controlled, users may ignore/drop the event if they are no longer
246 /// able to commit external confirmed funds to the child anchor transaction.
248 /// The set of `pending_htlcs` on the commitment transaction to be broadcast can be inspected to
249 /// determine whether a significant portion of the channel's funds are allocated to HTLCs,
250 /// enabling users to make their own decisions regarding the importance of the commitment
251 /// transaction's confirmation. Note that this is not required, but simply exists as an option
252 /// for users to override LDK's behavior. On commitments with no HTLCs (indicated by those with
253 /// an empty `pending_htlcs`), confirmation of the commitment transaction can be considered to
256 /// [`InMemorySigner`]: crate::chain::keysinterface::InMemorySigner
257 /// [`KeysManager::derive_channel_keys`]: crate::chain::keysinterface::KeysManager::derive_channel_keys
259 /// The target feerate that the transaction package, which consists of the commitment
260 /// transaction and the to-be-crafted child anchor transaction, must meet.
261 package_target_feerate_sat_per_1000_weight: u32,
262 /// The channel's commitment transaction to bump the fee of. This transaction should be
263 /// broadcast along with the anchor transaction constructed as a result of consuming this
265 commitment_tx: Transaction,
266 /// The absolute fee in satoshis of the commitment transaction. This can be used along the
267 /// with weight of the commitment transaction to determine its feerate.
268 commitment_tx_fee_satoshis: u64,
269 /// The descriptor to sign the anchor input of the anchor transaction constructed as a
270 /// result of consuming this event.
271 anchor_descriptor: AnchorDescriptor,
272 /// The set of pending HTLCs on the commitment transaction that need to be resolved once the
273 /// commitment transaction confirms.
274 pending_htlcs: Vec<HTLCOutputInCommitment>,
278 /// An Event which you should probably take some action in response to.
280 /// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
281 /// them directly as they don't round-trip exactly (for example FundingGenerationReady is never
282 /// written as it makes no sense to respond to it after reconnecting to peers).
283 #[derive(Clone, Debug)]
285 /// Used to indicate that the client should generate a funding transaction with the given
286 /// parameters and then call [`ChannelManager::funding_transaction_generated`].
287 /// Generated in [`ChannelManager`] message handling.
288 /// Note that *all inputs* in the funding transaction must spend SegWit outputs or your
289 /// counterparty can steal your funds!
291 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
292 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
293 FundingGenerationReady {
294 /// The random channel_id we picked which you'll need to pass into
295 /// [`ChannelManager::funding_transaction_generated`].
297 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
298 temporary_channel_id: [u8; 32],
299 /// The counterparty's node_id, which you'll need to pass back into
300 /// [`ChannelManager::funding_transaction_generated`].
302 /// [`ChannelManager::funding_transaction_generated`]: crate::ln::channelmanager::ChannelManager::funding_transaction_generated
303 counterparty_node_id: PublicKey,
304 /// The value, in satoshis, that the output should have.
305 channel_value_satoshis: u64,
306 /// The script which should be used in the transaction output.
307 output_script: Script,
308 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`], or 0 for
309 /// an inbound channel.
311 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
312 user_channel_id: u64,
314 /// Indicates we've received (an offer of) money! Just gotta dig out that payment preimage and
315 /// feed it to [`ChannelManager::claim_funds`] to get it....
317 /// Note that if the preimage is not known, you should call
318 /// [`ChannelManager::fail_htlc_backwards`] to free up resources for this HTLC and avoid
319 /// network congestion.
320 /// If you fail to call either [`ChannelManager::claim_funds`] or
321 /// [`ChannelManager::fail_htlc_backwards`] within the HTLC's timeout, the HTLC will be
322 /// automatically failed.
325 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
326 /// `PaymentReceived` events may be generated for the same payment.
328 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
329 /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards
331 /// The hash for which the preimage should be handed to the ChannelManager. Note that LDK will
332 /// not stop you from registering duplicate payment hashes for inbound payments.
333 payment_hash: PaymentHash,
334 /// The value, in thousandths of a satoshi, that this payment is for.
336 /// Information for claiming this received payment, based on whether the purpose of the
337 /// payment is to pay an invoice or to send a spontaneous payment.
338 purpose: PaymentPurpose,
340 /// Indicates a payment has been claimed and we've received money!
342 /// This most likely occurs when [`ChannelManager::claim_funds`] has been called in response
343 /// to an [`Event::PaymentReceived`]. However, if we previously crashed during a
344 /// [`ChannelManager::claim_funds`] call you may see this event without a corresponding
345 /// [`Event::PaymentReceived`] event.
348 /// LDK will not stop an inbound payment from being paid multiple times, so multiple
349 /// `PaymentReceived` events may be generated for the same payment. If you then call
350 /// [`ChannelManager::claim_funds`] twice for the same [`Event::PaymentReceived`] you may get
351 /// multiple `PaymentClaimed` events.
353 /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds
355 /// The payment hash of the claimed payment. Note that LDK will not stop you from
356 /// registering duplicate payment hashes for inbound payments.
357 payment_hash: PaymentHash,
358 /// The value, in thousandths of a satoshi, that this payment is for.
360 /// The purpose of this claimed payment, i.e. whether the payment was for an invoice or a
361 /// spontaneous payment.
362 purpose: PaymentPurpose,
364 /// Indicates an outbound payment we made succeeded (i.e. it made it all the way to its target
365 /// and we got back the payment preimage for it).
367 /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed`
368 /// event. In this situation, you SHOULD treat this payment as having succeeded.
370 /// The id returned by [`ChannelManager::send_payment`] and used with
371 /// [`ChannelManager::retry_payment`].
373 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
374 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
375 payment_id: Option<PaymentId>,
376 /// The preimage to the hash given to ChannelManager::send_payment.
377 /// Note that this serves as a payment receipt, if you wish to have such a thing, you must
378 /// store it somehow!
379 payment_preimage: PaymentPreimage,
380 /// The hash that was given to [`ChannelManager::send_payment`].
382 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
383 payment_hash: PaymentHash,
384 /// The total fee which was spent at intermediate hops in this payment, across all paths.
386 /// Note that, like [`Route::get_total_fees`] this does *not* include any potential
387 /// overpayment to the recipient node.
389 /// If the recipient or an intermediate node misbehaves and gives us free money, this may
390 /// overstate the amount paid, though this is unlikely.
392 /// [`Route::get_total_fees`]: crate::routing::router::Route::get_total_fees
393 fee_paid_msat: Option<u64>,
395 /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events
396 /// provide failure information for each MPP part in the payment.
398 /// This event is provided once there are no further pending HTLCs for the payment and the
399 /// payment is no longer retryable, either due to a several-block timeout or because
400 /// [`ChannelManager::abandon_payment`] was previously called for the corresponding payment.
402 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
404 /// The id returned by [`ChannelManager::send_payment`] and used with
405 /// [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`].
407 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
408 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
409 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
410 payment_id: PaymentId,
411 /// The hash that was given to [`ChannelManager::send_payment`].
413 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
414 payment_hash: PaymentHash,
416 /// Indicates that a path for an outbound payment was successful.
418 /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See
419 /// [`Event::PaymentSent`] for obtaining the payment preimage.
420 PaymentPathSuccessful {
421 /// The id returned by [`ChannelManager::send_payment`] and used with
422 /// [`ChannelManager::retry_payment`].
424 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
425 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
426 payment_id: PaymentId,
427 /// The hash that was given to [`ChannelManager::send_payment`].
429 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
430 payment_hash: Option<PaymentHash>,
431 /// The payment path that was successful.
433 /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain.
436 /// Indicates an outbound HTLC we sent failed. Probably some intermediary node dropped
437 /// something. You may wish to retry with a different route.
439 /// Note that this does *not* indicate that all paths for an MPP payment have failed, see
440 /// [`Event::PaymentFailed`] and [`all_paths_failed`].
442 /// [`all_paths_failed`]: Self::PaymentPathFailed::all_paths_failed
444 /// The id returned by [`ChannelManager::send_payment`] and used with
445 /// [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`].
447 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
448 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
449 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
450 payment_id: Option<PaymentId>,
451 /// The hash that was given to [`ChannelManager::send_payment`].
453 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
454 payment_hash: PaymentHash,
455 /// Indicates the payment was rejected for some reason by the recipient. This implies that
456 /// the payment has failed, not just the route in question. If this is not set, you may
457 /// retry the payment via a different route.
458 payment_failed_permanently: bool,
459 /// Any failure information conveyed via the Onion return packet by a node along the failed
462 /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into
463 /// account the update.
465 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
466 network_update: Option<NetworkUpdate>,
467 /// For both single-path and multi-path payments, this is set if all paths of the payment have
468 /// failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the
469 /// larger MPP payment were still in flight when this event was generated.
471 /// Note that if you are retrying individual MPP parts, using this value to determine if a
472 /// payment has fully failed is race-y. Because multiple failures can happen prior to events
473 /// being processed, you may retry in response to a first failure, with a second failure
474 /// (with `all_paths_failed` set) still pending. Then, when the second failure is processed
475 /// you will see `all_paths_failed` set even though the retry of the first failure still
476 /// has an associated in-flight HTLC. See (1) for an example of such a failure.
478 /// If you wish to retry individual MPP parts and learn when a payment has failed, you must
479 /// call [`ChannelManager::abandon_payment`] and wait for a [`Event::PaymentFailed`] event.
481 /// (1) <https://github.com/lightningdevkit/rust-lightning/issues/1164>
483 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
484 all_paths_failed: bool,
485 /// The payment path that failed.
487 /// The channel responsible for the failed payment path.
489 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
490 /// may not refer to a channel in the public network graph. These aliases may also collide
491 /// with channels in the public network graph.
493 /// If this is `Some`, then the corresponding channel should be avoided when the payment is
494 /// retried. May be `None` for older [`Event`] serializations.
495 short_channel_id: Option<u64>,
496 /// Parameters needed to compute a new [`Route`] when retrying the failed payment path.
498 /// See [`find_route`] for details.
500 /// [`Route`]: crate::routing::router::Route
501 /// [`find_route`]: crate::routing::router::find_route
502 retry: Option<RouteParameters>,
504 error_code: Option<u16>,
506 error_data: Option<Vec<u8>>,
508 /// Indicates that a probe payment we sent returned successful, i.e., only failed at the destination.
510 /// The id returned by [`ChannelManager::send_probe`].
512 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
513 payment_id: PaymentId,
514 /// The hash generated by [`ChannelManager::send_probe`].
516 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
517 payment_hash: PaymentHash,
518 /// The payment path that was successful.
521 /// Indicates that a probe payment we sent failed at an intermediary node on the path.
523 /// The id returned by [`ChannelManager::send_probe`].
525 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
526 payment_id: PaymentId,
527 /// The hash generated by [`ChannelManager::send_probe`].
529 /// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
530 payment_hash: PaymentHash,
531 /// The payment path that failed.
533 /// The channel responsible for the failed probe.
535 /// Note that for route hints or for the first hop in a path this may be an SCID alias and
536 /// may not refer to a channel in the public network graph. These aliases may also collide
537 /// with channels in the public network graph.
538 short_channel_id: Option<u64>,
540 /// Used to indicate that [`ChannelManager::process_pending_htlc_forwards`] should be called at
541 /// a time in the future.
543 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
544 PendingHTLCsForwardable {
545 /// The minimum amount of time that should be waited prior to calling
546 /// process_pending_htlc_forwards. To increase the effort required to correlate payments,
547 /// you should wait a random amount of time in roughly the range (now + time_forwardable,
548 /// now + 5*time_forwardable).
549 time_forwardable: Duration,
551 /// Used to indicate that an output which you should know how to spend was confirmed on chain
552 /// and is now spendable.
553 /// Such an output will *not* ever be spent by rust-lightning, and are not at risk of your
554 /// counterparty spending them due to some kind of timeout. Thus, you need to store them
555 /// somewhere and spend them when you create on-chain transactions.
557 /// The outputs which you should store as spendable by you.
558 outputs: Vec<SpendableOutputDescriptor>,
560 /// This event is generated when a payment has been successfully forwarded through us and a
561 /// forwarding fee earned.
563 /// The incoming channel between the previous node and us. This is only `None` for events
564 /// generated or serialized by versions prior to 0.0.107.
565 prev_channel_id: Option<[u8; 32]>,
566 /// The outgoing channel between the next node and us. This is only `None` for events
567 /// generated or serialized by versions prior to 0.0.107.
568 next_channel_id: Option<[u8; 32]>,
569 /// The fee, in milli-satoshis, which was earned as a result of the payment.
571 /// Note that if we force-closed the channel over which we forwarded an HTLC while the HTLC
572 /// was pending, the amount the next hop claimed will have been rounded down to the nearest
573 /// whole satoshi. Thus, the fee calculated here may be higher than expected as we still
574 /// claimed the full value in millisatoshis from the source. In this case,
575 /// `claim_from_onchain_tx` will be set.
577 /// If the channel which sent us the payment has been force-closed, we will claim the funds
578 /// via an on-chain transaction. In that case we do not yet know the on-chain transaction
579 /// fees which we will spend and will instead set this to `None`. It is possible duplicate
580 /// `PaymentForwarded` events are generated for the same payment iff `fee_earned_msat` is
582 fee_earned_msat: Option<u64>,
583 /// If this is `true`, the forwarded HTLC was claimed by our counterparty via an on-chain
585 claim_from_onchain_tx: bool,
587 /// Used to indicate that a previously opened channel with the given `channel_id` is in the
588 /// process of closure.
590 /// The channel_id of the channel which has been closed. Note that on-chain transactions
591 /// resolving the channel are likely still awaiting confirmation.
592 channel_id: [u8; 32],
593 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
594 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
595 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
596 /// `user_channel_id` will be 0 for an inbound channel.
597 /// This will always be zero for objects serialized with LDK versions prior to 0.0.102.
599 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
600 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
601 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
602 user_channel_id: u64,
603 /// The reason the channel was closed.
604 reason: ClosureReason
606 /// Used to indicate to the user that they can abandon the funding transaction and recycle the
607 /// inputs for another purpose.
609 /// The channel_id of the channel which has been closed.
610 channel_id: [u8; 32],
611 /// The full transaction received from the user
612 transaction: Transaction
614 /// Indicates a request to open a new channel by a peer.
616 /// To accept the request, call [`ChannelManager::accept_inbound_channel`]. To reject the
617 /// request, call [`ChannelManager::force_close_without_broadcasting_txn`].
619 /// The event is only triggered when a new open channel request is received and the
620 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true.
622 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
623 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
624 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
626 /// The temporary channel ID of the channel requested to be opened.
628 /// When responding to the request, the `temporary_channel_id` should be passed
629 /// back to the ChannelManager through [`ChannelManager::accept_inbound_channel`] to accept,
630 /// or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject.
632 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
633 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
634 temporary_channel_id: [u8; 32],
635 /// The node_id of the counterparty requesting to open the channel.
637 /// When responding to the request, the `counterparty_node_id` should be passed
638 /// back to the `ChannelManager` through [`ChannelManager::accept_inbound_channel`] to
639 /// accept the request, or through [`ChannelManager::force_close_without_broadcasting_txn`] to reject the
642 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
643 /// [`ChannelManager::force_close_without_broadcasting_txn`]: crate::ln::channelmanager::ChannelManager::force_close_without_broadcasting_txn
644 counterparty_node_id: PublicKey,
645 /// The channel value of the requested channel.
646 funding_satoshis: u64,
647 /// Our starting balance in the channel if the request is accepted, in milli-satoshi.
649 /// The features that this channel will operate with. If you reject the channel, a
650 /// well-behaved counterparty may automatically re-attempt the channel with a new set of
653 /// Note that if [`ChannelTypeFeatures::supports_scid_privacy`] returns true on this type,
654 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
657 /// Furthermore, note that if [`ChannelTypeFeatures::supports_zero_conf`] returns true on this type,
658 /// the resulting [`ChannelManager`] will not be readable by versions of LDK prior to
659 /// 0.0.107. Channels setting this type also need to get manually accepted via
660 /// [`crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`],
661 /// or will be rejected otherwise.
663 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
664 channel_type: ChannelTypeFeatures,
666 /// Indicates that the HTLC was accepted, but could not be processed when or after attempting to
669 /// Some scenarios where this event may be sent include:
670 /// * Insufficient capacity in the outbound channel
671 /// * While waiting to forward the HTLC, the channel it is meant to be forwarded through closes
672 /// * When an unknown SCID is requested for forwarding a payment.
673 /// * Claiming an amount for an MPP payment that exceeds the HTLC total
674 /// * The HTLC has timed out
676 /// This event, however, does not get generated if an HTLC fails to meet the forwarding
677 /// requirements (i.e. insufficient fees paid, or a CLTV that is too soon).
679 /// The channel over which the HTLC was received.
680 prev_channel_id: [u8; 32],
681 /// Destination of the HTLC that failed to be processed.
682 failed_next_destination: HTLCDestination,
685 /// Indicates that a transaction originating from LDK needs to have its fee bumped. This event
686 /// requires confirmed external funds to be readily available to spend.
688 /// LDK does not currently generate this event. It is limited to the scope of channels with
689 /// anchor outputs, which will be introduced in a future release.
690 BumpTransaction(BumpTransactionEvent),
693 impl Writeable for Event {
694 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
696 &Event::FundingGenerationReady { .. } => {
698 // We never write out FundingGenerationReady events as, upon disconnection, peers
699 // drop any channels which have not yet exchanged funding_signed.
701 &Event::PaymentReceived { ref payment_hash, ref amount_msat, ref purpose } => {
703 let mut payment_secret = None;
704 let payment_preimage;
706 PaymentPurpose::InvoicePayment { payment_preimage: preimage, payment_secret: secret } => {
707 payment_secret = Some(secret);
708 payment_preimage = *preimage;
710 PaymentPurpose::SpontaneousPayment(preimage) => {
711 payment_preimage = Some(*preimage);
714 write_tlv_fields!(writer, {
715 (0, payment_hash, required),
716 (2, payment_secret, option),
717 (4, amount_msat, required),
718 (6, 0u64, required), // user_payment_id required for compatibility with 0.0.103 and earlier
719 (8, payment_preimage, option),
722 &Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
724 write_tlv_fields!(writer, {
725 (0, payment_preimage, required),
726 (1, payment_hash, required),
727 (3, payment_id, option),
728 (5, fee_paid_msat, option),
731 &Event::PaymentPathFailed {
732 ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update,
733 ref all_paths_failed, ref path, ref short_channel_id, ref retry,
741 error_code.write(writer)?;
743 error_data.write(writer)?;
744 write_tlv_fields!(writer, {
745 (0, payment_hash, required),
746 (1, network_update, option),
747 (2, payment_failed_permanently, required),
748 (3, all_paths_failed, required),
750 (7, short_channel_id, option),
752 (11, payment_id, option),
755 &Event::PendingHTLCsForwardable { time_forwardable: _ } => {
757 // Note that we now ignore these on the read end as we'll re-generate them in
758 // ChannelManager, we write them here only for backwards compatibility.
760 &Event::SpendableOutputs { ref outputs } => {
762 write_tlv_fields!(writer, {
763 (0, VecWriteWrapper(outputs), required),
766 &Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
768 write_tlv_fields!(writer, {
769 (0, fee_earned_msat, option),
770 (1, prev_channel_id, option),
771 (2, claim_from_onchain_tx, required),
772 (3, next_channel_id, option),
775 &Event::ChannelClosed { ref channel_id, ref user_channel_id, ref reason } => {
777 write_tlv_fields!(writer, {
778 (0, channel_id, required),
779 (1, user_channel_id, required),
780 (2, reason, required)
783 &Event::DiscardFunding { ref channel_id, ref transaction } => {
785 write_tlv_fields!(writer, {
786 (0, channel_id, required),
787 (2, transaction, required)
790 &Event::PaymentPathSuccessful { ref payment_id, ref payment_hash, ref path } => {
792 write_tlv_fields!(writer, {
793 (0, payment_id, required),
794 (2, payment_hash, option),
798 &Event::PaymentFailed { ref payment_id, ref payment_hash } => {
800 write_tlv_fields!(writer, {
801 (0, payment_id, required),
802 (2, payment_hash, required),
805 &Event::OpenChannelRequest { .. } => {
807 // We never write the OpenChannelRequest events as, upon disconnection, peers
808 // drop any channels which have not yet exchanged funding_signed.
810 &Event::PaymentClaimed { ref payment_hash, ref amount_msat, ref purpose } => {
812 write_tlv_fields!(writer, {
813 (0, payment_hash, required),
814 (2, purpose, required),
815 (4, amount_msat, required),
818 &Event::ProbeSuccessful { ref payment_id, ref payment_hash, ref path } => {
820 write_tlv_fields!(writer, {
821 (0, payment_id, required),
822 (2, payment_hash, required),
826 &Event::ProbeFailed { ref payment_id, ref payment_hash, ref path, ref short_channel_id } => {
828 write_tlv_fields!(writer, {
829 (0, payment_id, required),
830 (2, payment_hash, required),
832 (6, short_channel_id, option),
835 &Event::HTLCHandlingFailed { ref prev_channel_id, ref failed_next_destination } => {
837 write_tlv_fields!(writer, {
838 (0, prev_channel_id, required),
839 (2, failed_next_destination, required),
843 &Event::BumpTransaction(ref event)=> {
846 // We never write the ChannelClose events as they'll be replayed upon restarting
847 // anyway if the commitment transaction remains unconfirmed.
848 BumpTransactionEvent::ChannelClose { .. } => {}
851 // Note that, going forward, all new events must only write data inside of
852 // `write_tlv_fields`. Versions 0.0.101+ will ignore odd-numbered events that write
853 // data via `write_tlv_fields`.
858 impl MaybeReadable for Event {
859 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, msgs::DecodeError> {
860 match Readable::read(reader)? {
861 // Note that we do not write a length-prefixed TLV for FundingGenerationReady events,
862 // unlike all other events, thus we return immediately here.
866 let mut payment_hash = PaymentHash([0; 32]);
867 let mut payment_preimage = None;
868 let mut payment_secret = None;
869 let mut amount_msat = 0;
870 let mut _user_payment_id = None::<u64>; // For compatibility with 0.0.103 and earlier
871 read_tlv_fields!(reader, {
872 (0, payment_hash, required),
873 (2, payment_secret, option),
874 (4, amount_msat, required),
875 (6, _user_payment_id, option),
876 (8, payment_preimage, option),
878 let purpose = match payment_secret {
879 Some(secret) => PaymentPurpose::InvoicePayment {
881 payment_secret: secret
883 None if payment_preimage.is_some() => PaymentPurpose::SpontaneousPayment(payment_preimage.unwrap()),
884 None => return Err(msgs::DecodeError::InvalidValue),
886 Ok(Some(Event::PaymentReceived {
896 let mut payment_preimage = PaymentPreimage([0; 32]);
897 let mut payment_hash = None;
898 let mut payment_id = None;
899 let mut fee_paid_msat = None;
900 read_tlv_fields!(reader, {
901 (0, payment_preimage, required),
902 (1, payment_hash, option),
903 (3, payment_id, option),
904 (5, fee_paid_msat, option),
906 if payment_hash.is_none() {
907 payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()));
909 Ok(Some(Event::PaymentSent {
912 payment_hash: payment_hash.unwrap(),
921 let error_code = Readable::read(reader)?;
923 let error_data = Readable::read(reader)?;
924 let mut payment_hash = PaymentHash([0; 32]);
925 let mut payment_failed_permanently = false;
926 let mut network_update = None;
927 let mut all_paths_failed = Some(true);
928 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
929 let mut short_channel_id = None;
930 let mut retry = None;
931 let mut payment_id = None;
932 read_tlv_fields!(reader, {
933 (0, payment_hash, required),
934 (1, network_update, ignorable),
935 (2, payment_failed_permanently, required),
936 (3, all_paths_failed, option),
938 (7, short_channel_id, option),
940 (11, payment_id, option),
942 Ok(Some(Event::PaymentPathFailed {
945 payment_failed_permanently,
947 all_paths_failed: all_paths_failed.unwrap(),
962 let mut outputs = VecReadWrapper(Vec::new());
963 read_tlv_fields!(reader, {
964 (0, outputs, required),
966 Ok(Some(Event::SpendableOutputs { outputs: outputs.0 }))
972 let mut fee_earned_msat = None;
973 let mut prev_channel_id = None;
974 let mut claim_from_onchain_tx = false;
975 let mut next_channel_id = None;
976 read_tlv_fields!(reader, {
977 (0, fee_earned_msat, option),
978 (1, prev_channel_id, option),
979 (2, claim_from_onchain_tx, required),
980 (3, next_channel_id, option),
982 Ok(Some(Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id }))
988 let mut channel_id = [0; 32];
989 let mut reason = None;
990 let mut user_channel_id_opt = None;
991 read_tlv_fields!(reader, {
992 (0, channel_id, required),
993 (1, user_channel_id_opt, option),
994 (2, reason, ignorable),
996 if reason.is_none() { return Ok(None); }
997 let user_channel_id = if let Some(id) = user_channel_id_opt { id } else { 0 };
998 Ok(Some(Event::ChannelClosed { channel_id, user_channel_id, reason: reason.unwrap() }))
1004 let mut channel_id = [0; 32];
1005 let mut transaction = Transaction{ version: 2, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
1006 read_tlv_fields!(reader, {
1007 (0, channel_id, required),
1008 (2, transaction, required),
1010 Ok(Some(Event::DiscardFunding { channel_id, transaction } ))
1016 let mut payment_id = PaymentId([0; 32]);
1017 let mut payment_hash = None;
1018 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1019 read_tlv_fields!(reader, {
1020 (0, payment_id, required),
1021 (2, payment_hash, option),
1022 (4, path, vec_type),
1024 Ok(Some(Event::PaymentPathSuccessful {
1027 path: path.unwrap(),
1034 let mut payment_hash = PaymentHash([0; 32]);
1035 let mut payment_id = PaymentId([0; 32]);
1036 read_tlv_fields!(reader, {
1037 (0, payment_id, required),
1038 (2, payment_hash, required),
1040 Ok(Some(Event::PaymentFailed {
1048 // Value 17 is used for `Event::OpenChannelRequest`.
1053 let mut payment_hash = PaymentHash([0; 32]);
1054 let mut purpose = None;
1055 let mut amount_msat = 0;
1056 read_tlv_fields!(reader, {
1057 (0, payment_hash, required),
1058 (2, purpose, ignorable),
1059 (4, amount_msat, required),
1061 if purpose.is_none() { return Ok(None); }
1062 Ok(Some(Event::PaymentClaimed {
1064 purpose: purpose.unwrap(),
1072 let mut payment_id = PaymentId([0; 32]);
1073 let mut payment_hash = PaymentHash([0; 32]);
1074 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1075 read_tlv_fields!(reader, {
1076 (0, payment_id, required),
1077 (2, payment_hash, required),
1078 (4, path, vec_type),
1080 Ok(Some(Event::ProbeSuccessful {
1083 path: path.unwrap(),
1090 let mut payment_id = PaymentId([0; 32]);
1091 let mut payment_hash = PaymentHash([0; 32]);
1092 let mut path: Option<Vec<RouteHop>> = Some(vec![]);
1093 let mut short_channel_id = None;
1094 read_tlv_fields!(reader, {
1095 (0, payment_id, required),
1096 (2, payment_hash, required),
1097 (4, path, vec_type),
1098 (6, short_channel_id, option),
1100 Ok(Some(Event::ProbeFailed {
1103 path: path.unwrap(),
1111 let mut prev_channel_id = [0; 32];
1112 let mut failed_next_destination_opt = None;
1113 read_tlv_fields!(reader, {
1114 (0, prev_channel_id, required),
1115 (2, failed_next_destination_opt, ignorable),
1117 if let Some(failed_next_destination) = failed_next_destination_opt {
1118 Ok(Some(Event::HTLCHandlingFailed {
1120 failed_next_destination,
1123 // If we fail to read a `failed_next_destination` assume it's because
1124 // `MaybeReadable::read` returned `Ok(None)`, though it's also possible we
1125 // were simply missing the field.
1131 // Versions prior to 0.0.100 did not ignore odd types, instead returning InvalidValue.
1132 // Version 0.0.100 failed to properly ignore odd types, possibly resulting in corrupt
1134 x if x % 2 == 1 => {
1135 // If the event is of unknown type, assume it was written with `write_tlv_fields`,
1136 // which prefixes the whole thing with a length BigSize. Because the event is
1137 // odd-type unknown, we should treat it as `Ok(None)` even if it has some TLV
1138 // fields that are even. Thus, we avoid using `read_tlv_fields` and simply read
1139 // exactly the number of bytes specified, ignoring them entirely.
1140 let tlv_len: BigSize = Readable::read(reader)?;
1141 FixedLengthReader::new(reader, tlv_len.0)
1142 .eat_remaining().map_err(|_| msgs::DecodeError::ShortRead)?;
1145 _ => Err(msgs::DecodeError::InvalidValue)
1150 /// An event generated by ChannelManager which indicates a message should be sent to a peer (or
1151 /// broadcast to most peers).
1152 /// These events are handled by PeerManager::process_events if you are using a PeerManager.
1153 #[derive(Clone, Debug)]
1154 pub enum MessageSendEvent {
1155 /// Used to indicate that we've accepted a channel open and should send the accept_channel
1156 /// message provided to the given peer.
1158 /// The node_id of the node which should receive this message
1160 /// The message which should be sent.
1161 msg: msgs::AcceptChannel,
1163 /// Used to indicate that we've initiated a channel open and should send the open_channel
1164 /// message provided to the given peer.
1166 /// The node_id of the node which should receive this message
1168 /// The message which should be sent.
1169 msg: msgs::OpenChannel,
1171 /// Used to indicate that a funding_created message should be sent to the peer with the given node_id.
1172 SendFundingCreated {
1173 /// The node_id of the node which should receive this message
1175 /// The message which should be sent.
1176 msg: msgs::FundingCreated,
1178 /// Used to indicate that a funding_signed message should be sent to the peer with the given node_id.
1180 /// The node_id of the node which should receive this message
1182 /// The message which should be sent.
1183 msg: msgs::FundingSigned,
1185 /// Used to indicate that a channel_ready message should be sent to the peer with the given node_id.
1187 /// The node_id of the node which should receive these message(s)
1189 /// The channel_ready message which should be sent.
1190 msg: msgs::ChannelReady,
1192 /// Used to indicate that an announcement_signatures message should be sent to the peer with the given node_id.
1193 SendAnnouncementSignatures {
1194 /// The node_id of the node which should receive these message(s)
1196 /// The announcement_signatures message which should be sent.
1197 msg: msgs::AnnouncementSignatures,
1199 /// Used to indicate that a series of HTLC update messages, as well as a commitment_signed
1200 /// message should be sent to the peer with the given node_id.
1202 /// The node_id of the node which should receive these message(s)
1204 /// The update messages which should be sent. ALL messages in the struct should be sent!
1205 updates: msgs::CommitmentUpdate,
1207 /// Used to indicate that a revoke_and_ack message should be sent to the peer with the given node_id.
1209 /// The node_id of the node which should receive this message
1211 /// The message which should be sent.
1212 msg: msgs::RevokeAndACK,
1214 /// Used to indicate that a closing_signed message should be sent to the peer with the given node_id.
1216 /// The node_id of the node which should receive this message
1218 /// The message which should be sent.
1219 msg: msgs::ClosingSigned,
1221 /// Used to indicate that a shutdown message should be sent to the peer with the given node_id.
1223 /// The node_id of the node which should receive this message
1225 /// The message which should be sent.
1226 msg: msgs::Shutdown,
1228 /// Used to indicate that a channel_reestablish message should be sent to the peer with the given node_id.
1229 SendChannelReestablish {
1230 /// The node_id of the node which should receive this message
1232 /// The message which should be sent.
1233 msg: msgs::ChannelReestablish,
1235 /// Used to send a channel_announcement and channel_update to a specific peer, likely on
1236 /// initial connection to ensure our peers know about our channels.
1237 SendChannelAnnouncement {
1238 /// The node_id of the node which should receive this message
1240 /// The channel_announcement which should be sent.
1241 msg: msgs::ChannelAnnouncement,
1242 /// The followup channel_update which should be sent.
1243 update_msg: msgs::ChannelUpdate,
1245 /// Used to indicate that a channel_announcement and channel_update should be broadcast to all
1246 /// peers (except the peer with node_id either msg.contents.node_id_1 or msg.contents.node_id_2).
1248 /// Note that after doing so, you very likely (unless you did so very recently) want to
1249 /// broadcast a node_announcement (e.g. via [`PeerManager::broadcast_node_announcement`]). This
1250 /// ensures that any nodes which see our channel_announcement also have a relevant
1251 /// node_announcement, including relevant feature flags which may be important for routing
1252 /// through or to us.
1254 /// [`PeerManager::broadcast_node_announcement`]: crate::ln::peer_handler::PeerManager::broadcast_node_announcement
1255 BroadcastChannelAnnouncement {
1256 /// The channel_announcement which should be sent.
1257 msg: msgs::ChannelAnnouncement,
1258 /// The followup channel_update which should be sent.
1259 update_msg: msgs::ChannelUpdate,
1261 /// Used to indicate that a channel_update should be broadcast to all peers.
1262 BroadcastChannelUpdate {
1263 /// The channel_update which should be sent.
1264 msg: msgs::ChannelUpdate,
1266 /// Used to indicate that a channel_update should be sent to a single peer.
1267 /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a
1268 /// private channel and we shouldn't be informing all of our peers of channel parameters.
1270 /// The node_id of the node which should receive this message
1272 /// The channel_update which should be sent.
1273 msg: msgs::ChannelUpdate,
1275 /// Broadcast an error downstream to be handled
1277 /// The node_id of the node which should receive this message
1279 /// The action which should be taken.
1280 action: msgs::ErrorAction
1282 /// Query a peer for channels with funding transaction UTXOs in a block range.
1283 SendChannelRangeQuery {
1284 /// The node_id of this message recipient
1286 /// The query_channel_range which should be sent.
1287 msg: msgs::QueryChannelRange,
1289 /// Request routing gossip messages from a peer for a list of channels identified by
1290 /// their short_channel_ids.
1292 /// The node_id of this message recipient
1294 /// The query_short_channel_ids which should be sent.
1295 msg: msgs::QueryShortChannelIds,
1297 /// Sends a reply to a channel range query. This may be one of several SendReplyChannelRange events
1298 /// emitted during processing of the query.
1299 SendReplyChannelRange {
1300 /// The node_id of this message recipient
1302 /// The reply_channel_range which should be sent.
1303 msg: msgs::ReplyChannelRange,
1305 /// Sends a timestamp filter for inbound gossip. This should be sent on each new connection to
1306 /// enable receiving gossip messages from the peer.
1307 SendGossipTimestampFilter {
1308 /// The node_id of this message recipient
1310 /// The gossip_timestamp_filter which should be sent.
1311 msg: msgs::GossipTimestampFilter,
1315 /// A trait indicating an object may generate message send events
1316 pub trait MessageSendEventsProvider {
1317 /// Gets the list of pending events which were generated by previous actions, clearing the list
1319 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent>;
1322 /// A trait indicating an object may generate onion messages to send
1323 pub trait OnionMessageProvider {
1324 /// Gets the next pending onion message for the peer with the given node id.
1325 fn next_onion_message_for_peer(&self, peer_node_id: PublicKey) -> Option<msgs::OnionMessage>;
1328 /// A trait indicating an object may generate events.
1330 /// Events are processed by passing an [`EventHandler`] to [`process_pending_events`].
1334 /// When using this trait, [`process_pending_events`] will call [`handle_event`] for each pending
1335 /// event since the last invocation.
1337 /// In order to ensure no [`Event`]s are lost, implementors of this trait will persist [`Event`]s
1338 /// and replay any unhandled events on startup. An [`Event`] is considered handled when
1339 /// [`process_pending_events`] returns, thus handlers MUST fully handle [`Event`]s and persist any
1340 /// relevant changes to disk *before* returning.
1342 /// Further, because an application may crash between an [`Event`] being handled and the
1343 /// implementor of this trait being re-serialized, [`Event`] handling must be idempotent - in
1344 /// effect, [`Event`]s may be replayed.
1346 /// Note, handlers may call back into the provider and thus deadlocking must be avoided. Be sure to
1347 /// consult the provider's documentation on the implication of processing events and how a handler
1348 /// may safely use the provider (e.g., see [`ChannelManager::process_pending_events`] and
1349 /// [`ChainMonitor::process_pending_events`]).
1351 /// (C-not implementable) As there is likely no reason for a user to implement this trait on their
1354 /// [`process_pending_events`]: Self::process_pending_events
1355 /// [`handle_event`]: EventHandler::handle_event
1356 /// [`ChannelManager::process_pending_events`]: crate::ln::channelmanager::ChannelManager#method.process_pending_events
1357 /// [`ChainMonitor::process_pending_events`]: crate::chain::chainmonitor::ChainMonitor#method.process_pending_events
1358 pub trait EventsProvider {
1359 /// Processes any events generated since the last call using the given event handler.
1361 /// See the trait-level documentation for requirements.
1362 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler;
1365 /// A trait implemented for objects handling events from [`EventsProvider`].
1366 pub trait EventHandler {
1367 /// Handles the given [`Event`].
1369 /// See [`EventsProvider`] for details that must be considered when implementing this method.
1370 fn handle_event(&self, event: &Event);
1373 impl<F> EventHandler for F where F: Fn(&Event) {
1374 fn handle_event(&self, event: &Event) {
1379 impl<T: EventHandler> EventHandler for Arc<T> {
1380 fn handle_event(&self, event: &Event) {
1381 self.deref().handle_event(event)