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