diff --git a/CHANGELOG.md b/CHANGELOG.md index ef50da0a28..5f1f8d9769 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -118,6 +118,15 @@ 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, including the higher fee of up to 1.5 times the + feerate we may still pay, and fails with `NodeError::ChannelSplicingFailed` if paying it could + 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::ChannelSplicingFailed` if the replacement takes more from our on-chain funds than + the pending splice and could 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 97a179c95f..6c3941134a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1614,8 +1614,13 @@ impl Node { }; 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).unwrap_or(0); + let spendable_amount_sats = if new_channel_with_funding_fee_rate.is_some() { + self.wallet.get_spendable_amount_sats(cur_anchor_reserve_sats).unwrap_or(0) + } else { + // A splice-in only spends confirmed outputs, and the check of its built contribution + // leaves out unconfirmed change, so check against the same funds before coin selection. + self.wallet.get_confirmed_unlocked_amount_sats().saturating_sub(cur_anchor_reserve_sats) + }; if spendable_amount_sats < amount_sats { log_error!( @@ -1662,6 +1667,65 @@ impl Node { Ok(()) } + /// Checks, now that the fee of `contribution` is known, that it leaves the anchor reserve in + /// place. Otherwise, fails with [`Error::ChannelSplicingFailed`], after returning the inputs + /// and outputs `contribution` reserved for itself to the wallet via + /// `Wallet::release_inputs_and_outputs`. Those it inherited from a pending splice stay + /// reserved. + /// + /// Once the transaction of `contribution` confirms, we hold `confirmed_unlocked_sats`, read + /// before `contribution` was built as building it locks the inputs it selects, plus the inputs + /// of `prior_contribution`, the contribution it replaces, which are ours again unless + /// `contribution` spends them too. What `contribution` may take from our wallet at most, see + /// [`max_wallet_spend_sats`], must leave the anchor reserve of those funds, unless it takes no + /// more than `prior_contribution` already may. + fn check_sufficient_onchain_funds_for_contribution( + &self, contribution: FundingContribution, prior_contribution: Option<&FundingContribution>, + confirmed_unlocked_sats: u64, + ) -> Result { + let required_funds_sats = max_wallet_spend_sats(&contribution); + if required_funds_sats <= prior_contribution.map_or(0, max_wallet_spend_sats) { + return Ok(contribution); + } + + let prior_inputs_sats: u64 = prior_contribution.map_or(0, |prior_contribution| { + prior_contribution.inputs().iter().map(|input| input.output().value.to_sat()).sum() + }); + let cur_anchor_reserve_sats = + total_anchor_channels_reserve_sats(&self.channel_manager, &self.config); + let available_funds_sats = confirmed_unlocked_sats + .saturating_add(prior_inputs_sats) + .saturating_sub(cur_anchor_reserve_sats); + if required_funds_sats <= available_funds_sats { + return Ok(contribution); + } + + let action_str = + if prior_contribution.is_some() { "bump the splice fee" } else { "splice-in" }; + log_error!( + self.logger, + "Unable to {} due to insufficient funds. Available: {}sats, Required: {}sats (including fees)", + action_str, + available_funds_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::ChannelSplicingFailed) + } + /// Connect to a node and open a new unannounced channel. /// /// To open an announced channel, see [`Node::open_announced_channel`]. @@ -1942,10 +2006,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) @@ -1973,18 +2033,35 @@ 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 } => { + // Only checked here, so that a pending splice of ours, whose inputs are locked, + // fails above as such rather than for lack of funds. + self.check_sufficient_onchain_funds(amount_sats, &counterparty_node_id, None)?; + + // Coin selection locks the inputs it picks, so read our funds before it. + let confirmed_unlocked_sats = self.wallet.get_confirmed_unlocked_amount_sats(); + + 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. + self.check_sufficient_onchain_funds_for_contribution( + contribution, + None, + confirmed_unlocked_sats, + )? + }, FundingAmount::Max => self.splice_in_with_all_contribution( funding_template, Vec::new(), @@ -2164,6 +2241,12 @@ 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`. + /// Together with the most we may pay in fees, as described above, the amount must fit within our + /// confirmed on-chain funds beyond the anchor reserve. If the amount alone doesn't, this fails + /// with [`NodeError::InsufficientFunds`], and if the fees don't, with + /// [`NodeError::ChannelSplicingFailed`]. + /// /// # Experimental API /// /// This API is experimental. Currently, a splice-in will be marked as an outbound payment, but @@ -2281,8 +2364,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::ChannelSplicingFailed`] 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, @@ -2410,6 +2494,12 @@ 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. /// + /// The replacement may take more from our on-chain funds than the pending splice, such as for + /// the higher fee of a splice-in or a withdrawal funded by wallet inputs. If so, our confirmed + /// on-chain funds must still cover the anchor reserve once it confirms, even at the most we may + /// pay in fees as described below. Otherwise, this fails with + /// [`NodeError::ChannelSplicingFailed`]. + /// /// 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 @@ -2461,6 +2551,10 @@ impl Node { return Err(Error::ChannelSplicingFailed); }; + // Coin selection for the replacement, if LDK needs one, locks the inputs it picks, so + // read our funds before it. + let confirmed_unlocked_sats = self.wallet.get_confirmed_unlocked_amount_sats(); + let rbf_template = funding_template.clone(); let prior_value_added_sats = funding_template .prior_contribution() @@ -2489,7 +2583,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 whose channel balance can't cover it 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(), + confirmed_unlocked_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. @@ -2947,6 +3049,41 @@ fn max_splice_out_output( Ok(output) } +/// The most `contribution` may take from our on-chain wallet once its transaction confirms: its +/// inputs, less the least change it may return. +/// +/// After we built `contribution`, LDK may still raise its fee up to its maximum feerate, when our +/// contribution joins a splice the counterparty initiated or the RBF minimum feerate rises. It +/// pays the difference from the change, and drops the change entirely if less than dust would be +/// left. +fn max_wallet_spend_sats(contribution: &FundingContribution) -> u64 { + let inputs_sats: u64 = + contribution.inputs().iter().map(|input| input.output().value.to_sat()).sum(); + let Some(change_output) = contribution.change_output() else { + return inputs_sats; + }; + + // At the same weight, the fee scales with the feerate, and as the acceptor we pay for less + // weight. Fees are rounded up, so this is at least the increase LDK may apply. + let fee_sats = contribution.estimated_fee().to_sat(); + let feerate_sat_per_kwu = contribution.feerate().to_sat_per_kwu(); + let max_feerate_sat_per_kwu = contribution.max_feerate().to_sat_per_kwu(); + let max_fee_increase_sats = if feerate_sat_per_kwu == 0 { + 0 + } else { + fee_sats + .saturating_mul(max_feerate_sat_per_kwu.saturating_sub(feerate_sat_per_kwu)) + .div_ceil(feerate_sat_per_kwu) + }; + + let dust_limit_sats = change_output.script_pubkey.minimal_non_dust().to_sat(); + let min_change_sats = match change_output.value.to_sat().checked_sub(max_fee_increase_sats) { + Some(change_sats) if change_sats >= dust_limit_sats => change_sats, + _ => 0, + }; + inputs_sats.saturating_sub(min_change_sats) +} + impl Drop for Node { fn drop(&mut self) { let _ = self.stop(); @@ -3182,4 +3319,76 @@ mod tests { assert_eq!(new.latest_pathfinding_scores_sync_timestamp, Some(1_300)); assert_eq!(new.latest_node_announcement_broadcast_timestamp, Some(2_000)); } + + fn test_p2wpkh_script(seed: u8) -> bitcoin::ScriptBuf { + use bitcoin::hashes::Hash; + bitcoin::ScriptBuf::new_p2wpkh(&bitcoin::WPubkeyHash::from_byte_array([seed; 20])) + } + + /// A contribution spending a 100,000 sat coin, with the given change, whose fee of 1,001 sats + /// at 1,000 sat/kwu may rise up to `max_feerate_sat_per_kwu`. + fn test_splice_in_contribution( + change_sat: Option, max_feerate_sat_per_kwu: u64, + ) -> FundingContribution { + let prevtx = bitcoin::Transaction { + version: bitcoin::transaction::Version::TWO, + lock_time: bitcoin::absolute::LockTime::ZERO, + input: vec![bitcoin::TxIn::default()], + output: vec![bitcoin::TxOut { + value: Amount::from_sat(100_000), + script_pubkey: test_p2wpkh_script(1), + }], + }; + let change_output = change_sat.map(|change_sat| bitcoin::TxOut { + value: Amount::from_sat(change_sat), + script_pubkey: test_p2wpkh_script(2), + }); + crate::payment::pending_payment_store::test_funding_contribution_with_parts( + 1_001, + 1_000, + max_feerate_sat_per_kwu, + &[prevtx], + &[], + change_output.as_ref(), + ) + } + + #[test] + fn max_wallet_spend_without_change_is_all_inputs() { + assert_eq!(max_wallet_spend_sats(&test_splice_in_contribution(None, 1_500)), 100_000); + } + + #[test] + fn max_wallet_spend_holds_back_change_for_a_higher_fee() { + // At 1.5 times the feerate, the fee of 1,001 sats may rise by 500.5 sats, rounded up. + assert_eq!( + max_wallet_spend_sats(&test_splice_in_contribution(Some(10_000), 1_500)), + 100_000 - 10_000 + 501 + ); + // Without room to raise the feerate, all of the change comes back. + assert_eq!( + max_wallet_spend_sats(&test_splice_in_contribution(Some(10_000), 1_000)), + 100_000 - 10_000 + ); + } + + #[test] + fn max_wallet_spend_counts_change_left_below_dust_as_spent() { + let dust_limit_sat = test_p2wpkh_script(2).minimal_non_dust().to_sat(); + // Change left at the dust limit after the higher fee is kept. + assert_eq!( + max_wallet_spend_sats(&test_splice_in_contribution(Some(501 + dust_limit_sat), 1_500)), + 100_000 - dust_limit_sat + ); + // Below it, the change is dropped and spent along with the inputs. + assert_eq!( + max_wallet_spend_sats(&test_splice_in_contribution( + Some(501 + dust_limit_sat - 1), + 1_500 + )), + 100_000 + ); + // So is change that can't even cover the higher fee. + assert_eq!(max_wallet_spend_sats(&test_splice_in_contribution(Some(400), 1_500)), 100_000); + } } diff --git a/src/payment/pending_payment_store.rs b/src/payment/pending_payment_store.rs index e234412657..fc603e616b 100644 --- a/src/payment/pending_payment_store.rs +++ b/src/payment/pending_payment_store.rs @@ -286,18 +286,18 @@ impl From<&PendingPaymentDetails> for PendingPaymentDetailsUpdate { pub(crate) fn test_funding_contribution_with_outputs( estimated_fee_sat: u64, feerate: u64, outputs: &[bitcoin::TxOut], ) -> lightning::ln::funding::FundingContribution { - test_funding_contribution_with_parts(estimated_fee_sat, feerate, &[], outputs, None) + test_funding_contribution_with_parts(estimated_fee_sat, feerate, feerate, &[], outputs, None) } /// Builds a [`FundingContribution`] for tests from its parts: the given estimated fee, an input /// spending output 0 — which must be P2WPKH — of each given previous transaction, the given -/// contributed outputs and change output, and the given input-selection feerate (also used as -/// the maximum), with the is-splice flag set. +/// contributed outputs and change output, and the given input-selection and maximum feerates, +/// with the is-splice flag set. /// /// [`FundingContribution`]: lightning::ln::funding::FundingContribution #[cfg(test)] pub(crate) fn test_funding_contribution_with_parts( - estimated_fee_sat: u64, feerate: u64, prevtxs: &[bitcoin::Transaction], + estimated_fee_sat: u64, feerate: u64, max_feerate: u64, prevtxs: &[bitcoin::Transaction], outputs: &[bitcoin::TxOut], change_output: Option<&bitcoin::TxOut>, ) -> lightning::ln::funding::FundingContribution { use lightning::util::ser::{BigSize, Writeable}; @@ -340,7 +340,7 @@ pub(crate) fn test_funding_contribution_with_parts( records.extend_from_slice(&[9, 8]); // (9, feerate) records.extend_from_slice(&feerate.to_be_bytes()); records.extend_from_slice(&[11, 8]); // (11, max_feerate) - records.extend_from_slice(&feerate.to_be_bytes()); + records.extend_from_slice(&max_feerate.to_be_bytes()); records.extend_from_slice(&[13, 1, 1]); // (13, is_splice: true) let mut tlv_bytes = Vec::new(); // BigSize length prefix over the TLV records above. diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index 563da245a5..ab8f5b812b 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -2322,6 +2322,24 @@ impl Wallet { self.get_balances(total_anchor_channels_reserve_sats).map(|(_, s)| s) } + /// Returns the value of our confirmed outputs that are neither spent nor locked for a pending + /// funding transaction. + /// + /// Unlike [`Self::get_spendable_amount_sats`], this leaves out unconfirmed change. A pending + /// splice's change is only counted there once wallet sync has seen its transaction, while its + /// inputs are locked from the start. + pub(crate) fn get_confirmed_unlocked_amount_sats(&self) -> u64 { + let locked_wallet = self.inner.lock().expect("lock"); + locked_wallet + .list_unspent() + .filter(|utxo| { + utxo.chain_position.is_confirmed() + && !locked_wallet.is_outpoint_locked(utxo.outpoint) + }) + .map(|utxo| utxo.txout.value.to_sat()) + .sum() + } + fn build_drain_psbt( &self, locked_wallet: &mut PersistedWallet, drain_script: ScriptBuf, cur_anchor_reserve_sats: u64, fee_rate: FeeRate, @@ -11645,6 +11663,7 @@ mod tests { let contribution = test_funding_contribution_with_parts( 300, 253, + 253, std::slice::from_ref(&prevtx), &[], None, @@ -13753,6 +13772,56 @@ mod tests { assert_eq!(selected_outpoints(&third), first_outpoints); } + /// The anchor reserve check of a splice must not depend on whether wallet sync has seen the + /// splice transaction yet, so neither may the funds it checks against. + #[tokio::test] + async fn confirmed_unlocked_amount_does_not_depend_on_seeing_a_splice() { + let store: Arc = Arc::new(DynStoreWrapper(InMemoryStore::new())); + let wallet = new_test_wallet(store, false).await; + insert_confirmed_tx(&wallet, wallet_paying_tx(&wallet, 1), 1); + insert_confirmed_tx(&wallet, wallet_paying_tx(&wallet, 2), 2); + assert_eq!(wallet.get_confirmed_unlocked_amount_sats(), 180_000); + + // Coin selection for a splice locks the inputs it picks. + let payment = TxOut { + value: Amount::from_sat(50_000), + script_pubkey: ScriptBuf::new_p2wpkh(&WPubkeyHash::from_byte_array([1; 20])), + }; + let fee_rate = FeeRate::from_sat_per_kwu(250); + let selection = + Wallet::select_confirmed_utxos(&wallet, Vec::new(), &[payment.clone()], fee_rate) + .await + .unwrap(); + let inputs_sats: u64 = + selection.confirmed_utxos.iter().map(|utxo| utxo.output().value.to_sat()).sum(); + let change_output = selection.change_output.clone().expect("the selection has change"); + let confirmed_unlocked_sats = wallet.get_confirmed_unlocked_amount_sats(); + assert_eq!(confirmed_unlocked_sats, 180_000 - inputs_sats); + let spendable_sats = wallet.get_spendable_amount_sats(0).unwrap(); + + // Once wallet sync sees the splice transaction, its inputs are spent rather than locked + // and its change counts as spendable, but our confirmed, unlocked funds stay the same. + let splice_tx = Transaction { + version: bitcoin::transaction::Version::TWO, + lock_time: LockTime::ZERO, + input: selection + .confirmed_utxos + .iter() + .map(|utxo| bitcoin::TxIn { + previous_output: utxo.outpoint(), + ..Default::default() + }) + .collect(), + output: vec![payment, change_output.clone()], + }; + insert_unconfirmed_tx(&wallet, splice_tx); + assert_eq!( + wallet.get_spendable_amount_sats(0).unwrap(), + spendable_sats + change_output.value.to_sat() + ); + assert_eq!(wallet.get_confirmed_unlocked_amount_sats(), confirmed_unlocked_sats); + } + #[tokio::test] async fn outpoints_locked_by_hand_are_kept_out_of_coin_selection() { let store: Arc = Arc::new(DynStoreWrapper(InMemoryStore::new())); diff --git a/tests/integration_tests_rust.rs b/tests/integration_tests_rust.rs index c831c98ade..62f0f0e750 100644 --- a/tests/integration_tests_rust.rs +++ b/tests/integration_tests_rust.rs @@ -4193,6 +4193,361 @@ 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::ChannelSplicingFailed), + 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 + ); + + // Leaving about 3,000 sats next to the fee isn't enough either: we may pay up to 1.5 times the + // feerate, about 6,250 sats more, from our change. + assert_eq!( + Err(NodeError::ChannelSplicingFailed), + node_b.splice_in( + &user_channel_id_b, + node_a.node_id(), + balances.spendable_onchain_balance_sats - 15_500, + Some(fee_rate.into()) + ) + ); + 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_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 22,000 + // sats of what we can spend next to the anchor reserve leaves about 9,500 sats of change beyond + // the reserve. That covers paying up to 1.5 times the feerate, about 6,250 sats more. + let fee_rate = FeeRate::from_sat_per_vb(50).unwrap(); + let splice_amount_sat = balances.spendable_onchain_balance_sats - 22_000; + 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; + + // node_b pays the whole fee of the splice transaction and gets its one other output as change. + let original_tx = electrsd.client.transaction_get(&original_txo.txid).unwrap(); + assert_eq!(original_tx.output.len(), 2); + let input_sat: u64 = original_tx + .input + .iter() + .map(|input| { + let prevout = input.previous_output; + electrsd.client.transaction_get(&prevout.txid).unwrap().output[prevout.vout as usize] + .value + .to_sat() + }) + .sum(); + let output_sat: u64 = original_tx.output.iter().map(|output| output.value.to_sat()).sum(); + let fee_sat = input_sat - output_sat; + let change_sat = original_tx.output[1 - original_txo.vout as usize].value.to_sat(); + + // A bump to 1.5 times the feerate pays half the fee more from the change, and may in turn pay + // up to 1.5 times its own feerate, which the change can't cover beyond the reserve. + assert!( + change_sat.saturating_sub(fee_sat * 5 / 4) < anchor_reserve_sat, + "{change_sat} sats of change after a splice fee of {fee_sat} sats" + ); + + // We don't sync node_b's wallet before bumping, so depending on the chain source it may not + // have seen the splice transaction yet. The check doesn't depend on that, see + // `confirmed_unlocked_amount_does_not_depend_on_seeing_a_splice`. + 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::ChannelSplicingFailed) + ); + + // At the original feerate, the bump is raised to the RBF minimum, which the room held back for + // paying up to 1.5 times the original feerate covers. + 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; + + // 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, less 1 sat of fee rounding, which is all of the reserve `list_balances` reports. + 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; + let balances = node_a.list_balances(); + assert_eq!(balances.total_onchain_balance_sats, anchor_reserve_sat - 1); + assert_eq!(balances.total_anchor_channels_reserve_sats, anchor_reserve_sat - 1); + + // 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::ChannelSplicingFailed) + ); + + // 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;