Skip to content

Commit 6a47fb1

Browse files
authored
Merge pull request #1223 from shubhamkmr04/splice-in-reserve-fees
Count the funding fee in the anchor reserve check for splice-ins and fee bumps
2 parents b70ab14 + 15d0afc commit 6a47fb1

5 files changed

Lines changed: 668 additions & 26 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,15 @@
118118
built after the channel had already been negotiated.
119119
- When acting as an LSPS2 service, we likewise account for the funding transaction's fee when
120120
checking that a JIT channel can be opened while retaining the anchor reserve.
121+
- Splicing in an exact amount now accounts for the fee of our contribution to the splice
122+
transaction when checking the anchor reserve, including the higher fee of up to 1.5 times the
123+
feerate we may still pay, and fails with `NodeError::ChannelSplicingFailed` if paying it could
124+
spend part of the reserve. Previously, the fee could be paid from the reserve.
125+
- `Node::bump_channel_funding_fee` now checks the anchor reserve as well, and fails with
126+
`NodeError::ChannelSplicingFailed` if the replacement takes more from our on-chain funds than
127+
the pending splice and could spend part of the reserve. Previously, the reserve could pay the
128+
higher fee of a splice-in, or fund a splice-out's withdrawal when the channel balance couldn't
129+
cover the higher fee.
121130

122131
# 0.7.0 - Dec. 3, 2025
123132
This seventh minor release introduces numerous new features, bug fixes, and API improvements. In particular, it adds support for channel Splicing, Async Payments, as well as sourcing chain data from a Bitcoin Core REST backend.

‎src/lib.rs‎

Lines changed: 230 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1614,8 +1614,13 @@ impl Node {
16141614
};
16151615
let cur_anchor_reserve_sats =
16161616
total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
1617-
let spendable_amount_sats =
1618-
self.wallet.get_spendable_amount_sats(cur_anchor_reserve_sats).unwrap_or(0);
1617+
let spendable_amount_sats = if new_channel_with_funding_fee_rate.is_some() {
1618+
self.wallet.get_spendable_amount_sats(cur_anchor_reserve_sats).unwrap_or(0)
1619+
} else {
1620+
// A splice-in only spends confirmed outputs, and the check of its built contribution
1621+
// leaves out unconfirmed change, so check against the same funds before coin selection.
1622+
self.wallet.get_confirmed_unlocked_amount_sats().saturating_sub(cur_anchor_reserve_sats)
1623+
};
16191624

16201625
if spendable_amount_sats < amount_sats {
16211626
log_error!(
@@ -1662,6 +1667,65 @@ impl Node {
16621667
Ok(())
16631668
}
16641669

1670+
/// Checks, now that the fee of `contribution` is known, that it leaves the anchor reserve in
1671+
/// place. Otherwise, fails with [`Error::ChannelSplicingFailed`], after returning the inputs
1672+
/// and outputs `contribution` reserved for itself to the wallet via
1673+
/// `Wallet::release_inputs_and_outputs`. Those it inherited from a pending splice stay
1674+
/// reserved.
1675+
///
1676+
/// Once the transaction of `contribution` confirms, we hold `confirmed_unlocked_sats`, read
1677+
/// before `contribution` was built as building it locks the inputs it selects, plus the inputs
1678+
/// of `prior_contribution`, the contribution it replaces, which are ours again unless
1679+
/// `contribution` spends them too. What `contribution` may take from our wallet at most, see
1680+
/// [`max_wallet_spend_sats`], must leave the anchor reserve of those funds, unless it takes no
1681+
/// more than `prior_contribution` already may.
1682+
fn check_sufficient_onchain_funds_for_contribution(
1683+
&self, contribution: FundingContribution, prior_contribution: Option<&FundingContribution>,
1684+
confirmed_unlocked_sats: u64,
1685+
) -> Result<FundingContribution, Error> {
1686+
let required_funds_sats = max_wallet_spend_sats(&contribution);
1687+
if required_funds_sats <= prior_contribution.map_or(0, max_wallet_spend_sats) {
1688+
return Ok(contribution);
1689+
}
1690+
1691+
let prior_inputs_sats: u64 = prior_contribution.map_or(0, |prior_contribution| {
1692+
prior_contribution.inputs().iter().map(|input| input.output().value.to_sat()).sum()
1693+
});
1694+
let cur_anchor_reserve_sats =
1695+
total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
1696+
let available_funds_sats = confirmed_unlocked_sats
1697+
.saturating_add(prior_inputs_sats)
1698+
.saturating_sub(cur_anchor_reserve_sats);
1699+
if required_funds_sats <= available_funds_sats {
1700+
return Ok(contribution);
1701+
}
1702+
1703+
let action_str =
1704+
if prior_contribution.is_some() { "bump the splice fee" } else { "splice-in" };
1705+
log_error!(
1706+
self.logger,
1707+
"Unable to {} due to insufficient funds. Available: {}sats, Required: {}sats (including fees)",
1708+
action_str,
1709+
available_funds_sats,
1710+
required_funds_sats,
1711+
);
1712+
1713+
// Return what was set aside for the contribution we drop, but nothing it inherited from a
1714+
// pending splice: that splice's transaction may still confirm.
1715+
let inputs = contribution.reserved_inputs().map(|input| input.outpoint()).collect();
1716+
let outputs = contribution.reserved_outputs().cloned().collect();
1717+
if let Err(e) =
1718+
self.runtime.block_on(self.wallet.release_inputs_and_outputs(inputs, outputs))
1719+
{
1720+
log_error!(
1721+
self.logger,
1722+
"Failed to release the inputs of a dropped splice contribution: {}",
1723+
e
1724+
);
1725+
}
1726+
Err(Error::ChannelSplicingFailed)
1727+
}
1728+
16651729
/// Connect to a node and open a new unannounced channel.
16661730
///
16671731
/// To open an announced channel, see [`Node::open_announced_channel`].
@@ -1942,10 +2006,6 @@ impl Node {
19422006
});
19432007
let max_feerate = max_funding_feerate(min_feerate);
19442008

1945-
if let FundingAmount::Exact { amount_sats } = splice_amount_sats {
1946-
self.check_sufficient_onchain_funds(amount_sats, &counterparty_node_id, None)?;
1947-
}
1948-
19492009
let funding_template = self
19502010
.channel_manager
19512011
.splice_channel(&channel_details.channel_id, &counterparty_node_id)
@@ -1973,18 +2033,35 @@ impl Node {
19732033
};
19742034

19752035
let contribution = match splice_amount_sats {
1976-
FundingAmount::Exact { amount_sats } => self
1977-
.runtime
1978-
.block_on(funding_template.splice_in(
1979-
Amount::from_sat(amount_sats),
1980-
feerate,
1981-
max_feerate,
1982-
Arc::clone(&self.wallet),
1983-
))
1984-
.map_err(|e| {
1985-
log_error!(self.logger, "Failed to splice channel: {}", e);
1986-
Error::ChannelSplicingFailed
1987-
})?,
2036+
FundingAmount::Exact { amount_sats } => {
2037+
// Only checked here, so that a pending splice of ours, whose inputs are locked,
2038+
// fails above as such rather than for lack of funds.
2039+
self.check_sufficient_onchain_funds(amount_sats, &counterparty_node_id, None)?;
2040+
2041+
// Coin selection locks the inputs it picks, so read our funds before it.
2042+
let confirmed_unlocked_sats = self.wallet.get_confirmed_unlocked_amount_sats();
2043+
2044+
let contribution = self
2045+
.runtime
2046+
.block_on(funding_template.splice_in(
2047+
Amount::from_sat(amount_sats),
2048+
feerate,
2049+
max_feerate,
2050+
Arc::clone(&self.wallet),
2051+
))
2052+
.map_err(|e| {
2053+
log_error!(self.logger, "Failed to splice channel: {}", e);
2054+
Error::ChannelSplicingFailed
2055+
})?;
2056+
2057+
// The fee for our contribution is paid from the same on-chain funds as the
2058+
// amount, and coin selection doesn't keep the anchor reserve aside.
2059+
self.check_sufficient_onchain_funds_for_contribution(
2060+
contribution,
2061+
None,
2062+
confirmed_unlocked_sats,
2063+
)?
2064+
},
19882065
FundingAmount::Max => self.splice_in_with_all_contribution(
19892066
funding_template,
19902067
Vec::new(),
@@ -2164,6 +2241,12 @@ impl Node {
21642241
/// pending splice that requires a higher feerate to be replaced, or when the counterparty
21652242
/// initiates a splice concurrently and our contribution is added to theirs.
21662243
///
2244+
/// The fee for our contribution is paid from the same on-chain funds as `splice_amount_sats`.
2245+
/// Together with the most we may pay in fees, as described above, the amount must fit within our
2246+
/// confirmed on-chain funds beyond the anchor reserve. If the amount alone doesn't, this fails
2247+
/// with [`NodeError::InsufficientFunds`], and if the fees don't, with
2248+
/// [`NodeError::ChannelSplicingFailed`].
2249+
///
21672250
/// # Experimental API
21682251
///
21692252
/// This API is experimental. Currently, a splice-in will be marked as an outbound payment, but
@@ -2281,8 +2364,9 @@ impl Node {
22812364
///
22822365
/// [`Node::bump_channel_funding_fee`] preserves the destination output value, including for
22832366
/// maximum withdrawals. If the channel cannot cover the higher fee, it may fund the entire
2284-
/// output and fees from the on-chain wallet instead, leaving the channel balance unwithdrawn.
2285-
/// It does not reduce the destination output to pay the additional fee.
2367+
/// output and fees from the on-chain wallet instead, leaving the channel balance unwithdrawn,
2368+
/// or fail with [`NodeError::ChannelSplicingFailed`] if that would spend part of the anchor
2369+
/// reserve. It does not reduce the destination output to pay the additional fee.
22862370
///
22872371
/// Success means the contribution was submitted, not that the splice has completed. Monitor
22882372
/// [`Event::SpliceNegotiated`] or [`Event::SpliceNegotiationFailed`] for the negotiation result,
@@ -2410,6 +2494,12 @@ impl Node {
24102494
/// fees, leaving the channel balance unwithdrawn. This also applies to withdrawals created
24112495
/// with [`Node::splice_out_max`]; the output is not reduced to cover the higher fee.
24122496
///
2497+
/// The replacement may take more from our on-chain funds than the pending splice, such as for
2498+
/// the higher fee of a splice-in or a withdrawal funded by wallet inputs. If so, our confirmed
2499+
/// on-chain funds must still cover the anchor reserve once it confirms, even at the most we may
2500+
/// pay in fees as described below. Otherwise, this fails with
2501+
/// [`NodeError::ChannelSplicingFailed`].
2502+
///
24132503
/// A splice of all on-chain funds (see [`Node::splice_in_with_all`]) has no amount to preserve:
24142504
/// the bump is paid by adding less to the channel, or, if the pending splice's maximum feerate
24152505
/// does not allow that or less than dust would be left to add, the splice is rebuilt from all
@@ -2461,6 +2551,10 @@ impl Node {
24612551
return Err(Error::ChannelSplicingFailed);
24622552
};
24632553

2554+
// Coin selection for the replacement, if LDK needs one, locks the inputs it picks, so
2555+
// read our funds before it.
2556+
let confirmed_unlocked_sats = self.wallet.get_confirmed_unlocked_amount_sats();
2557+
24642558
let rbf_template = funding_template.clone();
24652559
let prior_value_added_sats = funding_template
24662560
.prior_contribution()
@@ -2489,7 +2583,15 @@ impl Node {
24892583
},
24902584
};
24912585
let contribution = match adjusted {
2492-
Some(contribution) => contribution,
2586+
// The replacement may take more from our wallet than the pending splice does: a
2587+
// splice-in pays the higher fee from its change or newly selected coins, and a
2588+
// splice-out whose channel balance can't cover it is funded from our wallet
2589+
// entirely. Neither keeps the anchor reserve aside.
2590+
Some(contribution) => self.check_sufficient_onchain_funds_for_contribution(
2591+
contribution,
2592+
funding_template.prior_contribution(),
2593+
confirmed_unlocked_sats,
2594+
)?,
24932595
// The pending splice spends manually selected inputs, as a splice-in of all funds
24942596
// does, so replace it with one built the same way from all confirmed funds: its
24952597
// inputs and any coins confirmed since.
@@ -2947,6 +3049,41 @@ fn max_splice_out_output(
29473049
Ok(output)
29483050
}
29493051

3052+
/// The most `contribution` may take from our on-chain wallet once its transaction confirms: its
3053+
/// inputs, less the least change it may return.
3054+
///
3055+
/// After we built `contribution`, LDK may still raise its fee up to its maximum feerate, when our
3056+
/// contribution joins a splice the counterparty initiated or the RBF minimum feerate rises. It
3057+
/// pays the difference from the change, and drops the change entirely if less than dust would be
3058+
/// left.
3059+
fn max_wallet_spend_sats(contribution: &FundingContribution) -> u64 {
3060+
let inputs_sats: u64 =
3061+
contribution.inputs().iter().map(|input| input.output().value.to_sat()).sum();
3062+
let Some(change_output) = contribution.change_output() else {
3063+
return inputs_sats;
3064+
};
3065+
3066+
// At the same weight, the fee scales with the feerate, and as the acceptor we pay for less
3067+
// weight. Fees are rounded up, so this is at least the increase LDK may apply.
3068+
let fee_sats = contribution.estimated_fee().to_sat();
3069+
let feerate_sat_per_kwu = contribution.feerate().to_sat_per_kwu();
3070+
let max_feerate_sat_per_kwu = contribution.max_feerate().to_sat_per_kwu();
3071+
let max_fee_increase_sats = if feerate_sat_per_kwu == 0 {
3072+
0
3073+
} else {
3074+
fee_sats
3075+
.saturating_mul(max_feerate_sat_per_kwu.saturating_sub(feerate_sat_per_kwu))
3076+
.div_ceil(feerate_sat_per_kwu)
3077+
};
3078+
3079+
let dust_limit_sats = change_output.script_pubkey.minimal_non_dust().to_sat();
3080+
let min_change_sats = match change_output.value.to_sat().checked_sub(max_fee_increase_sats) {
3081+
Some(change_sats) if change_sats >= dust_limit_sats => change_sats,
3082+
_ => 0,
3083+
};
3084+
inputs_sats.saturating_sub(min_change_sats)
3085+
}
3086+
29503087
impl Drop for Node {
29513088
fn drop(&mut self) {
29523089
let _ = self.stop();
@@ -3182,4 +3319,76 @@ mod tests {
31823319
assert_eq!(new.latest_pathfinding_scores_sync_timestamp, Some(1_300));
31833320
assert_eq!(new.latest_node_announcement_broadcast_timestamp, Some(2_000));
31843321
}
3322+
3323+
fn test_p2wpkh_script(seed: u8) -> bitcoin::ScriptBuf {
3324+
use bitcoin::hashes::Hash;
3325+
bitcoin::ScriptBuf::new_p2wpkh(&bitcoin::WPubkeyHash::from_byte_array([seed; 20]))
3326+
}
3327+
3328+
/// A contribution spending a 100,000 sat coin, with the given change, whose fee of 1,001 sats
3329+
/// at 1,000 sat/kwu may rise up to `max_feerate_sat_per_kwu`.
3330+
fn test_splice_in_contribution(
3331+
change_sat: Option<u64>, max_feerate_sat_per_kwu: u64,
3332+
) -> FundingContribution {
3333+
let prevtx = bitcoin::Transaction {
3334+
version: bitcoin::transaction::Version::TWO,
3335+
lock_time: bitcoin::absolute::LockTime::ZERO,
3336+
input: vec![bitcoin::TxIn::default()],
3337+
output: vec![bitcoin::TxOut {
3338+
value: Amount::from_sat(100_000),
3339+
script_pubkey: test_p2wpkh_script(1),
3340+
}],
3341+
};
3342+
let change_output = change_sat.map(|change_sat| bitcoin::TxOut {
3343+
value: Amount::from_sat(change_sat),
3344+
script_pubkey: test_p2wpkh_script(2),
3345+
});
3346+
crate::payment::pending_payment_store::test_funding_contribution_with_parts(
3347+
1_001,
3348+
1_000,
3349+
max_feerate_sat_per_kwu,
3350+
&[prevtx],
3351+
&[],
3352+
change_output.as_ref(),
3353+
)
3354+
}
3355+
3356+
#[test]
3357+
fn max_wallet_spend_without_change_is_all_inputs() {
3358+
assert_eq!(max_wallet_spend_sats(&test_splice_in_contribution(None, 1_500)), 100_000);
3359+
}
3360+
3361+
#[test]
3362+
fn max_wallet_spend_holds_back_change_for_a_higher_fee() {
3363+
// At 1.5 times the feerate, the fee of 1,001 sats may rise by 500.5 sats, rounded up.
3364+
assert_eq!(
3365+
max_wallet_spend_sats(&test_splice_in_contribution(Some(10_000), 1_500)),
3366+
100_000 - 10_000 + 501
3367+
);
3368+
// Without room to raise the feerate, all of the change comes back.
3369+
assert_eq!(
3370+
max_wallet_spend_sats(&test_splice_in_contribution(Some(10_000), 1_000)),
3371+
100_000 - 10_000
3372+
);
3373+
}
3374+
3375+
#[test]
3376+
fn max_wallet_spend_counts_change_left_below_dust_as_spent() {
3377+
let dust_limit_sat = test_p2wpkh_script(2).minimal_non_dust().to_sat();
3378+
// Change left at the dust limit after the higher fee is kept.
3379+
assert_eq!(
3380+
max_wallet_spend_sats(&test_splice_in_contribution(Some(501 + dust_limit_sat), 1_500)),
3381+
100_000 - dust_limit_sat
3382+
);
3383+
// Below it, the change is dropped and spent along with the inputs.
3384+
assert_eq!(
3385+
max_wallet_spend_sats(&test_splice_in_contribution(
3386+
Some(501 + dust_limit_sat - 1),
3387+
1_500
3388+
)),
3389+
100_000
3390+
);
3391+
// So is change that can't even cover the higher fee.
3392+
assert_eq!(max_wallet_spend_sats(&test_splice_in_contribution(Some(400), 1_500)), 100_000);
3393+
}
31853394
}

‎src/payment/pending_payment_store.rs‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -286,18 +286,18 @@ impl From<&PendingPaymentDetails> for PendingPaymentDetailsUpdate {
286286
pub(crate) fn test_funding_contribution_with_outputs(
287287
estimated_fee_sat: u64, feerate: u64, outputs: &[bitcoin::TxOut],
288288
) -> lightning::ln::funding::FundingContribution {
289-
test_funding_contribution_with_parts(estimated_fee_sat, feerate, &[], outputs, None)
289+
test_funding_contribution_with_parts(estimated_fee_sat, feerate, feerate, &[], outputs, None)
290290
}
291291

292292
/// Builds a [`FundingContribution`] for tests from its parts: the given estimated fee, an input
293293
/// spending output 0 — which must be P2WPKH — of each given previous transaction, the given
294-
/// contributed outputs and change output, and the given input-selection feerate (also used as
295-
/// the maximum), with the is-splice flag set.
294+
/// contributed outputs and change output, and the given input-selection and maximum feerates,
295+
/// with the is-splice flag set.
296296
///
297297
/// [`FundingContribution`]: lightning::ln::funding::FundingContribution
298298
#[cfg(test)]
299299
pub(crate) fn test_funding_contribution_with_parts(
300-
estimated_fee_sat: u64, feerate: u64, prevtxs: &[bitcoin::Transaction],
300+
estimated_fee_sat: u64, feerate: u64, max_feerate: u64, prevtxs: &[bitcoin::Transaction],
301301
outputs: &[bitcoin::TxOut], change_output: Option<&bitcoin::TxOut>,
302302
) -> lightning::ln::funding::FundingContribution {
303303
use lightning::util::ser::{BigSize, Writeable};
@@ -340,7 +340,7 @@ pub(crate) fn test_funding_contribution_with_parts(
340340
records.extend_from_slice(&[9, 8]); // (9, feerate)
341341
records.extend_from_slice(&feerate.to_be_bytes());
342342
records.extend_from_slice(&[11, 8]); // (11, max_feerate)
343-
records.extend_from_slice(&feerate.to_be_bytes());
343+
records.extend_from_slice(&max_feerate.to_be_bytes());
344344
records.extend_from_slice(&[13, 1, 1]); // (13, is_splice: true)
345345
let mut tlv_bytes = Vec::new();
346346
// BigSize length prefix over the TLV records above.

0 commit comments

Comments
 (0)