From 14aa7ec9f23f4a110decc76bd99dd58d9393beda Mon Sep 17 00:00:00 2001 From: Shubham Kumar Date: Tue, 17 Nov 2026 18:58:47 +0530 Subject: [PATCH 1/4] Return the spendable balance from `check_sufficient_onchain_funds` Splicing in an exact amount is about to also check what its built contribution takes from our wallet, fee included. Coin selection locks the inputs it picks, which takes them off the spendable balance, so that check needs the balance from before coin selection. Have `check_sufficient_onchain_funds` return the spendable balance it checked the amount against, so that the splice-in can reuse it. Part of #1166. Developed with assistance from Claude Code. --- src/lib.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 87dd434d51..884f6199af 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1589,10 +1589,12 @@ impl Node { Ok(new_channel_anchor_reserve_sats(&self.config, peer_node_id, anchor_channel)) } + /// Returns the spendable on-chain balance, i.e., excluding the anchor reserve, that + /// `amount_sats` was checked against. fn check_sufficient_onchain_funds( &self, amount_sats: u64, peer_node_id: &PublicKey, new_channel_with_funding_fee_rate: Option, - ) -> Result<(), Error> { + ) -> Result { let action_str = if new_channel_with_funding_fee_rate.is_some() { "create channel" } else { @@ -1645,7 +1647,7 @@ impl Node { } } - Ok(()) + Ok(spendable_amount_sats) } /// Connect to a node and open a new unannounced channel. From 915b7dd46dfcf8c66e036d2abef86e49f0dded3b Mon Sep 17 00:00:00 2001 From: Shubham Kumar Date: Sun, 8 Nov 2026 10:36:09 +0530 Subject: [PATCH 2/4] Count the funding fee in the anchor reserve check for splice-ins Splicing in an exact amount only checked that our on-chain funds cover the amount on top of the anchor reserve. The fee for our contribution to the splice transaction is paid from the same funds, though, and coin selection doesn't keep the reserve aside, so the fee could be taken from it. Once the contribution is built, also check that what it takes from our wallet, its inputs minus its change, fits in the funds beyond the reserve. Coin selection locks the inputs it picks, which takes them off the spendable balance, so compare against the balance from before it: the check of the amount alone now runs right before coin selection and provides it. If the contribution doesn't fit, release what coin selection locked for it and fail with `InsufficientFunds`. A plain lack of funds still fails before coin selection. Part of #1166. Developed with assistance from Claude Code. --- CHANGELOG.md | 3 ++ src/lib.rs | 81 ++++++++++++++++++++++++++------- tests/integration_tests_rust.rs | 79 ++++++++++++++++++++++++++++++++ 3 files changed, 147 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ef50da0a28..a441af5c8f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -118,6 +118,9 @@ built after the channel had already been negotiated. - When acting as an LSPS2 service, we likewise account for the funding transaction's fee when checking that a JIT channel can be opened while retaining the anchor reserve. +- Splicing in an exact amount now accounts for the fee of our contribution to the splice + transaction when checking the anchor reserve, and fails with `NodeError::InsufficientFunds` if + paying it would spend part of the reserve. Previously, the fee could be paid from the reserve. # 0.7.0 - Dec. 3, 2025 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. diff --git a/src/lib.rs b/src/lib.rs index 884f6199af..30eadfe21e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1930,10 +1930,6 @@ impl Node { }); let max_feerate = max_funding_feerate(min_feerate); - if let FundingAmount::Exact { amount_sats } = splice_amount_sats { - self.check_sufficient_onchain_funds(amount_sats, &counterparty_node_id, None)?; - } - let funding_template = self .channel_manager .splice_channel(&channel_details.channel_id, &counterparty_node_id) @@ -1961,18 +1957,67 @@ impl Node { }; let contribution = match splice_amount_sats { - FundingAmount::Exact { amount_sats } => self - .runtime - .block_on(funding_template.splice_in( - Amount::from_sat(amount_sats), - feerate, - max_feerate, - Arc::clone(&self.wallet), - )) - .map_err(|e| { - log_error!(self.logger, "Failed to splice channel: {}", e); - Error::ChannelSplicingFailed - })?, + FundingAmount::Exact { amount_sats } => { + // Coin selection locks the inputs it picks, which takes them off the spendable + // balance, so keep the balance from before it to check the contribution against. + let spendable_amount_sats = self.check_sufficient_onchain_funds( + amount_sats, + &counterparty_node_id, + None, + )?; + + let contribution = self + .runtime + .block_on(funding_template.splice_in( + Amount::from_sat(amount_sats), + feerate, + max_feerate, + Arc::clone(&self.wallet), + )) + .map_err(|e| { + log_error!(self.logger, "Failed to splice channel: {}", e); + Error::ChannelSplicingFailed + })?; + + // The fee for our contribution is paid from the same on-chain funds as the + // amount, and coin selection doesn't keep the anchor reserve aside. Now that the + // fee is known, check that what the contribution takes from our wallet, its + // inputs minus its change, still leaves the reserve in place. + let inputs_sats: u64 = contribution + .inputs() + .iter() + .map(|input| input.output().value.to_sat()) + .sum(); + let change_sats = + contribution.change_output().map_or(0, |output| output.value.to_sat()); + let required_funds_sats = inputs_sats.saturating_sub(change_sats); + if required_funds_sats > spendable_amount_sats { + log_error!( + self.logger, + "Unable to splice-in due to insufficient funds. Available: {}sats, Required: {}sats (including fee)", + spendable_amount_sats, + required_funds_sats, + ); + + // Return what coin selection set aside for the contribution we drop. + let inputs = + contribution.inputs().iter().map(|input| input.outpoint()).collect(); + let outputs = contribution.change_output().cloned().into_iter().collect(); + if let Err(e) = self + .runtime + .block_on(self.wallet.release_inputs_and_outputs(inputs, outputs)) + { + log_error!( + self.logger, + "Failed to release the inputs of a dropped splice contribution: {}", + e + ); + } + return Err(Error::InsufficientFunds); + } + + contribution + }, FundingAmount::Max => self.splice_in_with_all_contribution( funding_template, Vec::new(), @@ -2152,6 +2197,10 @@ impl Node { /// pending splice that requires a higher feerate to be replaced, or when the counterparty /// initiates a splice concurrently and our contribution is added to theirs. /// + /// The fee for our contribution is paid from the same on-chain funds as `splice_amount_sats`, + /// so both together must fit within [`BalanceDetails::spendable_onchain_balance_sats`], which + /// excludes the anchor reserve. Otherwise, this fails with [`NodeError::InsufficientFunds`]. + /// /// # Experimental API /// /// This API is experimental. Currently, a splice-in will be marked as an outbound payment, but diff --git a/tests/integration_tests_rust.rs b/tests/integration_tests_rust.rs index 3443e300d5..1997571906 100644 --- a/tests/integration_tests_rust.rs +++ b/tests/integration_tests_rust.rs @@ -4080,6 +4080,85 @@ async fn run_rbf_splice_channel_test(confirm_original: bool) { node_b.stop().unwrap(); } +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn splice_in_fee_does_not_spend_anchor_reserve() { + let (bitcoind, electrsd) = setup_bitcoind_and_electrsd(); + let chain_source = random_chain_source(&bitcoind, &electrsd); + let (node_a, node_b) = setup_two_nodes(&chain_source, false, false); + + let premine_amount_sat = 1_000_000; + premine_and_distribute_funds( + &bitcoind.client, + &electrsd.client, + vec![ + node_a.onchain_payment().new_address().unwrap(), + node_b.onchain_payment().new_address().unwrap(), + ], + Amount::from_sat(premine_amount_sat), + ) + .await; + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); + + // node_a funds the channel, so node_b's premine stays untouched for the splice-in. + open_channel(&node_a, &node_b, 500_000, false, &electrsd).await; + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await; + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); + + expect_channel_ready_event!(node_a, node_b.node_id()); + let user_channel_id_b = expect_channel_ready_event!(node_b, node_a.node_id()); + + let anchor_reserve_sat = 25_000; + let balances = node_b.list_balances(); + assert_eq!(balances.total_anchor_channels_reserve_sats, anchor_reserve_sat); + assert_eq!(balances.total_onchain_balance_sats, premine_amount_sat); + + // The amount fits in what we can spend next to the anchor reserve, but at 50 sat/vB the splice + // transaction's fee of about 12,500 sats would have to come out of the reserve. + let splice_amount_sat = balances.spendable_onchain_balance_sats - 5_000; + let fee_rate = FeeRate::from_sat_per_vb(50).unwrap(); + assert_eq!( + Err(NodeError::InsufficientFunds), + node_b.splice_in( + &user_channel_id_b, + node_a.node_id(), + splice_amount_sat, + Some(fee_rate.into()) + ) + ); + + // Coin selection locked the inputs of the rejected contribution, which must be released again. + assert_eq!( + node_b.list_balances().spendable_onchain_balance_sats, + balances.spendable_onchain_balance_sats + ); + + // At the ~1 sat/vB the estimator yields on regtest, the fee fits next to the reserve. + node_b.splice_in(&user_channel_id_b, node_a.node_id(), splice_amount_sat, None).unwrap(); + let txo = expect_splice_negotiated_event!(node_b, node_a.node_id()); + wait_for_classified_funding_payment(&node_b, txo.txid).await; + wait_for_tx(&electrsd.client, txo.txid).await; + + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await; + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); + + expect_channel_ready_event!(node_a, node_b.node_id()); + expect_channel_ready_event!(node_b, node_a.node_id()); + + let balances = node_b.list_balances(); + assert!( + balances.total_onchain_balance_sats >= anchor_reserve_sat, + "the splice transaction left {}sats on-chain, less than the {}sats anchor reserve", + balances.total_onchain_balance_sats, + anchor_reserve_sat, + ); + + node_a.stop().unwrap(); + node_b.stop().unwrap(); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn splice_in_with_all_bump_fee_retains_anchor_reserve() { let default_reserve_sats = AnchorChannelsConfig::default().per_channel_reserve_sats; From 8880ed2576660f80908bf41dc88cfc2748e47f55 Mon Sep 17 00:00:00 2001 From: Shubham Kumar Date: Wed, 18 Nov 2026 13:00:10 +0530 Subject: [PATCH 3/4] Move the splice contribution reserve check into its own method Fee bumps of a pending splice are about to need the check that `splice_in_inner` runs once LDK has built our contribution: that what it takes from our wallet, fee included, leaves the anchor reserve in place. A bump's contribution replaces the pending one, though, so only what it takes beyond that one should count. Move the check into `check_sufficient_onchain_funds_for_contribution`, which takes the replaced contribution as `prior_contribution`. On rejection it releases what LDK reports through `reserved_inputs` and `reserved_outputs`, i.e. only what the contribution reserved for itself, never what it inherited from the pending splice. A splice-in has no prior contribution and inherits nothing, so its behavior is unchanged. Part of #1166. Developed with assistance from Claude Code. --- src/lib.rs | 94 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 57 insertions(+), 37 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 30eadfe21e..29af9708b5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1650,6 +1650,57 @@ impl Node { Ok(spendable_amount_sats) } + /// Checks, now that the fee of `contribution` is known, that it leaves the anchor reserve in + /// place. Otherwise, releases what it reserved for itself and fails with + /// [`Error::InsufficientFunds`]. + /// + /// What a contribution takes from our wallet is its inputs minus its change, fee included. + /// When it replaces `prior_contribution`, only what it takes beyond that one counts. This must + /// fit within `spendable_amount_sats`, the spendable balance read before `contribution` was + /// built, as building it locks the inputs it selects. + fn check_sufficient_onchain_funds_for_contribution( + &self, contribution: FundingContribution, prior_contribution: Option<&FundingContribution>, + spendable_amount_sats: u64, + ) -> Result { + let action_str = + if prior_contribution.is_some() { "bump the splice fee" } else { "splice-in" }; + let wallet_funds_sats = |contribution: &FundingContribution| { + let inputs_sats: u64 = + contribution.inputs().iter().map(|input| input.output().value.to_sat()).sum(); + let change_sats = + contribution.change_output().map_or(0, |output| output.value.to_sat()); + inputs_sats.saturating_sub(change_sats) + }; + let required_funds_sats = wallet_funds_sats(&contribution) + .saturating_sub(prior_contribution.map_or(0, wallet_funds_sats)); + if required_funds_sats <= spendable_amount_sats { + return Ok(contribution); + } + + log_error!( + self.logger, + "Unable to {} due to insufficient funds. Available: {}sats, Required: {}sats (including fee)", + action_str, + spendable_amount_sats, + required_funds_sats, + ); + + // Return what was set aside for the contribution we drop, but nothing it inherited from a + // pending splice: that splice's transaction may still confirm. + let inputs = contribution.reserved_inputs().map(|input| input.outpoint()).collect(); + let outputs = contribution.reserved_outputs().cloned().collect(); + if let Err(e) = + self.runtime.block_on(self.wallet.release_inputs_and_outputs(inputs, outputs)) + { + log_error!( + self.logger, + "Failed to release the inputs of a dropped splice contribution: {}", + e + ); + } + Err(Error::InsufficientFunds) + } + /// Connect to a node and open a new unannounced channel. /// /// To open an announced channel, see [`Node::open_announced_channel`]. @@ -1980,43 +2031,12 @@ impl Node { })?; // The fee for our contribution is paid from the same on-chain funds as the - // amount, and coin selection doesn't keep the anchor reserve aside. Now that the - // fee is known, check that what the contribution takes from our wallet, its - // inputs minus its change, still leaves the reserve in place. - let inputs_sats: u64 = contribution - .inputs() - .iter() - .map(|input| input.output().value.to_sat()) - .sum(); - let change_sats = - contribution.change_output().map_or(0, |output| output.value.to_sat()); - let required_funds_sats = inputs_sats.saturating_sub(change_sats); - if required_funds_sats > spendable_amount_sats { - log_error!( - self.logger, - "Unable to splice-in due to insufficient funds. Available: {}sats, Required: {}sats (including fee)", - spendable_amount_sats, - required_funds_sats, - ); - - // Return what coin selection set aside for the contribution we drop. - let inputs = - contribution.inputs().iter().map(|input| input.outpoint()).collect(); - let outputs = contribution.change_output().cloned().into_iter().collect(); - if let Err(e) = self - .runtime - .block_on(self.wallet.release_inputs_and_outputs(inputs, outputs)) - { - log_error!( - self.logger, - "Failed to release the inputs of a dropped splice contribution: {}", - e - ); - } - return Err(Error::InsufficientFunds); - } - - contribution + // amount, and coin selection doesn't keep the anchor reserve aside. + self.check_sufficient_onchain_funds_for_contribution( + contribution, + None, + spendable_amount_sats, + )? }, FundingAmount::Max => self.splice_in_with_all_contribution( funding_template, From 94aa36a54f4dd89fb3b81423c548b7e31dbf3998 Mon Sep 17 00:00:00 2001 From: Shubham Kumar Date: Wed, 18 Nov 2026 14:30:39 +0530 Subject: [PATCH 4/4] Check the anchor reserve when fee-bumping a splice `bump_channel_funding_fee` didn't check the anchor reserve at all. A bump of an exact splice-in pays the higher fee from our wallet: LDK shrinks the pending contribution's change or, past its maximum feerate, re-runs coin selection. A bump of a splice-out whose channel balance can't cover the higher fee falls back to funding the whole withdrawal and fees from our wallet. Neither keeps the reserve aside. Read the spendable balance before LDK builds the replacement, as coin selection locks the inputs it picks. Then check that what the replacement takes from our wallet beyond the pending contribution fits in it, as the on-chain `bump_fee_rbf` does for its additional fee. If it doesn't, release what the replacement reserved and fail with `InsufficientFunds`. Bumps of `splice_in_with_all` are unaffected: an in-place bump takes nothing more from the wallet, and a rebuild already keeps the reserve as its own output. Part of #1166. Developed with assistance from Claude Code. --- CHANGELOG.md | 5 + src/lib.rs | 28 +++- tests/integration_tests_rust.rs | 247 ++++++++++++++++++++++++++++++++ 3 files changed, 277 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a441af5c8f..ad18946c57 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -121,6 +121,11 @@ - Splicing in an exact amount now accounts for the fee of our contribution to the splice transaction when checking the anchor reserve, and fails with `NodeError::InsufficientFunds` if paying it would spend part of the reserve. Previously, the fee could be paid from the reserve. +- `Node::bump_channel_funding_fee` now checks the anchor reserve as well, and fails with + `NodeError::InsufficientFunds` if what the replacement takes from our on-chain funds beyond + the pending splice would spend part of the reserve. Previously, the reserve could pay the higher + fee of a splice-in, or fund a splice-out's withdrawal when the channel balance couldn't cover the + higher fee. # 0.7.0 - Dec. 3, 2025 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. diff --git a/src/lib.rs b/src/lib.rs index 29af9708b5..976b0ed4b7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2338,8 +2338,9 @@ impl Node { /// /// [`Node::bump_channel_funding_fee`] preserves the destination output value, including for /// maximum withdrawals. If the channel cannot cover the higher fee, it may fund the entire - /// output and fees from the on-chain wallet instead, leaving the channel balance unwithdrawn. - /// It does not reduce the destination output to pay the additional fee. + /// output and fees from the on-chain wallet instead, leaving the channel balance unwithdrawn, + /// or fail with [`NodeError::InsufficientFunds`] if that would spend part of the anchor + /// reserve. It does not reduce the destination output to pay the additional fee. /// /// Success means the contribution was submitted, not that the splice has completed. Monitor /// [`Event::SpliceNegotiated`] or [`Event::SpliceNegotiationFailed`] for the negotiation result, @@ -2467,6 +2468,11 @@ impl Node { /// fees, leaving the channel balance unwithdrawn. This also applies to withdrawals created /// with [`Node::splice_out_max`]; the output is not reduced to cover the higher fee. /// + /// What the replacement takes from our on-chain funds beyond what the pending splice takes, + /// such as the higher fee of a splice-in or a withdrawal funded by wallet inputs, must fit + /// within [`BalanceDetails::spendable_onchain_balance_sats`], which excludes the anchor + /// reserve. Otherwise, this fails with [`NodeError::InsufficientFunds`]. + /// /// A splice of all on-chain funds (see [`Node::splice_in_with_all`]) has no amount to preserve: /// the bump is paid by adding less to the channel, or, if the pending splice's maximum feerate /// does not allow that or less than dust would be left to add, the splice is rebuilt from all @@ -2518,6 +2524,14 @@ impl Node { return Err(Error::ChannelSplicingFailed); }; + // Coin selection for the replacement, if LDK needs one, locks the inputs it picks, which + // takes them off the spendable balance, so keep the balance from before it to check the + // replacement against. + let cur_anchor_reserve_sats = + total_anchor_channels_reserve_sats(&self.channel_manager, &self.config); + let spendable_amount_sats = + self.wallet.get_spendable_amount_sats(cur_anchor_reserve_sats)?; + let rbf_template = funding_template.clone(); let prior_value_added_sats = funding_template .prior_contribution() @@ -2546,7 +2560,15 @@ impl Node { }, }; let contribution = match adjusted { - Some(contribution) => contribution, + // The replacement may take more from our wallet than the pending splice does: a + // splice-in pays the higher fee from its change or newly selected coins, and a + // splice-out the channel can't pay it for is funded from our wallet entirely. + // Neither keeps the anchor reserve aside. + Some(contribution) => self.check_sufficient_onchain_funds_for_contribution( + contribution, + funding_template.prior_contribution(), + spendable_amount_sats, + )?, // The pending splice spends manually selected inputs, as a splice-in of all funds // does, so replace it with one built the same way from all confirmed funds: its // inputs and any coins confirmed since. diff --git a/tests/integration_tests_rust.rs b/tests/integration_tests_rust.rs index 1997571906..eb571cb328 100644 --- a/tests/integration_tests_rust.rs +++ b/tests/integration_tests_rust.rs @@ -4159,6 +4159,253 @@ async fn splice_in_fee_does_not_spend_anchor_reserve() { node_b.stop().unwrap(); } +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn splice_in_bump_fee_does_not_spend_anchor_reserve() { + let (bitcoind, electrsd) = setup_bitcoind_and_electrsd_for_splice_rbf(); + let chain_source = random_chain_source(&bitcoind, &electrsd); + let (node_a, node_b) = setup_two_nodes(&chain_source, false, false); + + premine_and_distribute_funds( + &bitcoind.client, + &electrsd.client, + vec![ + node_a.onchain_payment().new_address().unwrap(), + node_b.onchain_payment().new_address().unwrap(), + ], + Amount::from_sat(1_000_000), + ) + .await; + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); + + // node_a funds the channel, so node_b's premine stays untouched for the splice-in. + open_channel(&node_a, &node_b, 500_000, false, &electrsd).await; + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await; + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); + + expect_channel_ready_event!(node_a, node_b.node_id()); + let user_channel_id_b = expect_channel_ready_event!(node_b, node_a.node_id()); + + let anchor_reserve_sat = 25_000; + let balances = node_b.list_balances(); + assert_eq!(balances.total_anchor_channels_reserve_sats, anchor_reserve_sat); + + // At 50 sat/vB the splice transaction's fee is about 12,500 sats, so splicing in all but 15,500 + // sats of what we can spend next to the anchor reserve leaves about 3,000 sats of its change + // spendable. + let fee_rate = FeeRate::from_sat_per_vb(50).unwrap(); + let splice_amount_sat = balances.spendable_onchain_balance_sats - 15_500; + node_b + .splice_in(&user_channel_id_b, node_a.node_id(), splice_amount_sat, Some(fee_rate.into())) + .unwrap(); + let original_txo = expect_splice_negotiated_event!(node_b, node_a.node_id()); + wait_for_tx(&electrsd.client, original_txo.txid).await; + wait_for_classified_funding_payment(&node_b, original_txo.txid).await; + let original_tx = electrsd.client.transaction_get(&original_txo.txid).unwrap(); + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); + + // A bump to 1.5 times the feerate, the most the splice's change may pay for, costs half its fee + // more, which would take part of the anchor reserve. A bump to the RBF minimum, about 4% more, + // fits. + let original_fee_sat = + funding_payment(&node_b, original_txo.txid).fee_paid_msat.expect("splice has a fee") / 1000; + let spendable_sat = node_b.list_balances().spendable_onchain_balance_sats; + assert!( + spendable_sat < original_fee_sat / 2 && spendable_sat > original_fee_sat / 10, + "{spendable_sat} sats spendable after a splice fee of {original_fee_sat} sats" + ); + + let max_fee_rate = FeeRate::from_sat_per_kwu(fee_rate.to_sat_per_kwu() * 3 / 2); + assert_eq!( + node_b.bump_channel_funding_fee( + &user_channel_id_b, + node_a.node_id(), + Some(max_fee_rate.into()) + ), + Err(NodeError::InsufficientFunds) + ); + assert_eq!(node_b.list_balances().spendable_onchain_balance_sats, spendable_sat); + + // Our feerate is raised to the RBF minimum. + node_b + .bump_channel_funding_fee(&user_channel_id_b, node_a.node_id(), Some(fee_rate.into())) + .unwrap(); + let rbf_txo = expect_splice_negotiated_event!(node_b, node_a.node_id()); + assert_ne!(rbf_txo, original_txo, "RBF should produce a different funding txo"); + wait_for_tx(&electrsd.client, rbf_txo.txid).await; + wait_for_classified_funding_payment(&node_b, rbf_txo.txid).await; + + // The bump was paid from the splice's change, spending the same inputs. + let rbf_tx = electrsd.client.transaction_get(&rbf_txo.txid).unwrap(); + let sorted_inputs = |tx: &Transaction| { + let mut inputs: Vec<_> = tx.input.iter().map(|input| input.previous_output).collect(); + inputs.sort(); + inputs + }; + assert_eq!(sorted_inputs(&rbf_tx), sorted_inputs(&original_tx)); + + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await; + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); + + expect_channel_ready_event!(node_a, node_b.node_id()); + expect_channel_ready_event!(node_b, node_a.node_id()); + assert_eq!(node_b.list_channels()[0].funding_txo, Some(rbf_txo)); + + let balances = node_b.list_balances(); + assert!( + balances.total_onchain_balance_sats >= anchor_reserve_sat, + "the splice transaction left {}sats on-chain, less than the {}sats anchor reserve", + balances.total_onchain_balance_sats, + anchor_reserve_sat, + ); + + node_a.stop().unwrap(); + node_b.stop().unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn splice_out_bump_fee_does_not_spend_anchor_reserve() { + let (bitcoind, electrsd) = setup_bitcoind_and_electrsd_for_splice_rbf(); + let chain_source = random_chain_source(&bitcoind, &electrsd); + let (node_a, node_b) = setup_two_nodes(&chain_source, false, false); + + // node_b needs on-chain funds of its own to accept an anchor channel. + premine_and_distribute_funds( + &bitcoind.client, + &electrsd.client, + vec![ + node_a.onchain_payment().new_address().unwrap(), + node_b.onchain_payment().new_address().unwrap(), + ], + Amount::from_sat(1_000_000), + ) + .await; + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); + + // Funding the channel with all of its funds leaves node_a with only the anchor reserve + // on-chain. + open_channel_with_all(&node_a, &node_b, false, &electrsd).await; + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await; + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); + + let user_channel_id_a = expect_channel_ready_event!(node_a, node_b.node_id()); + expect_channel_ready_event!(node_b, node_a.node_id()); + + let anchor_reserve_sat = 25_000; + assert_eq!(node_a.list_balances().total_anchor_channels_reserve_sats, anchor_reserve_sat); + + // Give node_a a coin half the anchor reserve short of all the channel lets us withdraw, fee + // included. Together with the reserve, it can fund the withdrawal from the wallet, but only by + // spending half of the reserve. + let withdrawal_budget_sat = node_a.list_channels()[0].next_splice_out_maximum_sat; + distribute_funds_unconfirmed( + &bitcoind.client, + &electrsd.client, + vec![node_a.onchain_payment().new_address().unwrap()], + Amount::from_sat(withdrawal_budget_sat - anchor_reserve_sat / 2), + ) + .await; + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 1).await; + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); + + // Withdrawing the maximum leaves no channel balance for a higher fee, so a bump funds the + // withdrawal and fees from node_a's wallet instead. + let fee_rate = FeeRate::from_sat_per_kwu(1_000); + let address = bitcoind.client.new_address().expect("failed to get new address"); + node_a + .splice_out_max(&user_channel_id_a, node_b.node_id(), &address, Some(fee_rate.into())) + .unwrap(); + let original_txo = expect_splice_negotiated_event!(node_a, node_b.node_id()); + wait_for_tx(&electrsd.client, original_txo.txid).await; + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); + + let original_tx = electrsd.client.transaction_get(&original_txo.txid).unwrap(); + assert_eq!(original_tx.input.len(), 1, "the splice-out spent wallet inputs"); + let withdrawal = original_tx + .output + .iter() + .find(|output| output.script_pubkey == address.script_pubkey()) + .expect("the splice-out pays the address") + .clone(); + let spendable_sat = node_a.list_balances().spendable_onchain_balance_sats; + assert!( + spendable_sat < withdrawal.value.to_sat(), + "{spendable_sat} sats spendable fund a withdrawal of {} sats", + withdrawal.value.to_sat() + ); + + let bump_fee_rate = FeeRate::from_sat_per_kwu(1_200); + assert_eq!( + node_a.bump_channel_funding_fee( + &user_channel_id_a, + node_b.node_id(), + Some(bump_fee_rate.into()) + ), + Err(NodeError::InsufficientFunds) + ); + + // Coin selection locked the inputs of the rejected replacement, which must be released again. + assert_eq!(node_a.list_balances().spendable_onchain_balance_sats, spendable_sat); + + // Once another coin confirms, while the splice transaction stays in the mempool, the same bump + // fits next to the reserve. + let coin_txid = distribute_funds_unconfirmed( + &bitcoind.client, + &electrsd.client, + vec![node_a.onchain_payment().new_address().unwrap()], + Amount::from_sat(anchor_reserve_sat), + ) + .await; + let coin_tx_hex: String = bitcoind + .client + .call::("getrawtransaction", &[json!(coin_txid.to_string())]) + .unwrap() + .as_str() + .unwrap() + .to_string(); + mine_block_with(&bitcoind, &electrsd, &[coin_tx_hex]).await; + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); + + node_a + .bump_channel_funding_fee(&user_channel_id_a, node_b.node_id(), Some(bump_fee_rate.into())) + .unwrap(); + let rbf_txo = expect_splice_negotiated_event!(node_a, node_b.node_id()); + assert_ne!(rbf_txo, original_txo, "RBF should produce a different funding txo"); + wait_for_tx(&electrsd.client, rbf_txo.txid).await; + + // The replacement pays the same withdrawal, now from node_a's wallet. + let rbf_tx = electrsd.client.transaction_get(&rbf_txo.txid).unwrap(); + assert!(rbf_tx.input.len() > 1, "the replacement spent no wallet inputs"); + assert!(rbf_tx.output.contains(&withdrawal)); + + generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await; + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); + + expect_channel_ready_event!(node_a, node_b.node_id()); + expect_channel_ready_event!(node_b, node_a.node_id()); + assert_eq!(node_a.list_channels()[0].funding_txo, Some(rbf_txo)); + + let balances = node_a.list_balances(); + assert!( + balances.total_onchain_balance_sats >= anchor_reserve_sat, + "the splice transaction left {}sats on-chain, less than the {}sats anchor reserve", + balances.total_onchain_balance_sats, + anchor_reserve_sat, + ); + + node_a.stop().unwrap(); + node_b.stop().unwrap(); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn splice_in_with_all_bump_fee_retains_anchor_reserve() { let default_reserve_sats = AnchorChannelsConfig::default().per_channel_reserve_sats;