Skip to content

Conversation

@TheBlueMatt
Copy link
Collaborator

`Balance` seeks to expose our balance accurate based on what we
would get, less fees, if we were to force-close right now. This is
great, but for an end-user wallet its not really what you want to
display as the "balance" of the wallet.

Instead, you want to give a balance which matches the sum of HTLCs
received over time, which is only possible when balance information
is avilable which ignores things like dust, anchors, fees, and
reserve values.

Here we provide such a balance - a new "offchain balance" in
`HolderCommitmentTransactionBalance`.

Fixes #4241.

`Balance` seeks to expose our balance accurate based on what we
would get, less fees, if we were to force-close right now. This is
great, but for an end-user wallet its not really what you want to
display as the "balance" of the wallet.

Instead, you want to give a balance which matches the sum of HTLCs
received over time, which is only possible when balance information
is avilable which ignores things like dust, anchors, fees, and
reserve values.

Here we provide such a balance - a new "offchain balance" in
`HolderCommitmentTransactionBalance`.
@TheBlueMatt TheBlueMatt added this to the 0.3 milestone Dec 8, 2025
@ldk-reviews-bot
Copy link

ldk-reviews-bot commented Dec 8, 2025

I've assigned @joostjager as a reviewer!
I'll wait for their review and will help manage the review process.
Once they submit their review, I'll check if a second reviewer would be helpful.

@codecov
Copy link

codecov bot commented Dec 8, 2025

Codecov Report

❌ Patch coverage is 83.57143% with 23 lines in your changes missing coverage. Please review.
✅ Project coverage is 89.32%. Comparing base (fbf0c61) to head (4f1abd3).
⚠️ Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
lightning/src/chain/channelmonitor.rs 47.72% 23 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##             main    #4267    +/-   ##
========================================
  Coverage   89.32%   89.32%            
========================================
  Files         180      180            
  Lines      139267   139410   +143     
  Branches   139267   139410   +143     
========================================
+ Hits       124402   124530   +128     
- Misses      12235    12254    +19     
+ Partials     2630     2626     -4     
Flag Coverage Δ
fuzzing 35.09% <67.52%> (+0.10%) ⬆️
tests 88.67% <83.57%> (-0.02%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

pub struct HolderCommitmentTransactionBalance {
/// The amount available to claim, in satoshis, excluding the on-chain fees which will be
/// required to do so.
pub amount_satoshis: u64,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renaming to amount_onchain_satoshis might be helpful to avoid confusion. Or maybe it should be amount_unilateral_close_satoshis?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, good point. What about amount_claimable_satoshis? Initially I thought that might be confusing as there's a somewhat separate concept of "claimable" between on-chain and off-chain, but actually they're pretty related - the amount we're allowed to send off-chain is, basically, the amount we're able to claim on-chain in an FC, with the one exception being dust, but that only applies for channels with 0 reserve (which are mostly end-user channels and probably use the amount_offchain_satoshis. Its also a part of Balance::ClaimableOnChannelClose which makes it align better I think?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Claimable" as the unilaterally recoverable balance does seem like an improvement. And it often remains hard to capture the full meaning in a name when dealing with lightning concepts.

///
/// This is generally roughly equal to [`Self::amount_satoshis`] +
/// [`Self::transaction_fee_satoshis`] + any anchor outputs in the current commitment
/// transaction. It might differ slightly due to differences in rounding and HTLC calculation.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What differences in rounding and htlc calculation cause this?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fee is calculated by just totaling the transaction fee (funding amount minus sum of all the outputs). The amount-offchain is the actual channel balance minus HTLCs pending outbound (in msats) plus inbound HTLCs we have the preimage for.

The HTLC difference is the fees on outputs for inbound HTLCs we have the preimages for, rounding is totally different as well.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could consider describing some of this in the code.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, spent a minute fighting with it but not sure how to add it such that its actually useful information. It shouldn't differ by more than a few sats, so going into detail about how its all calculated seems kinda overkill?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes not critical to add. Just the question that came to mind when reading the comment.

balance_candidates.last().map(|balance| balance.amount_offchain_satoshis.unwrap_or(balance.amount_satoshis)).unwrap_or(0)
}
},
Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. }|
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't offchain_amount_satoshis be undefined if the channel is no longer offchain? Maybe this indicates that the name isn't fully covering the meaning of the value.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yea, maybe the name could use some workshopping. My intended use here is really "balance that an end-user wallet might care about" which obviously includes funds which we're in the process of claiming on-chain, but until we close its not really anything corresponding to anything "on-chain". I'm definitely open to a better name, if you have any thoughts.

Copy link
Contributor

@joostjager joostjager Dec 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

user_balance maybe? That is quite indirect though, but maybe it is good to steer away from onchain/offchain because there are nuances to that.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I don't want to imply that our devs should prefer this as the "balance". Its really not - the claimable amount is closer to the "balance" IMO, though of course its a bit misleading as well...

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, don't know. Maybe 2nd reviewer has inspiration...

#[derive(Clone, Debug)]
pub struct CommitmentTransaction {
commitment_number: u64,
to_broadcaster_value_offchain_msat: Option<u64>,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Were there other data structures that could have stored this value? The field looks a bit out of place between all the on-chain properties.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could put it directly in the ChannelMonitorUpdateStep::LatestCounterpartyCommitment but it doesn't really feel like it belongs there any more. The nice thing about being in the CommitmentTransaction is it will (eventually) go through the custom commitment transaction API, which I think feels right?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LatestCounterpartyCommitment does have some additional non-on-chain info like htlc sources already. But not sure how those two options compare.

The nice thing about being in the CommitmentTransaction is it will (eventually) go through the custom commitment transaction API

Can you elaborate a bit more on what it brings to have to_broadcaster_value_offchain_msat go through the custom commit tx API? That the calculation of value_offchain can also be custom you mean?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That the calculation of value_offchain can also be custom you mean?

Right, this. Some "balance" might actually be locked up in some sub-protocol LDK isn't aware of, at least eventually.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See comment below, and PR #4026 for a potential path to customization of this offchain value.

@ldk-reviews-bot
Copy link

👋 The first review has been submitted!

Do you think this PR is ready for a second reviewer? If so, click here to assign a second reviewer.

In a previous commit we introduced the concept of the "offchain
balance" to `HolderCommitmentTransactionBalance` to better capture
the type of balance that end-user walets likely wish to expose.

Here we expose an accessor on `Balance` to fetch that concept
across difference `Balance` variants easily.

Fixes lightningdevkit#4241
@TheBlueMatt TheBlueMatt force-pushed the 2025-12-end-user-balances branch from 0b0f140 to 4f1abd3 Compare December 9, 2025 15:45
@ldk-reviews-bot
Copy link

✅ Added second reviewer: @tankyleo

Copy link
Contributor

@tankyleo tankyleo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you considered exposing this concept in channel instead, via get_available_balances and ChannelDetails ? We've now consolidated and cleaned up a lot of things in channel, so I wonder if calculating this concept there is now straightforward and easier to reason about than in the past. I understand I am missing conversations behind the removal of AvailableBalances::balance_msat, have only read some parts.

In #4026 I give the channel state machine snapshot to TxBuilder and ask it to give me AvailableBalances, so there is still a path to customization if we go the channel direction.

FundedChannel::send_htlc calls get_available_balances to determine whether it can send this new HTLC, so it seems reasonable to me to have get_available_balances also produce the offchain balance.

@TheBlueMatt
Copy link
Collaborator Author

Have you considered exposing this concept in channel instead, via get_available_balances and ChannelDetails ? We've now consolidated and cleaned up a lot of things in channel, so I wonder if calculating this concept there is now straightforward and easier to reason about than in the past. I understand I am missing conversations behind the removal of AvailableBalances::balance_msat, have only read some parts.

Part of the reason we dropped it is because we didn't want to have two separate ways to calculate "balance". While I agree this approach would simplify the implementation, it would reintroduce the dual balance APIs, which I'm very much not a fan of.

@tankyleo
Copy link
Contributor

it would reintroduce the dual balance APIs, which I'm very much not a fan of.

Agreed dual-balance API is ugly.

I'm also not digesting well sticking an offchain balance in CommitmentTransaction and ChannelMonitor :)

I do like keeping ChannelMonitor focused on only reporting balances it can claim on-chain.

Keeping it as dual-APIs would make it clear to the user, if you want an offchain balance, look in channel, if you want a balance that you can actually claim on-chain, look in channelmonitor.

In my experience with ldk-server, I always looked at channel::AvailableBalances.next_outbound_htlc_limit_msat in order to determine what balance I could send next (I had a single channel). So seems to me users will be jumping between the two APIs in any case ?

If we put the offchain_balance setting in channel, would devs now stop looking at ChannelMonitor for balances to report to end-users, and look at just channel::AvailableBalances ?

@wpaulino would love to hear your thoughts - if you are good with this direction here, I can see it working too.

@wpaulino
Copy link
Contributor

I'm also not a huge fan of tracking the offchain balance in the monitor. Exposing it in AvailableBalances may force us to consider HTLCs in the holding cell as well though, which further complicates things.

I would actually prefer to see @MaxFangX's suggestion in #4241 to include the amount burned to fees from the offchain state, with either a helper or documentation on how you could arrive at the offchain balance.

@tankyleo
Copy link
Contributor

tankyleo commented Dec 11, 2025

Exposing it in AvailableBalances may force us to consider HTLCs in the holding cell as well though, which further complicates things.

Hmm in #4026 I build the set of HTLCs like this before passing it to TxBuilder for balance calculations, did you have some further complications in mind ?

                let pending_outbound_htlcs = self.pending_outbound_htlcs.iter().map(|htlc| HTLCAmountDirection { amount_msat: htlc.amount_msat, outbound: true });
                let pending_inbound_htlcs = self.pending_inbound_htlcs.iter().map(|htlc| HTLCAmountDirection { amount_msat: htlc.amount_msat, outbound: false });
                let holding_cell_htlcs = self.holding_cell_htlc_updates.iter().filter_map(|htlc| {
                        if let &HTLCUpdateAwaitingACK::AddHTLC { amount_msat, .. } = htlc {
                                Some(HTLCAmountDirection { outbound: true, amount_msat })
                        } else {
                                None
                        }
                });

                let mut pending_htlcs: Vec<HTLCAmountDirection> = Vec::with_capacity(self.pending_outbound_htlcs.len() + self.pending_inbound_htlcs.len() + self.holding_cell_htlc_updates.len());
                pending_htlcs.extend(pending_outbound_htlcs.chain(pending_inbound_htlcs).chain(holding_cell_htlcs));

                let dust_exposure_limiting_feerate = self.get_dust_exposure_limiting_feerate(
                        &fee_estimator, funding.get_channel_type(),
                );
                let max_dust_htlc_exposure_msat = self.get_max_dust_htlc_exposure_msat(dust_exposure_limiting_feerate);

                SpecTxBuilder {}.get_available_balances(
                        funding.is_outbound(),
                        funding.get_value_satoshis(),
                        funding.get_value_to_self_msat(),
                        &pending_htlcs,
                        self.feerate_per_kw,
                        dust_exposure_limiting_feerate,
                        max_dust_htlc_exposure_msat,
                        self.get_holder_channel_constraints(funding),
                        self.get_counterparty_channel_constraints(funding),
                        funding.get_channel_type(),
                )

@TheBlueMatt
Copy link
Collaborator Author

TheBlueMatt commented Dec 11, 2025

I'm also not digesting well sticking an offchain balance in CommitmentTransaction and ChannelMonitor :)

Its weird in ChannelMonitor to some extent yes, but that's where we put Balance, so... 🤷‍♂️ . I guess I didn't really see CommitmentTransaction as "only stuff specific to on-chain goes in here" cause it already has more derivation parameters and other random crap, so it felt fine enough to shove other information about how the commitment transaction was built there.

Keeping it as dual-APIs would make it clear to the user, if you want an offchain balance, look in channel, if you want a balance that you can actually claim on-chain, look in channelmonitor.

This is what we had before, and people just never saw the other balance, used the one in ChannelDetails without thinking, and had issues with it being weird. I don't buy that two separate places works.

In my experience with ldk-server, I always looked at channel::AvailableBalances.next_outbound_htlc_limit_msat in order to determine what balance I could send next (I had a single channel). So seems to me users will be jumping between the two APIs in any case ?

But this is a totally different concept from the "balance". The next_outbound_htlc_limit_msat only describes the balance for a single channel for a single HTLC. A payment (the thing the user cares about) might MPP across multiple channels or might even be able to violate the next_outbound_htlc_limit_msat by MPPing across a single channel! (though our router currently cannot do so, maybe we should add support for that eventually...).

Admittedly this is maybe useful, in sum across channels, as the "balance you can send in your next payment over LN", but IMO its wrong to pull this for that as in the future it might well break - the router may get smarter and MPP across a single channel.

I would actually prefer to see @MaxFangX's suggestion in #4241 to include the amount burned to fees from the offchain state, with either a helper or documentation on how you could arrive at the offchain balance.

This is just two sides of the same coin? Storing the "user balance minus available-to-claim balance" just means doing math when building the CommitmentTransaction and then doing the inverse math in Balance balance-fetching logic. I mean we can swap it, but I don't see how its much of a difference?

@wpaulino
Copy link
Contributor

This is just two sides of the same coin? Storing the "user balance minus available-to-claim balance" just means doing math when building the CommitmentTransaction and then doing the inverse math in Balance balance-fetching logic. I mean we can swap it, but I don't see how its much of a difference?

I agree it's essentially the same, but it maintains the "onchain" theme of the monitor better than just exposing the offchain balance directly since fees are enforceable onchain, and meshes well with the already exposed HolderCommitmentTransactionBalance::transaction_fee_satoshis.

@MaxFangX
Copy link
Contributor

This is just two sides of the same coin? Storing the "user balance minus available-to-claim balance" just means doing math when building the CommitmentTransaction and then doing the inverse math in Balance balance-fetching logic. I mean we can swap it, but I don't see how its much of a difference?

Not opinionated on how LDK how stores the value internally, but just want to note that due to UI / UX reasons we've already had to manually match on Balance ourselves to tweak what is included so that our displayed balance is more intuitive to users: https://github.com/lexe-app/lexe-public/blob/c7b38b38f4f787fb5449683b48931018bbbf92e5/lexe-ln/src/balance.rs#L135-L170

We'd love to remove this logic and just use the new offchain_amount_satoshis helper but due to how finicky these edge cases are I don't have confidence that we won't need to tweak the matching again in the future. So as long as we can fall back to handling Balance directly, and as long as calculating our own version of our 'user balance' is reasonably easy to do, we're ok with it.

@TheBlueMatt
Copy link
Collaborator Author

I agree it's essentially the same, but it maintains the "onchain" theme of the monitor better than just exposing the offchain balance directly since fees are enforceable onchain, and meshes well with the already exposed HolderCommitmentTransactionBalance::transaction_fee_satoshis.

To clarify your concern - is your view that the ChannelMonitor should only expose "on-chain" information or that ChannelMonitor should only have, internally, "on-chain" information?

If its the first you're really arguing we need to move Balance (again), imo. Just switching how we store the burned value isn't really solving that - the API will still be ChannelMonitor::balances() -> Balance::get_offchain_balance (or whatever you want to call it) and the primary way devs interact with this will be fetching a balance that includes offchain things.

In terms of internal storage, ultimately the ChannelMonitor is just storing a CommitmentTransaction. That's mostly on-chain info, but about half of it is information that was used to derive/build the commitment transaction (and might be useful for other purposes, like ChannelMonitor claiming outputs on the commitment tx). Its also (going to be) a primary return value from the custom tx builder API, so including additional info relevant to that feels fine to me.

Not opinionated on how LDK how stores the value internally, but just want to note that due to UI / UX reasons we've already had to manually match on Balance ourselves to tweak what is included so that our displayed balance is more intuitive to users: https://github.com/lexe-app/lexe-public/blob/c7b38b38f4f787fb5449683b48931018bbbf92e5/lexe-ln/src/balance.rs#L135-L170

That's still gonna be funky with reserve values + anchors as values below reserve will still show 0 (at least for inbound channels) and anchors will be excluded from the balance (for outbound channels). I assume that is not what you want?

@MaxFangX
Copy link
Contributor

That's still gonna be funky with reserve values + anchors as values below reserve will still show 0 (at least for inbound channels) and anchors will be excluded from the balance (for outbound channels). I assume that is not what you want?

Correct. Things like anchors and channel reserves are low-level implementation details that average Joe consumers aren't going to care about once they have some significant amount of funds in the channel. They're going to be more concerned if when testing the wallet they deposit 100 sats and it displays as 0 sats despite a successful payment - they'll think the wallet is a scam, or at minimum think it is broken in some way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Expose the amount held on our end of the channel

6 participants