776e742f3fecabb2e76ca982051238e21e6059a7
[rust-lightning] / lightning / src / 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
12 use alloc::vec::Vec;
13
14 use bitcoin::secp256k1::PublicKey;
15
16 use crate::chain::chaininterface::{FeeEstimator, LowerBoundedFeeEstimator};
17 use crate::chain::transaction::OutPoint;
18 use crate::ln::channel::ChannelContext;
19 use crate::ln::features::{ChannelTypeFeatures, InitFeatures};
20 use crate::ln::types::{ChannelId, PaymentHash};
21 use crate::sign::SignerProvider;
22 use crate::util::config::ChannelConfig;
23
24 use core::ops::Deref;
25
26 /// Exposes the state of pending inbound HTLCs.
27 ///
28 /// At a high level, an HTLC being forwarded from one Lightning node to another Lightning node goes
29 /// through the following states in the state machine:
30 /// - Announced for addition by the originating node through the update_add_htlc message.
31 /// - Added to the commitment transaction of the receiving node and originating node in turn
32 ///   through the exchange of commitment_signed and revoke_and_ack messages.
33 /// - Announced for resolution (fulfillment or failure) by the receiving node through either one of
34 ///   the update_fulfill_htlc, update_fail_htlc, and update_fail_malformed_htlc messages.
35 /// - Removed from the commitment transaction of the originating node and receiving node in turn
36 ///   through the exchange of commitment_signed and revoke_and_ack messages.
37 ///
38 /// This can be used to inspect what next message an HTLC is waiting for to advance its state.
39 #[derive(Clone, Debug, PartialEq)]
40 pub enum InboundHTLCStateDetails {
41         /// We have added this HTLC in our commitment transaction by receiving commitment_signed and
42         /// returning revoke_and_ack. We are awaiting the appropriate revoke_and_ack's from the remote
43         /// before this HTLC is included on the remote commitment transaction.
44         AwaitingRemoteRevokeToAdd,
45         /// This HTLC has been included in the commitment_signed and revoke_and_ack messages on both sides
46         /// and is included in both commitment transactions.
47         ///
48         /// This HTLC is now safe to either forward or be claimed as a payment by us. The HTLC will
49         /// remain in this state until the forwarded upstream HTLC has been resolved and we resolve this
50         /// HTLC correspondingly, or until we claim it as a payment. If it is part of a multipart
51         /// payment, it will only be claimed together with other required parts.
52         Committed,
53         /// We have received the preimage for this HTLC and it is being removed by fulfilling it with
54         /// update_fulfill_htlc. This HTLC is still on both commitment transactions, but we are awaiting
55         /// the appropriate revoke_and_ack's from the remote before this HTLC is removed from the remote
56         /// commitment transaction after update_fulfill_htlc.
57         AwaitingRemoteRevokeToRemoveFulfill,
58         /// The HTLC is being removed by failing it with update_fail_htlc or update_fail_malformed_htlc.
59         /// This HTLC is still on both commitment transactions, but we are awaiting the appropriate
60         /// revoke_and_ack's from the remote before this HTLC is removed from the remote commitment
61         /// transaction.
62         AwaitingRemoteRevokeToRemoveFail,
63 }
64
65 impl_writeable_tlv_based_enum_upgradable!(InboundHTLCStateDetails,
66         (0, AwaitingRemoteRevokeToAdd) => {},
67         (2, Committed) => {},
68         (4, AwaitingRemoteRevokeToRemoveFulfill) => {},
69         (6, AwaitingRemoteRevokeToRemoveFail) => {};
70 );
71
72 /// Exposes details around pending inbound HTLCs.
73 #[derive(Clone, Debug, PartialEq)]
74 pub struct InboundHTLCDetails {
75         /// The HTLC ID.
76         /// The IDs are incremented by 1 starting from 0 for each offered HTLC.
77         /// They are unique per channel and inbound/outbound direction, unless an HTLC was only announced
78         /// and not part of any commitment transaction.
79         pub htlc_id: u64,
80         /// The amount in msat.
81         pub amount_msat: u64,
82         /// The block height at which this HTLC expires.
83         pub cltv_expiry: u32,
84         /// The payment hash.
85         pub payment_hash: PaymentHash,
86         /// The state of the HTLC in the state machine.
87         ///
88         /// Determines on which commitment transactions the HTLC is included and what message the HTLC is
89         /// waiting for to advance to the next state.
90         ///
91         /// See [`InboundHTLCStateDetails`] for information on the specific states.
92         ///
93         /// LDK will always fill this field in, but when downgrading to prior versions of LDK, new
94         /// states may result in `None` here.
95         pub state: Option<InboundHTLCStateDetails>,
96         /// Whether the HTLC has an output below the local dust limit. If so, the output will be trimmed
97         /// from the local commitment transaction and added to the commitment transaction fee.
98         /// For non-anchor channels, this takes into account the cost of the second-stage HTLC
99         /// transactions as well.
100         ///
101         /// When the local commitment transaction is broadcasted as part of a unilateral closure,
102         /// the value of this HTLC will therefore not be claimable but instead burned as a transaction
103         /// fee.
104         ///
105         /// Note that dust limits are specific to each party. An HTLC can be dust for the local
106         /// commitment transaction but not for the counterparty's commitment transaction and vice versa.
107         pub is_dust: bool,
108 }
109
110 impl_writeable_tlv_based!(InboundHTLCDetails, {
111         (0, htlc_id, required),
112         (2, amount_msat, required),
113         (4, cltv_expiry, required),
114         (6, payment_hash, required),
115         (7, state, upgradable_option),
116         (8, is_dust, required),
117 });
118
119 /// Exposes the state of pending outbound HTLCs.
120 ///
121 /// At a high level, an HTLC being forwarded from one Lightning node to another Lightning node goes
122 /// through the following states in the state machine:
123 /// - Announced for addition by the originating node through the update_add_htlc message.
124 /// - Added to the commitment transaction of the receiving node and originating node in turn
125 ///   through the exchange of commitment_signed and revoke_and_ack messages.
126 /// - Announced for resolution (fulfillment or failure) by the receiving node through either one of
127 ///   the update_fulfill_htlc, update_fail_htlc, and update_fail_malformed_htlc messages.
128 /// - Removed from the commitment transaction of the originating node and receiving node in turn
129 ///   through the exchange of commitment_signed and revoke_and_ack messages.
130 ///
131 /// This can be used to inspect what next message an HTLC is waiting for to advance its state.
132 #[derive(Clone, Debug, PartialEq)]
133 pub enum OutboundHTLCStateDetails {
134         /// We are awaiting the appropriate revoke_and_ack's from the remote before the HTLC is added
135         /// on the remote's commitment transaction after update_add_htlc.
136         AwaitingRemoteRevokeToAdd,
137         /// The HTLC has been added to the remote's commitment transaction by sending commitment_signed
138         /// and receiving revoke_and_ack in return.
139         ///
140         /// The HTLC will remain in this state until the remote node resolves the HTLC, or until we
141         /// unilaterally close the channel due to a timeout with an uncooperative remote node.
142         Committed,
143         /// The HTLC has been fulfilled successfully by the remote with a preimage in update_fulfill_htlc,
144         /// and we removed the HTLC from our commitment transaction by receiving commitment_signed and
145         /// returning revoke_and_ack. We are awaiting the appropriate revoke_and_ack's from the remote
146         /// for the removal from its commitment transaction.
147         AwaitingRemoteRevokeToRemoveSuccess,
148         /// The HTLC has been failed by the remote with update_fail_htlc or update_fail_malformed_htlc,
149         /// and we removed the HTLC from our commitment transaction by receiving commitment_signed and
150         /// returning revoke_and_ack. We are awaiting the appropriate revoke_and_ack's from the remote
151         /// for the removal from its commitment transaction.
152         AwaitingRemoteRevokeToRemoveFailure,
153 }
154
155 impl_writeable_tlv_based_enum_upgradable!(OutboundHTLCStateDetails,
156         (0, AwaitingRemoteRevokeToAdd) => {},
157         (2, Committed) => {},
158         (4, AwaitingRemoteRevokeToRemoveSuccess) => {},
159         (6, AwaitingRemoteRevokeToRemoveFailure) => {};
160 );
161
162 /// Exposes details around pending outbound HTLCs.
163 #[derive(Clone, Debug, PartialEq)]
164 pub struct OutboundHTLCDetails {
165         /// The HTLC ID.
166         /// The IDs are incremented by 1 starting from 0 for each offered HTLC.
167         /// They are unique per channel and inbound/outbound direction, unless an HTLC was only announced
168         /// and not part of any commitment transaction.
169         ///
170         /// Not present when we are awaiting a remote revocation and the HTLC is not added yet.
171         pub htlc_id: Option<u64>,
172         /// The amount in msat.
173         pub amount_msat: u64,
174         /// The block height at which this HTLC expires.
175         pub cltv_expiry: u32,
176         /// The payment hash.
177         pub payment_hash: PaymentHash,
178         /// The state of the HTLC in the state machine.
179         ///
180         /// Determines on which commitment transactions the HTLC is included and what message the HTLC is
181         /// waiting for to advance to the next state.
182         ///
183         /// See [`OutboundHTLCStateDetails`] for information on the specific states.
184         ///
185         /// LDK will always fill this field in, but when downgrading to prior versions of LDK, new
186         /// states may result in `None` here.
187         pub state: Option<OutboundHTLCStateDetails>,
188         /// The extra fee being skimmed off the top of this HTLC.
189         pub skimmed_fee_msat: Option<u64>,
190         /// Whether the HTLC has an output below the local dust limit. If so, the output will be trimmed
191         /// from the local commitment transaction and added to the commitment transaction fee.
192         /// For non-anchor channels, this takes into account the cost of the second-stage HTLC
193         /// transactions as well.
194         ///
195         /// When the local commitment transaction is broadcasted as part of a unilateral closure,
196         /// the value of this HTLC will therefore not be claimable but instead burned as a transaction
197         /// fee.
198         ///
199         /// Note that dust limits are specific to each party. An HTLC can be dust for the local
200         /// commitment transaction but not for the counterparty's commitment transaction and vice versa.
201         pub is_dust: bool,
202 }
203
204 impl_writeable_tlv_based!(OutboundHTLCDetails, {
205         (0, htlc_id, required),
206         (2, amount_msat, required),
207         (4, cltv_expiry, required),
208         (6, payment_hash, required),
209         (7, state, upgradable_option),
210         (8, skimmed_fee_msat, required),
211         (10, is_dust, required),
212 });
213
214 /// Information needed for constructing an invoice route hint for this channel.
215 #[derive(Clone, Debug, PartialEq)]
216 pub struct CounterpartyForwardingInfo {
217         /// Base routing fee in millisatoshis.
218         pub fee_base_msat: u32,
219         /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
220         pub fee_proportional_millionths: u32,
221         /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
222         /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
223         /// `cltv_expiry_delta` for more details.
224         pub cltv_expiry_delta: u16,
225 }
226
227 /// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
228 /// to better separate parameters.
229 #[derive(Clone, Debug, PartialEq)]
230 pub struct ChannelCounterparty {
231         /// The node_id of our counterparty
232         pub node_id: PublicKey,
233         /// The Features the channel counterparty provided upon last connection.
234         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
235         /// many routing-relevant features are present in the init context.
236         pub features: InitFeatures,
237         /// The value, in satoshis, that must always be held in the channel for our counterparty. This
238         /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
239         /// claiming at least this value on chain.
240         ///
241         /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
242         ///
243         /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
244         pub unspendable_punishment_reserve: u64,
245         /// Information on the fees and requirements that the counterparty requires when forwarding
246         /// payments to us through this channel.
247         pub forwarding_info: Option<CounterpartyForwardingInfo>,
248         /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
249         /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
250         /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
251         pub outbound_htlc_minimum_msat: Option<u64>,
252         /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
253         pub outbound_htlc_maximum_msat: Option<u64>,
254 }
255
256 /// Details of a channel, as returned by [`ChannelManager::list_channels`] and [`ChannelManager::list_usable_channels`]
257 ///
258 /// [`ChannelManager::list_channels`]: crate::ln::channelmanager::ChannelManager::list_channels
259 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
260 #[derive(Clone, Debug, PartialEq)]
261 pub struct ChannelDetails {
262         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
263         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
264         /// Note that this means this value is *not* persistent - it can change once during the
265         /// lifetime of the channel.
266         pub channel_id: ChannelId,
267         /// Parameters which apply to our counterparty. See individual fields for more information.
268         pub counterparty: ChannelCounterparty,
269         /// The Channel's funding transaction output, if we've negotiated the funding transaction with
270         /// our counterparty already.
271         pub funding_txo: Option<OutPoint>,
272         /// The features which this channel operates with. See individual features for more info.
273         ///
274         /// `None` until negotiation completes and the channel type is finalized.
275         pub channel_type: Option<ChannelTypeFeatures>,
276         /// The position of the funding transaction in the chain. None if the funding transaction has
277         /// not yet been confirmed and the channel fully opened.
278         ///
279         /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
280         /// payments instead of this. See [`get_inbound_payment_scid`].
281         ///
282         /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
283         /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
284         ///
285         /// [`inbound_scid_alias`]: Self::inbound_scid_alias
286         /// [`outbound_scid_alias`]: Self::outbound_scid_alias
287         /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
288         /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
289         /// [`confirmations_required`]: Self::confirmations_required
290         pub short_channel_id: Option<u64>,
291         /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
292         /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
293         /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
294         /// `Some(0)`).
295         ///
296         /// This will be `None` as long as the channel is not available for routing outbound payments.
297         ///
298         /// [`short_channel_id`]: Self::short_channel_id
299         /// [`confirmations_required`]: Self::confirmations_required
300         pub outbound_scid_alias: Option<u64>,
301         /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
302         /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
303         /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
304         /// when they see a payment to be routed to us.
305         ///
306         /// Our counterparty may choose to rotate this value at any time, though will always recognize
307         /// previous values for inbound payment forwarding.
308         ///
309         /// [`short_channel_id`]: Self::short_channel_id
310         pub inbound_scid_alias: Option<u64>,
311         /// The value, in satoshis, of this channel as appears in the funding output
312         pub channel_value_satoshis: u64,
313         /// The value, in satoshis, that must always be held in the channel for us. This value ensures
314         /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
315         /// this value on chain.
316         ///
317         /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
318         ///
319         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
320         ///
321         /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
322         pub unspendable_punishment_reserve: Option<u64>,
323         /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
324         /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
325         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
326         /// `user_channel_id` will be randomized for an inbound channel.  This may be zero for objects
327         /// serialized with LDK versions prior to 0.0.113.
328         ///
329         /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
330         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
331         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
332         pub user_channel_id: u128,
333         /// The currently negotiated fee rate denominated in satoshi per 1000 weight units,
334         /// which is applied to commitment and HTLC transactions.
335         ///
336         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.115.
337         pub feerate_sat_per_1000_weight: Option<u32>,
338         /// Our total balance.  This is the amount we would get if we close the channel.
339         /// This value is not exact. Due to various in-flight changes and feerate changes, exactly this
340         /// amount is not likely to be recoverable on close.
341         ///
342         /// This does not include any pending HTLCs which are not yet fully resolved (and, thus, whose
343         /// balance is not available for inclusion in new outbound HTLCs). This further does not include
344         /// any pending outgoing HTLCs which are awaiting some other resolution to be sent.
345         /// This does not consider any on-chain fees.
346         ///
347         /// See also [`ChannelDetails::outbound_capacity_msat`]
348         pub balance_msat: u64,
349         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
350         /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
351         /// available for inclusion in new outbound HTLCs). This further does not include any pending
352         /// outgoing HTLCs which are awaiting some other resolution to be sent.
353         ///
354         /// See also [`ChannelDetails::balance_msat`]
355         ///
356         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
357         /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
358         /// should be able to spend nearly this amount.
359         pub outbound_capacity_msat: u64,
360         /// The available outbound capacity for sending a single HTLC to the remote peer. This is
361         /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
362         /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
363         /// to use a limit as close as possible to the HTLC limit we can currently send.
364         ///
365         /// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`],
366         /// [`ChannelDetails::balance_msat`], and [`ChannelDetails::outbound_capacity_msat`].
367         pub next_outbound_htlc_limit_msat: u64,
368         /// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of
369         /// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than
370         /// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a
371         /// route which is valid.
372         pub next_outbound_htlc_minimum_msat: u64,
373         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
374         /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
375         /// available for inclusion in new inbound HTLCs).
376         /// Note that there are some corner cases not fully handled here, so the actual available
377         /// inbound capacity may be slightly higher than this.
378         ///
379         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
380         /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
381         /// However, our counterparty should be able to spend nearly this amount.
382         pub inbound_capacity_msat: u64,
383         /// The number of required confirmations on the funding transaction before the funding will be
384         /// considered "locked". This number is selected by the channel fundee (i.e. us if
385         /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
386         /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
387         /// [`ChannelHandshakeLimits::max_minimum_depth`].
388         ///
389         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
390         ///
391         /// [`is_outbound`]: ChannelDetails::is_outbound
392         /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
393         /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
394         pub confirmations_required: Option<u32>,
395         /// The current number of confirmations on the funding transaction.
396         ///
397         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
398         pub confirmations: Option<u32>,
399         /// The number of blocks (after our commitment transaction confirms) that we will need to wait
400         /// until we can claim our funds after we force-close the channel. During this time our
401         /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
402         /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
403         /// time to claim our non-HTLC-encumbered funds.
404         ///
405         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
406         pub force_close_spend_delay: Option<u16>,
407         /// True if the channel was initiated (and thus funded) by us.
408         pub is_outbound: bool,
409         /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
410         /// channel is not currently being shut down. `channel_ready` message exchange implies the
411         /// required confirmation count has been reached (and we were connected to the peer at some
412         /// point after the funding transaction received enough confirmations). The required
413         /// confirmation count is provided in [`confirmations_required`].
414         ///
415         /// [`confirmations_required`]: ChannelDetails::confirmations_required
416         pub is_channel_ready: bool,
417         /// The stage of the channel's shutdown.
418         /// `None` for `ChannelDetails` serialized on LDK versions prior to 0.0.116.
419         pub channel_shutdown_state: Option<ChannelShutdownState>,
420         /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
421         /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
422         ///
423         /// This is a strict superset of `is_channel_ready`.
424         pub is_usable: bool,
425         /// True if this channel is (or will be) publicly-announced.
426         pub is_public: bool,
427         /// The smallest value HTLC (in msat) we will accept, for this channel. This field
428         /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
429         pub inbound_htlc_minimum_msat: Option<u64>,
430         /// The largest value HTLC (in msat) we currently will accept, for this channel.
431         pub inbound_htlc_maximum_msat: Option<u64>,
432         /// Set of configurable parameters that affect channel operation.
433         ///
434         /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
435         pub config: Option<ChannelConfig>,
436         /// Pending inbound HTLCs.
437         ///
438         /// This field is empty for objects serialized with LDK versions prior to 0.0.122.
439         pub pending_inbound_htlcs: Vec<InboundHTLCDetails>,
440         /// Pending outbound HTLCs.
441         ///
442         /// This field is empty for objects serialized with LDK versions prior to 0.0.122.
443         pub pending_outbound_htlcs: Vec<OutboundHTLCDetails>,
444 }
445
446 impl ChannelDetails {
447         /// Gets the current SCID which should be used to identify this channel for inbound payments.
448         /// This should be used for providing invoice hints or in any other context where our
449         /// counterparty will forward a payment to us.
450         ///
451         /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
452         /// [`ChannelDetails::short_channel_id`]. See those for more information.
453         pub fn get_inbound_payment_scid(&self) -> Option<u64> {
454                 self.inbound_scid_alias.or(self.short_channel_id)
455         }
456
457         /// Gets the current SCID which should be used to identify this channel for outbound payments.
458         /// This should be used in [`Route`]s to describe the first hop or in other contexts where
459         /// we're sending or forwarding a payment outbound over this channel.
460         ///
461         /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
462         /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
463         ///
464         /// [`Route`]: crate::routing::router::Route
465         pub fn get_outbound_payment_scid(&self) -> Option<u64> {
466                 self.short_channel_id.or(self.outbound_scid_alias)
467         }
468
469         pub(super) fn from_channel_context<SP: Deref, F: Deref>(
470                 context: &ChannelContext<SP>, best_block_height: u32, latest_features: InitFeatures,
471                 fee_estimator: &LowerBoundedFeeEstimator<F>
472         ) -> Self
473         where
474                 SP::Target: SignerProvider,
475                 F::Target: FeeEstimator
476         {
477                 let balance = context.get_available_balances(fee_estimator);
478                 let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
479                         context.get_holder_counterparty_selected_channel_reserve_satoshis();
480                 ChannelDetails {
481                         channel_id: context.channel_id(),
482                         counterparty: ChannelCounterparty {
483                                 node_id: context.get_counterparty_node_id(),
484                                 features: latest_features,
485                                 unspendable_punishment_reserve: to_remote_reserve_satoshis,
486                                 forwarding_info: context.counterparty_forwarding_info(),
487                                 // Ensures that we have actually received the `htlc_minimum_msat` value
488                                 // from the counterparty through the `OpenChannel` or `AcceptChannel`
489                                 // message (as they are always the first message from the counterparty).
490                                 // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
491                                 // default `0` value set by `Channel::new_outbound`.
492                                 outbound_htlc_minimum_msat: if context.have_received_message() {
493                                         Some(context.get_counterparty_htlc_minimum_msat()) } else { None },
494                                 outbound_htlc_maximum_msat: context.get_counterparty_htlc_maximum_msat(),
495                         },
496                         funding_txo: context.get_funding_txo(),
497                         // Note that accept_channel (or open_channel) is always the first message, so
498                         // `have_received_message` indicates that type negotiation has completed.
499                         channel_type: if context.have_received_message() { Some(context.get_channel_type().clone()) } else { None },
500                         short_channel_id: context.get_short_channel_id(),
501                         outbound_scid_alias: if context.is_usable() { Some(context.outbound_scid_alias()) } else { None },
502                         inbound_scid_alias: context.latest_inbound_scid_alias(),
503                         channel_value_satoshis: context.get_value_satoshis(),
504                         feerate_sat_per_1000_weight: Some(context.get_feerate_sat_per_1000_weight()),
505                         unspendable_punishment_reserve: to_self_reserve_satoshis,
506                         balance_msat: balance.balance_msat,
507                         inbound_capacity_msat: balance.inbound_capacity_msat,
508                         outbound_capacity_msat: balance.outbound_capacity_msat,
509                         next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
510                         next_outbound_htlc_minimum_msat: balance.next_outbound_htlc_minimum_msat,
511                         user_channel_id: context.get_user_id(),
512                         confirmations_required: context.minimum_depth(),
513                         confirmations: Some(context.get_funding_tx_confirmations(best_block_height)),
514                         force_close_spend_delay: context.get_counterparty_selected_contest_delay(),
515                         is_outbound: context.is_outbound(),
516                         is_channel_ready: context.is_usable(),
517                         is_usable: context.is_live(),
518                         is_public: context.should_announce(),
519                         inbound_htlc_minimum_msat: Some(context.get_holder_htlc_minimum_msat()),
520                         inbound_htlc_maximum_msat: context.get_holder_htlc_maximum_msat(),
521                         config: Some(context.config()),
522                         channel_shutdown_state: Some(context.shutdown_state()),
523                         pending_inbound_htlcs: context.get_pending_inbound_htlc_details(),
524                         pending_outbound_htlcs: context.get_pending_outbound_htlc_details(),
525                 }
526         }
527 }
528
529 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
530 /// Further information on the details of the channel shutdown.
531 /// Upon channels being forced closed (i.e. commitment transaction confirmation detected
532 /// by `ChainMonitor`), ChannelShutdownState will be set to `ShutdownComplete` or
533 /// the channel will be removed shortly.
534 /// Also note, that in normal operation, peers could disconnect at any of these states
535 /// and require peer re-connection before making progress onto other states
536 pub enum ChannelShutdownState {
537         /// Channel has not sent or received a shutdown message.
538         NotShuttingDown,
539         /// Local node has sent a shutdown message for this channel.
540         ShutdownInitiated,
541         /// Shutdown message exchanges have concluded and the channels are in the midst of
542         /// resolving all existing open HTLCs before closing can continue.
543         ResolvingHTLCs,
544         /// All HTLCs have been resolved, nodes are currently negotiating channel close onchain fee rates.
545         NegotiatingClosingFee,
546         /// We've successfully negotiated a closing_signed dance. At this point `ChannelManager` is about
547         /// to drop the channel.
548         ShutdownComplete,
549 }