lightning/ln/channel_state.rs
1// This file is Copyright its original authors, visible in version control
2// history.
3//
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
8// licenses.
9
10//! Information about the state of a channel.
11
12use alloc::vec::Vec;
13
14use bitcoin::secp256k1::PublicKey;
15
16use crate::chain::chaininterface::{FeeEstimator, LowerBoundedFeeEstimator};
17use crate::chain::transaction::OutPoint;
18use crate::ln::channel::Channel;
19use crate::ln::types::ChannelId;
20use crate::sign::SignerProvider;
21use crate::types::features::{ChannelTypeFeatures, InitFeatures};
22use crate::types::payment::PaymentHash;
23use crate::util::config::ChannelConfig;
24
25use core::ops::Deref;
26
27/// Exposes the state of pending inbound HTLCs.
28///
29/// At a high level, an HTLC being forwarded from one Lightning node to another Lightning node goes
30/// through the following states in the state machine:
31/// - Announced for addition by the originating node through the update_add_htlc message.
32/// - Added to the commitment transaction of the receiving node and originating node in turn
33/// through the exchange of commitment_signed and revoke_and_ack messages.
34/// - Announced for resolution (fulfillment or failure) by the receiving node through either one of
35/// the update_fulfill_htlc, update_fail_htlc, and update_fail_malformed_htlc messages.
36/// - Removed from the commitment transaction of the originating node and receiving node in turn
37/// through the exchange of commitment_signed and revoke_and_ack messages.
38///
39/// This can be used to inspect what next message an HTLC is waiting for to advance its state.
40#[derive(Clone, Debug, PartialEq)]
41pub enum InboundHTLCStateDetails {
42 /// We have added this HTLC in our commitment transaction by receiving commitment_signed and
43 /// returning revoke_and_ack. We are awaiting the appropriate revoke_and_ack's from the remote
44 /// before this HTLC is included on the remote commitment transaction.
45 AwaitingRemoteRevokeToAdd,
46 /// This HTLC has been included in the commitment_signed and revoke_and_ack messages on both sides
47 /// and is included in both commitment transactions.
48 ///
49 /// This HTLC is now safe to either forward or be claimed as a payment by us. The HTLC will
50 /// remain in this state until the forwarded upstream HTLC has been resolved and we resolve this
51 /// HTLC correspondingly, or until we claim it as a payment. If it is part of a multipart
52 /// payment, it will only be claimed together with other required parts.
53 Committed,
54 /// We have received the preimage for this HTLC and it is being removed by fulfilling it with
55 /// update_fulfill_htlc. This HTLC is still on both commitment transactions, but we are awaiting
56 /// the appropriate revoke_and_ack's from the remote before this HTLC is removed from the remote
57 /// commitment transaction after update_fulfill_htlc.
58 AwaitingRemoteRevokeToRemoveFulfill,
59 /// The HTLC is being removed by failing it with update_fail_htlc or update_fail_malformed_htlc.
60 /// This HTLC is still on both commitment transactions, but we are awaiting the appropriate
61 /// revoke_and_ack's from the remote before this HTLC is removed from the remote commitment
62 /// transaction.
63 AwaitingRemoteRevokeToRemoveFail,
64}
65
66impl_writeable_tlv_based_enum_upgradable!(InboundHTLCStateDetails,
67 (0, AwaitingRemoteRevokeToAdd) => {},
68 (2, Committed) => {},
69 (4, AwaitingRemoteRevokeToRemoveFulfill) => {},
70 (6, AwaitingRemoteRevokeToRemoveFail) => {},
71);
72
73/// Exposes details around pending inbound HTLCs.
74#[derive(Clone, Debug, PartialEq)]
75pub struct InboundHTLCDetails {
76 /// The HTLC ID.
77 /// The IDs are incremented by 1 starting from 0 for each offered HTLC.
78 /// They are unique per channel and inbound/outbound direction, unless an HTLC was only announced
79 /// and not part of any commitment transaction.
80 pub htlc_id: u64,
81 /// The amount in msat.
82 pub amount_msat: u64,
83 /// The block height at which this HTLC expires.
84 pub cltv_expiry: u32,
85 /// The payment hash.
86 pub payment_hash: PaymentHash,
87 /// The state of the HTLC in the state machine.
88 ///
89 /// Determines on which commitment transactions the HTLC is included and what message the HTLC is
90 /// waiting for to advance to the next state.
91 ///
92 /// See [`InboundHTLCStateDetails`] for information on the specific states.
93 ///
94 /// LDK will always fill this field in, but when downgrading to prior versions of LDK, new
95 /// states may result in `None` here.
96 pub state: Option<InboundHTLCStateDetails>,
97 /// Whether the HTLC has an output below the local dust limit. If so, the output will be trimmed
98 /// from the local commitment transaction and added to the commitment transaction fee.
99 /// For non-anchor channels, this takes into account the cost of the second-stage HTLC
100 /// transactions as well.
101 ///
102 /// When the local commitment transaction is broadcasted as part of a unilateral closure,
103 /// the value of this HTLC will therefore not be claimable but instead burned as a transaction
104 /// fee.
105 ///
106 /// Note that dust limits are specific to each party. An HTLC can be dust for the local
107 /// commitment transaction but not for the counterparty's commitment transaction and vice versa.
108 pub is_dust: bool,
109}
110
111impl_writeable_tlv_based!(InboundHTLCDetails, {
112 (0, htlc_id, required),
113 (2, amount_msat, required),
114 (4, cltv_expiry, required),
115 (6, payment_hash, required),
116 (7, state, upgradable_option),
117 (8, is_dust, required),
118});
119
120/// Exposes the state of pending outbound HTLCs.
121///
122/// At a high level, an HTLC being forwarded from one Lightning node to another Lightning node goes
123/// through the following states in the state machine:
124/// - Announced for addition by the originating node through the update_add_htlc message.
125/// - Added to the commitment transaction of the receiving node and originating node in turn
126/// through the exchange of commitment_signed and revoke_and_ack messages.
127/// - Announced for resolution (fulfillment or failure) by the receiving node through either one of
128/// the update_fulfill_htlc, update_fail_htlc, and update_fail_malformed_htlc messages.
129/// - Removed from the commitment transaction of the originating node and receiving node in turn
130/// through the exchange of commitment_signed and revoke_and_ack messages.
131///
132/// This can be used to inspect what next message an HTLC is waiting for to advance its state.
133#[derive(Clone, Debug, PartialEq)]
134pub enum OutboundHTLCStateDetails {
135 /// We are awaiting the appropriate revoke_and_ack's from the remote before the HTLC is added
136 /// on the remote's commitment transaction after update_add_htlc.
137 AwaitingRemoteRevokeToAdd,
138 /// The HTLC has been added to the remote's commitment transaction by sending commitment_signed
139 /// and receiving revoke_and_ack in return.
140 ///
141 /// The HTLC will remain in this state until the remote node resolves the HTLC, or until we
142 /// unilaterally close the channel due to a timeout with an uncooperative remote node.
143 Committed,
144 /// The HTLC has been fulfilled successfully by the remote with a preimage in update_fulfill_htlc,
145 /// and we removed the HTLC from our commitment transaction by receiving commitment_signed and
146 /// returning revoke_and_ack. We are awaiting the appropriate revoke_and_ack's from the remote
147 /// for the removal from its commitment transaction.
148 AwaitingRemoteRevokeToRemoveSuccess,
149 /// The HTLC has been failed by the remote with update_fail_htlc or update_fail_malformed_htlc,
150 /// and we removed the HTLC from our commitment transaction by receiving commitment_signed and
151 /// returning revoke_and_ack. We are awaiting the appropriate revoke_and_ack's from the remote
152 /// for the removal from its commitment transaction.
153 AwaitingRemoteRevokeToRemoveFailure,
154}
155
156impl_writeable_tlv_based_enum_upgradable!(OutboundHTLCStateDetails,
157 (0, AwaitingRemoteRevokeToAdd) => {},
158 (2, Committed) => {},
159 (4, AwaitingRemoteRevokeToRemoveSuccess) => {},
160 (6, AwaitingRemoteRevokeToRemoveFailure) => {},
161);
162
163/// Exposes details around pending outbound HTLCs.
164#[derive(Clone, Debug, PartialEq)]
165pub struct OutboundHTLCDetails {
166 /// The HTLC ID.
167 /// The IDs are incremented by 1 starting from 0 for each offered HTLC.
168 /// They are unique per channel and inbound/outbound direction, unless an HTLC was only announced
169 /// and not part of any commitment transaction.
170 ///
171 /// Not present when we are awaiting a remote revocation and the HTLC is not added yet.
172 pub htlc_id: Option<u64>,
173 /// The amount in msat.
174 pub amount_msat: u64,
175 /// The block height at which this HTLC expires.
176 pub cltv_expiry: u32,
177 /// The payment hash.
178 pub payment_hash: PaymentHash,
179 /// The state of the HTLC in the state machine.
180 ///
181 /// Determines on which commitment transactions the HTLC is included and what message the HTLC is
182 /// waiting for to advance to the next state.
183 ///
184 /// See [`OutboundHTLCStateDetails`] for information on the specific states.
185 ///
186 /// LDK will always fill this field in, but when downgrading to prior versions of LDK, new
187 /// states may result in `None` here.
188 pub state: Option<OutboundHTLCStateDetails>,
189 /// The extra fee being skimmed off the top of this HTLC.
190 pub skimmed_fee_msat: Option<u64>,
191 /// Whether the HTLC has an output below the local dust limit. If so, the output will be trimmed
192 /// from the local commitment transaction and added to the commitment transaction fee.
193 /// For non-anchor channels, this takes into account the cost of the second-stage HTLC
194 /// transactions as well.
195 ///
196 /// When the local commitment transaction is broadcasted as part of a unilateral closure,
197 /// the value of this HTLC will therefore not be claimable but instead burned as a transaction
198 /// fee.
199 ///
200 /// Note that dust limits are specific to each party. An HTLC can be dust for the local
201 /// commitment transaction but not for the counterparty's commitment transaction and vice versa.
202 pub is_dust: bool,
203}
204
205impl_writeable_tlv_based!(OutboundHTLCDetails, {
206 (0, htlc_id, required),
207 (2, amount_msat, required),
208 (4, cltv_expiry, required),
209 (6, payment_hash, required),
210 (7, state, upgradable_option),
211 (8, skimmed_fee_msat, required),
212 (10, is_dust, required),
213});
214
215/// Information needed for constructing an invoice route hint for this channel.
216#[derive(Clone, Debug, PartialEq)]
217pub struct CounterpartyForwardingInfo {
218 /// Base routing fee in millisatoshis.
219 pub fee_base_msat: u32,
220 /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
221 pub fee_proportional_millionths: u32,
222 /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
223 /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
224 /// `cltv_expiry_delta` for more details.
225 pub cltv_expiry_delta: u16,
226}
227
228impl_writeable_tlv_based!(CounterpartyForwardingInfo, {
229 (2, fee_base_msat, required),
230 (4, fee_proportional_millionths, required),
231 (6, cltv_expiry_delta, required),
232});
233
234/// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
235/// to better separate parameters.
236#[derive(Clone, Debug, PartialEq)]
237pub struct ChannelCounterparty {
238 /// The node_id of our counterparty
239 pub node_id: PublicKey,
240 /// The Features the channel counterparty provided upon last connection.
241 /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
242 /// many routing-relevant features are present in the init context.
243 pub features: InitFeatures,
244 /// The value, in satoshis, that must always be held in the channel for our counterparty. This
245 /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
246 /// claiming at least this value on chain.
247 ///
248 /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
249 ///
250 /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
251 pub unspendable_punishment_reserve: u64,
252 /// Information on the fees and requirements that the counterparty requires when forwarding
253 /// payments to us through this channel.
254 pub forwarding_info: Option<CounterpartyForwardingInfo>,
255 /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
256 /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
257 /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
258 pub outbound_htlc_minimum_msat: Option<u64>,
259 /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
260 pub outbound_htlc_maximum_msat: Option<u64>,
261}
262
263impl_writeable_tlv_based!(ChannelCounterparty, {
264 (2, node_id, required),
265 (4, features, required),
266 (6, unspendable_punishment_reserve, required),
267 (8, forwarding_info, option),
268 (9, outbound_htlc_minimum_msat, option),
269 (11, outbound_htlc_maximum_msat, option),
270});
271
272/// Details of a channel, as returned by [`ChannelManager::list_channels`] and [`ChannelManager::list_usable_channels`]
273///
274/// Balances of a channel are available through [`ChainMonitor::get_claimable_balances`] and
275/// [`ChannelMonitor::get_claimable_balances`], calculated with respect to the corresponding on-chain
276/// transactions.
277///
278/// When a channel is spliced, most fields continue to refer to the original pre-splice channel
279/// state until the splice transaction reaches sufficient confirmations to be locked (and we
280/// exchange `splice_locked` messages with our peer). See individual fields for details.
281///
282/// [`ChannelManager::list_channels`]: crate::ln::channelmanager::ChannelManager::list_channels
283/// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
284/// [`ChainMonitor::get_claimable_balances`]: crate::chain::chainmonitor::ChainMonitor::get_claimable_balances
285/// [`ChannelMonitor::get_claimable_balances`]: crate::chain::channelmonitor::ChannelMonitor::get_claimable_balances
286#[derive(Clone, Debug, PartialEq)]
287pub struct ChannelDetails {
288 /// The channel's ID (prior to initial channel setup this is a random 32 bytes, thereafter it is
289 /// derived from channel funding or key material).
290 ///
291 /// Note that this means this value is *not* persistent - it can change once during the
292 /// lifetime of the channel.
293 pub channel_id: ChannelId,
294 /// Parameters which apply to our counterparty. See individual fields for more information.
295 pub counterparty: ChannelCounterparty,
296 /// The Channel's funding transaction output, if we've negotiated the funding transaction with
297 /// our counterparty already.
298 ///
299 /// When a channel is spliced, this continues to refer to the original pre-splice channel
300 /// state until the splice transaction reaches sufficient confirmations to be locked (and we
301 /// exchange `splice_locked` messages with our peer).
302 pub funding_txo: Option<OutPoint>,
303 /// The features which this channel operates with. See individual features for more info.
304 ///
305 /// `None` until negotiation completes and the channel type is finalized.
306 ///
307 /// When a channel is spliced, this continues to refer to the original pre-splice channel
308 /// state until the splice transaction reaches sufficient confirmations to be locked (and we
309 /// exchange `splice_locked` messages with our peer).
310 pub channel_type: Option<ChannelTypeFeatures>,
311 /// The position of the funding transaction in the chain. None if the funding transaction has
312 /// not yet been confirmed and the channel fully opened.
313 ///
314 /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
315 /// payments instead of this. See [`get_inbound_payment_scid`].
316 ///
317 /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
318 /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
319 ///
320 /// When a channel is spliced, this continues to refer to the original pre-splice channel
321 /// state until the splice transaction reaches sufficient confirmations to be locked (and we
322 /// exchange `splice_locked` messages with our peer).
323 ///
324 /// [`inbound_scid_alias`]: Self::inbound_scid_alias
325 /// [`outbound_scid_alias`]: Self::outbound_scid_alias
326 /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
327 /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
328 /// [`confirmations_required`]: Self::confirmations_required
329 pub short_channel_id: Option<u64>,
330 /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
331 /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
332 /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
333 /// `Some(0)`).
334 ///
335 /// This will be `None` as long as the channel is not available for routing outbound payments.
336 ///
337 /// When a channel is spliced, this continues to refer to the original pre-splice channel
338 /// state until the splice transaction reaches sufficient confirmations to be locked (and we
339 /// exchange `splice_locked` messages with our peer).
340 ///
341 /// [`short_channel_id`]: Self::short_channel_id
342 /// [`confirmations_required`]: Self::confirmations_required
343 pub outbound_scid_alias: Option<u64>,
344 /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
345 /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
346 /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
347 /// when they see a payment to be routed to us.
348 ///
349 /// Our counterparty may choose to rotate this value at any time, though will always recognize
350 /// previous values for inbound payment forwarding.
351 ///
352 /// [`short_channel_id`]: Self::short_channel_id
353 pub inbound_scid_alias: Option<u64>,
354 /// The value, in satoshis, of this channel as appears in the funding output
355 ///
356 /// When a channel is spliced, this continues to refer to the original pre-splice channel
357 /// state until the splice transaction reaches sufficient confirmations to be locked (and we
358 /// exchange `splice_locked` messages with our peer).
359 pub channel_value_satoshis: u64,
360 /// The value, in satoshis, that must always be held in the channel for us. This value ensures
361 /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
362 /// this value on chain.
363 ///
364 /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
365 ///
366 /// This value will be `None` for outbound channels until the counterparty accepts the channel.
367 ///
368 /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
369 pub unspendable_punishment_reserve: Option<u64>,
370 /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
371 /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
372 /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
373 /// `user_channel_id` will be randomized for an inbound channel. This may be zero for objects
374 /// serialized with LDK versions prior to 0.0.113.
375 ///
376 /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
377 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
378 /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
379 pub user_channel_id: u128,
380 /// The currently negotiated fee rate denominated in satoshi per 1000 weight units,
381 /// which is applied to commitment and HTLC transactions.
382 ///
383 /// This value will be `None` for objects serialized with LDK versions prior to 0.0.115.
384 pub feerate_sat_per_1000_weight: Option<u32>,
385 /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
386 /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
387 /// available for inclusion in new outbound HTLCs). This further does not include any pending
388 /// outgoing HTLCs which are awaiting some other resolution to be sent.
389 ///
390 /// This value is not exact. Due to various in-flight changes, feerate changes, and our
391 /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
392 /// should be able to spend nearly this amount.
393 pub outbound_capacity_msat: u64,
394 /// The available outbound capacity for sending a single HTLC to the remote peer. This is
395 /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
396 /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
397 /// to use a limit as close as possible to the HTLC limit we can currently send.
398 ///
399 /// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`] and
400 /// [`ChannelDetails::outbound_capacity_msat`].
401 pub next_outbound_htlc_limit_msat: u64,
402 /// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of
403 /// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than
404 /// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a
405 /// route which is valid.
406 pub next_outbound_htlc_minimum_msat: u64,
407 /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
408 /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
409 /// available for inclusion in new inbound HTLCs).
410 /// Note that there are some corner cases not fully handled here, so the actual available
411 /// inbound capacity may be slightly higher than this.
412 ///
413 /// This value is not exact. Due to various in-flight changes, feerate changes, and our
414 /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
415 /// However, our counterparty should be able to spend nearly this amount.
416 pub inbound_capacity_msat: u64,
417 /// The number of required confirmations on the funding transaction before the funding will be
418 /// considered "locked". This number is selected by the channel fundee (i.e. us if
419 /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
420 /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
421 /// [`ChannelHandshakeLimits::max_minimum_depth`].
422 ///
423 /// This value will be `None` for outbound channels until the counterparty accepts the channel.
424 ///
425 /// [`is_outbound`]: ChannelDetails::is_outbound
426 /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
427 /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
428 pub confirmations_required: Option<u32>,
429 /// The current number of confirmations on the funding transaction.
430 ///
431 /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
432 pub confirmations: Option<u32>,
433 /// The number of blocks (after our commitment transaction confirms) that we will need to wait
434 /// until we can claim our funds after we force-close the channel. During this time our
435 /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
436 /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
437 /// time to claim our non-HTLC-encumbered funds.
438 ///
439 /// This value will be `None` for outbound channels until the counterparty accepts the channel.
440 pub force_close_spend_delay: Option<u16>,
441 /// True if the channel was initiated (and thus funded) by us.
442 pub is_outbound: bool,
443 /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
444 /// channel is not currently being shut down. `channel_ready` message exchange implies the
445 /// required confirmation count has been reached (and we were connected to the peer at some
446 /// point after the funding transaction received enough confirmations). The required
447 /// confirmation count is provided in [`confirmations_required`].
448 ///
449 /// [`confirmations_required`]: ChannelDetails::confirmations_required
450 pub is_channel_ready: bool,
451 /// The stage of the channel's shutdown.
452 /// `None` for `ChannelDetails` serialized on LDK versions prior to 0.0.116.
453 pub channel_shutdown_state: Option<ChannelShutdownState>,
454 /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
455 /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
456 ///
457 /// This is a strict superset of `is_channel_ready`.
458 pub is_usable: bool,
459 /// True if this channel is (or will be) publicly-announced.
460 pub is_announced: bool,
461 /// The smallest value HTLC (in msat) we will accept, for this channel. This field
462 /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
463 pub inbound_htlc_minimum_msat: Option<u64>,
464 /// The largest value HTLC (in msat) we currently will accept, for this channel.
465 pub inbound_htlc_maximum_msat: Option<u64>,
466 /// Set of configurable parameters that affect channel operation.
467 ///
468 /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
469 pub config: Option<ChannelConfig>,
470 /// Pending inbound HTLCs.
471 ///
472 /// This field is empty for objects serialized with LDK versions prior to 0.0.122.
473 pub pending_inbound_htlcs: Vec<InboundHTLCDetails>,
474 /// Pending outbound HTLCs.
475 ///
476 /// This field is empty for objects serialized with LDK versions prior to 0.0.122.
477 pub pending_outbound_htlcs: Vec<OutboundHTLCDetails>,
478 /// The witness script that is used to lock the channel's funding output to commitment
479 /// transactions.
480 ///
481 /// When a channel is spliced, this continues to refer to the original funding output (which
482 /// was spent by the splice transaction) until the splice transaction reached sufficient
483 /// confirmations to be locked (and we exchange `splice_locked` messages with our peer).
484 ///
485 /// This field will be `None` for objects serialized with LDK versions prior to 0.2.0.
486 pub funding_redeem_script: Option<bitcoin::ScriptBuf>,
487}
488
489impl ChannelDetails {
490 /// Gets the current SCID which should be used to identify this channel for inbound payments.
491 /// This should be used for providing invoice hints or in any other context where our
492 /// counterparty will forward a payment to us.
493 ///
494 /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
495 /// [`ChannelDetails::short_channel_id`]. See those for more information.
496 pub fn get_inbound_payment_scid(&self) -> Option<u64> {
497 self.inbound_scid_alias.or(self.short_channel_id)
498 }
499
500 /// Gets the current SCID which should be used to identify this channel for outbound payments.
501 /// This should be used in [`Route`]s to describe the first hop or in other contexts where
502 /// we're sending or forwarding a payment outbound over this channel.
503 ///
504 /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
505 /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
506 ///
507 /// [`Route`]: crate::routing::router::Route
508 pub fn get_outbound_payment_scid(&self) -> Option<u64> {
509 self.short_channel_id.or(self.outbound_scid_alias)
510 }
511
512 /// Gets the funding output for this channel, if available.
513 ///
514 /// When a channel is spliced, this continues to refer to the original funding output (which
515 /// was spent by the splice transaction) until the splice transaction reaches sufficient
516 /// confirmations to be locked (and we exchange `splice_locked` messages with our peer).
517 pub fn get_funding_output(&self) -> Option<bitcoin::TxOut> {
518 match self.funding_redeem_script.as_ref() {
519 None => None,
520 Some(redeem_script) => Some(bitcoin::TxOut {
521 value: bitcoin::Amount::from_sat(self.channel_value_satoshis),
522 script_pubkey: redeem_script.to_p2wsh(),
523 }),
524 }
525 }
526
527 pub(super) fn from_channel<SP: Deref, F: Deref>(
528 channel: &Channel<SP>, best_block_height: u32, latest_features: InitFeatures,
529 fee_estimator: &LowerBoundedFeeEstimator<F>,
530 ) -> Self
531 where
532 SP::Target: SignerProvider,
533 F::Target: FeeEstimator,
534 {
535 let context = channel.context();
536 let funding = channel.funding();
537 let balance = channel.get_available_balances(fee_estimator);
538 let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
539 funding.get_holder_counterparty_selected_channel_reserve_satoshis();
540 #[allow(deprecated)] // TODO: Remove once balance_msat is removed.
541 ChannelDetails {
542 channel_id: context.channel_id(),
543 counterparty: ChannelCounterparty {
544 node_id: context.get_counterparty_node_id(),
545 features: latest_features,
546 unspendable_punishment_reserve: to_remote_reserve_satoshis,
547 forwarding_info: context.counterparty_forwarding_info(),
548 // Ensures that we have actually received the `htlc_minimum_msat` value
549 // from the counterparty through the `OpenChannel` or `AcceptChannel`
550 // message (as they are always the first message from the counterparty).
551 // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
552 // default `0` value set by `Channel::new_outbound`.
553 outbound_htlc_minimum_msat: if context.have_received_message() {
554 Some(context.get_counterparty_htlc_minimum_msat())
555 } else {
556 None
557 },
558 outbound_htlc_maximum_msat: context.get_counterparty_htlc_maximum_msat(funding),
559 },
560 funding_txo: funding.get_funding_txo(),
561 funding_redeem_script: funding
562 .channel_transaction_parameters
563 .make_funding_redeemscript_opt(),
564 // Note that accept_channel (or open_channel) is always the first message, so
565 // `have_received_message` indicates that type negotiation has completed.
566 channel_type: if context.have_received_message() {
567 Some(funding.get_channel_type().clone())
568 } else {
569 None
570 },
571 short_channel_id: funding.get_short_channel_id(),
572 outbound_scid_alias: if context.is_usable() {
573 Some(context.outbound_scid_alias())
574 } else {
575 None
576 },
577 inbound_scid_alias: context.latest_inbound_scid_alias(),
578 channel_value_satoshis: funding.get_value_satoshis(),
579 feerate_sat_per_1000_weight: Some(context.get_feerate_sat_per_1000_weight()),
580 unspendable_punishment_reserve: to_self_reserve_satoshis,
581 inbound_capacity_msat: balance.inbound_capacity_msat,
582 outbound_capacity_msat: balance.outbound_capacity_msat,
583 next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
584 next_outbound_htlc_minimum_msat: balance.next_outbound_htlc_minimum_msat,
585 user_channel_id: context.get_user_id(),
586 confirmations_required: channel.minimum_depth(),
587 confirmations: Some(funding.get_funding_tx_confirmations(best_block_height)),
588 force_close_spend_delay: funding.get_counterparty_selected_contest_delay(),
589 is_outbound: funding.is_outbound(),
590 is_channel_ready: context.is_usable(),
591 is_usable: context.is_live(),
592 is_announced: context.should_announce(),
593 inbound_htlc_minimum_msat: Some(context.get_holder_htlc_minimum_msat()),
594 inbound_htlc_maximum_msat: context.get_holder_htlc_maximum_msat(funding),
595 config: Some(context.config()),
596 channel_shutdown_state: Some(context.shutdown_state()),
597 pending_inbound_htlcs: context.get_pending_inbound_htlc_details(funding),
598 pending_outbound_htlcs: context.get_pending_outbound_htlc_details(funding),
599 }
600 }
601}
602
603impl_writeable_tlv_based!(ChannelDetails, {
604 (1, inbound_scid_alias, option),
605 (2, channel_id, required),
606 (3, channel_type, option),
607 (4, counterparty, required),
608 (5, outbound_scid_alias, option),
609 (6, funding_txo, option),
610 (7, config, option),
611 (8, short_channel_id, option),
612 (9, confirmations, option),
613 (10, channel_value_satoshis, required),
614 (12, unspendable_punishment_reserve, option),
615 // Note that _user_channel_id_low is used below, but rustc warns anyway
616 (14, _user_channel_id_low, (legacy, u64,
617 |us: &ChannelDetails| Some(us.user_channel_id as u64))),
618 (16, _balance_msat, (legacy, u64, |us: &ChannelDetails| Some(us.next_outbound_htlc_limit_msat))),
619 (18, outbound_capacity_msat, required),
620 (19, next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat)),
621 (20, inbound_capacity_msat, required),
622 (21, next_outbound_htlc_minimum_msat, (default_value, 0)),
623 (22, confirmations_required, option),
624 (24, force_close_spend_delay, option),
625 (26, is_outbound, required),
626 (28, is_channel_ready, required),
627 (30, is_usable, required),
628 (32, is_announced, required),
629 (33, inbound_htlc_minimum_msat, option),
630 (35, inbound_htlc_maximum_msat, option),
631 // Note that _user_channel_id_high is used below, but rustc warns anyway
632 (37, _user_channel_id_high, (legacy, u64,
633 |us: &ChannelDetails| Some((us.user_channel_id >> 64) as u64))),
634 (39, feerate_sat_per_1000_weight, option),
635 (41, channel_shutdown_state, option),
636 (43, pending_inbound_htlcs, optional_vec),
637 (45, pending_outbound_htlcs, optional_vec),
638 (47, funding_redeem_script, option),
639 (_unused, user_channel_id, (static_value,
640 _user_channel_id_low.unwrap_or(0) as u128 | ((_user_channel_id_high.unwrap_or(0) as u128) << 64)
641 )),
642});
643
644#[derive(Clone, Copy, Debug, PartialEq, Eq)]
645/// Further information on the details of the channel shutdown.
646/// Upon channels being forced closed (i.e. commitment transaction confirmation detected
647/// by `ChainMonitor`), ChannelShutdownState will be set to `ShutdownComplete` or
648/// the channel will be removed shortly.
649/// Also note, that in normal operation, peers could disconnect at any of these states
650/// and require peer re-connection before making progress onto other states
651pub enum ChannelShutdownState {
652 /// Channel has not sent or received a shutdown message.
653 NotShuttingDown,
654 /// Local node has sent a shutdown message for this channel.
655 ShutdownInitiated,
656 /// Shutdown message exchanges have concluded and the channels are in the midst of
657 /// resolving all existing open HTLCs before closing can continue.
658 ResolvingHTLCs,
659 /// All HTLCs have been resolved, nodes are currently negotiating channel close onchain fee rates.
660 NegotiatingClosingFee,
661 /// We've successfully negotiated a closing_signed dance. At this point `ChannelManager` is about
662 /// to drop the channel.
663 ShutdownComplete,
664}
665
666impl_writeable_tlv_based_enum!(ChannelShutdownState,
667 (0, NotShuttingDown) => {},
668 (2, ShutdownInitiated) => {},
669 (4, ResolvingHTLCs) => {},
670 (6, NegotiatingClosingFee) => {},
671 (8, ShutdownComplete) => {},
672);
673
674#[cfg(test)]
675mod tests {
676 use bitcoin::{hashes::Hash as _, secp256k1::PublicKey};
677 use lightning_types::features::Features;
678 use types::payment::PaymentHash;
679
680 use crate::{
681 chain::transaction::OutPoint,
682 ln::{
683 chan_utils::make_funding_redeemscript,
684 channel_state::{
685 InboundHTLCDetails, InboundHTLCStateDetails, OutboundHTLCDetails,
686 OutboundHTLCStateDetails,
687 },
688 types::ChannelId,
689 },
690 util::{
691 config::ChannelConfig,
692 ser::{Readable, Writeable},
693 },
694 };
695
696 use super::{ChannelCounterparty, ChannelDetails, ChannelShutdownState};
697
698 #[test]
699 fn test_channel_details_serialization() {
700 #[allow(deprecated)]
701 let channel_details = ChannelDetails {
702 channel_id: ChannelId::new_zero(),
703 counterparty: ChannelCounterparty {
704 features: Features::empty(),
705 node_id: PublicKey::from_slice(&[2; 33]).unwrap(),
706 unspendable_punishment_reserve: 1983,
707 forwarding_info: None,
708 outbound_htlc_minimum_msat: None,
709 outbound_htlc_maximum_msat: None,
710 },
711 funding_txo: Some(OutPoint {
712 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(),
713 index: 1,
714 }),
715 funding_redeem_script: Some(make_funding_redeemscript(
716 &PublicKey::from_slice(&[2; 33]).unwrap(),
717 &PublicKey::from_slice(&[2; 33]).unwrap(),
718 )),
719 channel_type: None,
720 short_channel_id: None,
721 outbound_scid_alias: None,
722 inbound_scid_alias: None,
723 channel_value_satoshis: 50_100,
724 user_channel_id: (u64::MAX as u128) + 1, // Gets us into the high bytes
725 outbound_capacity_msat: 24_300,
726 next_outbound_htlc_limit_msat: 20_000,
727 next_outbound_htlc_minimum_msat: 132,
728 inbound_capacity_msat: 42,
729 unspendable_punishment_reserve: Some(8273),
730 confirmations_required: Some(5),
731 confirmations: Some(73),
732 force_close_spend_delay: Some(10),
733 is_outbound: true,
734 is_channel_ready: false,
735 is_usable: true,
736 is_announced: false,
737 inbound_htlc_minimum_msat: Some(98),
738 inbound_htlc_maximum_msat: Some(983274),
739 config: Some(ChannelConfig::default()),
740 feerate_sat_per_1000_weight: Some(212),
741 channel_shutdown_state: Some(ChannelShutdownState::NotShuttingDown),
742 pending_inbound_htlcs: vec![InboundHTLCDetails {
743 htlc_id: 12,
744 amount_msat: 333,
745 cltv_expiry: 127,
746 payment_hash: PaymentHash([3; 32]),
747 state: Some(InboundHTLCStateDetails::AwaitingRemoteRevokeToAdd),
748 is_dust: true,
749 }],
750 pending_outbound_htlcs: vec![OutboundHTLCDetails {
751 htlc_id: Some(81),
752 amount_msat: 5000,
753 cltv_expiry: 129,
754 payment_hash: PaymentHash([4; 32]),
755 state: Some(OutboundHTLCStateDetails::AwaitingRemoteRevokeToAdd),
756 skimmed_fee_msat: Some(42),
757 is_dust: false,
758 }],
759 };
760 let mut buffer = Vec::new();
761 channel_details.write(&mut buffer).unwrap();
762 let deser_channel_details = ChannelDetails::read(&mut buffer.as_slice()).unwrap();
763
764 assert_eq!(deser_channel_details, channel_details);
765 }
766}