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