From e2ae2f9bce05b866e223eea55029875f61dfa04d Mon Sep 17 00:00:00 2001 From: Leo Nash Date: Thu, 9 Apr 2026 06:32:01 +0000 Subject: [PATCH 1/6] Run existing validation code against the candidate funding scope As a result, we now validate that both commitments retain at least one output under the new funding scope, which is crucial for zero-reserve channels. --- lightning/src/ln/channel.rs | 385 +++++++++++++++--------------------- 1 file changed, 155 insertions(+), 230 deletions(-) diff --git a/lightning/src/ln/channel.rs b/lightning/src/ln/channel.rs index e6397aefbcb..86b34d65421 100644 --- a/lightning/src/ln/channel.rs +++ b/lightning/src/ln/channel.rs @@ -2735,20 +2735,50 @@ impl FundingScope { prev_funding: &Self, context: &ChannelContext, our_funding_contribution: SignedAmount, their_funding_contribution: SignedAmount, counterparty_funding_pubkey: PublicKey, our_new_holder_keys: ChannelPublicKeys, - ) -> Self { - debug_assert!(our_funding_contribution.unsigned_abs() <= Amount::MAX_MONEY); - debug_assert!(their_funding_contribution.unsigned_abs() <= Amount::MAX_MONEY); + ) -> Result { + if our_funding_contribution.unsigned_abs() > Amount::MAX_MONEY { + return Err(format!( + "Channel {} cannot be spliced; our {} contribution exceeds the total bitcoin supply", + context.channel_id(), + our_funding_contribution, + )); + } - let post_channel_value = prev_funding.compute_post_splice_value( - our_funding_contribution.to_sat(), - their_funding_contribution.to_sat(), - ); + if their_funding_contribution.unsigned_abs() > Amount::MAX_MONEY { + return Err(format!( + "Channel {} cannot be spliced; their {} contribution exceeds the total bitcoin supply", + context.channel_id(), + their_funding_contribution, + )); + } + + let channel_value_satoshis = prev_funding.get_value_satoshis(); + let value_to_self_satoshis = prev_funding.get_value_to_self_msat() / 1000; + let value_to_counterparty_satoshis = channel_value_satoshis + .checked_sub(value_to_self_satoshis) + .expect("value_to_self is greater than channel value"); + let our_funding_contribution_sat = our_funding_contribution.to_sat(); + let their_funding_contribution_sat = their_funding_contribution.to_sat(); let post_value_to_self_msat = prev_funding - .value_to_self_msat - .checked_add_signed(our_funding_contribution.to_sat() * 1000); - debug_assert!(post_value_to_self_msat.is_some()); - let post_value_to_self_msat = post_value_to_self_msat.unwrap(); + .get_value_to_self_msat() + .checked_add_signed(our_funding_contribution_sat * 1000) + .ok_or(format!( + "Our contribution candidate {our_funding_contribution_sat}sat is \ + greater than our total balance in the channel {value_to_self_satoshis}sat" + ))?; + + value_to_counterparty_satoshis.checked_add_signed(their_funding_contribution_sat).ok_or( + format!( + "Their contribution candidate {their_funding_contribution_sat}sat is \ + greater than their total balance in the channel {value_to_counterparty_satoshis}sat" + ), + )?; + + let post_channel_value = prev_funding.get_value_satoshis() + .checked_add_signed(our_funding_contribution.to_sat()) + .and_then(|v| v.checked_add_signed(their_funding_contribution.to_sat())) + .ok_or(format!("The sum of contributions {our_funding_contribution} and {their_funding_contribution} is greater than the channel's value"))?; let channel_parameters = &prev_funding.channel_transaction_parameters; let mut post_channel_transaction_parameters = ChannelTransactionParameters { @@ -2784,7 +2814,7 @@ impl FundingScope { prev_funding.holder_selected_channel_reserve_satoshis == 0, ); - Self { + Ok(Self { channel_transaction_parameters: post_channel_transaction_parameters, value_to_self_msat: post_value_to_self_msat, funding_transaction: None, @@ -2799,12 +2829,6 @@ impl FundingScope { prev.0.saturating_add_signed(our_funding_contribution.to_sat() * 1000); let new_counterparty_balance_msat = prev.1.saturating_add_signed(their_funding_contribution.to_sat() * 1000); - if new_holder_balance_msat < counterparty_selected_channel_reserve_satoshis { - assert_eq!(new_holder_balance_msat, prev.0); - } - if new_counterparty_balance_msat < holder_selected_channel_reserve_satoshis { - assert_eq!(new_counterparty_balance_msat, prev.1); - } Mutex::new((new_holder_balance_msat, new_counterparty_balance_msat)) }, #[cfg(debug_assertions)] @@ -2814,12 +2838,6 @@ impl FundingScope { prev.0.saturating_add_signed(our_funding_contribution.to_sat() * 1000); let new_counterparty_balance_msat = prev.1.saturating_add_signed(their_funding_contribution.to_sat() * 1000); - if new_holder_balance_msat < counterparty_selected_channel_reserve_satoshis { - assert_eq!(new_holder_balance_msat, prev.0); - } - if new_counterparty_balance_msat < holder_selected_channel_reserve_satoshis { - assert_eq!(new_counterparty_balance_msat, prev.1); - } Mutex::new((new_holder_balance_msat, new_counterparty_balance_msat)) }, #[cfg(any(test, fuzzing))] @@ -2830,16 +2848,7 @@ impl FundingScope { funding_tx_confirmed_in: None, minimum_depth_override: None, short_channel_id: None, - } - } - - /// Compute the post-splice channel value from each counterparty's contributions. - pub(super) fn compute_post_splice_value( - &self, our_funding_contribution: i64, their_funding_contribution: i64, - ) -> u64 { - self.get_value_satoshis().saturating_add_signed( - our_funding_contribution.saturating_add(their_funding_contribution), - ) + }) } /// Returns a `SharedOwnedInput` for using this `FundingScope` as the input to a new splice. @@ -12590,9 +12599,12 @@ where let our_funding_contribution = contribution.net_value(); - if let Err(e) = - self.validate_splice_contributions(our_funding_contribution, SignedAmount::ZERO) - { + if let Err(e) = self.validate_splice_contributions( + our_funding_contribution, + SignedAmount::ZERO, + self.funding.get_counterparty_pubkeys().funding_pubkey, + self.funding.get_holder_pubkeys().clone(), + ) { log_error!(logger, "Channel {} cannot be funded: {}", self.context.channel_id(), e); return Err(QuiescentError::FailSplice(self.splice_funding_failed_for(contribution))); } @@ -12782,61 +12794,30 @@ where fn validate_splice_contributions( &self, our_funding_contribution: SignedAmount, their_funding_contribution: SignedAmount, - ) -> Result<(), String> { - if our_funding_contribution.unsigned_abs() > Amount::MAX_MONEY { - return Err(format!( - "Channel {} cannot be spliced; our {} contribution exceeds the total bitcoin supply", - self.context.channel_id(), - our_funding_contribution, - )); - } - - if their_funding_contribution.unsigned_abs() > Amount::MAX_MONEY { - return Err(format!( - "Channel {} cannot be spliced; their {} contribution exceeds the total bitcoin supply", - self.context.channel_id(), - their_funding_contribution, - )); - } + counterparty_funding_pubkey: PublicKey, our_new_holder_keys: ChannelPublicKeys, + ) -> Result { + let candidate_scope = FundingScope::for_splice( + &self.funding, + self.context(), + our_funding_contribution, + their_funding_contribution, + counterparty_funding_pubkey, + our_new_holder_keys, + )?; - let (holder_balance_remaining, counterparty_balance_remaining) = - self.get_holder_counterparty_balances_floor_incl_fee(&self.funding).map_err(|e| { - format!("Channel {} cannot be spliced; {}", self.context.channel_id(), e) - })?; + let (post_splice_holder_balance, post_splice_counterparty_balance) = + self.get_holder_counterparty_balances_floor_incl_fee(&candidate_scope).map_err( + |e| format!("Channel {} cannot be spliced; {}", self.context.channel_id(), e), + )?; - let post_channel_value = self.funding.compute_post_splice_value( - our_funding_contribution.to_sat(), - their_funding_contribution.to_sat(), + let holder_selected_channel_reserve = + Amount::from_sat(candidate_scope.holder_selected_channel_reserve_satoshis); + let counterparty_selected_channel_reserve = Amount::from_sat( + candidate_scope.counterparty_selected_channel_reserve_satoshis.expect("Reserve is set"), ); - let counterparty_selected_channel_reserve = - Amount::from_sat(get_v2_channel_reserve_satoshis( - post_channel_value, - MIN_CHAN_DUST_LIMIT_SATOSHIS, - self.funding - .counterparty_selected_channel_reserve_satoshis - .expect("counterparty reserve is set") - == 0, - )); - let holder_selected_channel_reserve = Amount::from_sat(get_v2_channel_reserve_satoshis( - post_channel_value, - self.context.counterparty_dust_limit_satoshis, - self.funding.holder_selected_channel_reserve_satoshis == 0, - )); // We allow parties to draw from their previous reserve, as long as they satisfy their v2 reserve - if our_funding_contribution != SignedAmount::ZERO { - let post_splice_holder_balance = Amount::from_sat( - holder_balance_remaining.to_sat() - .checked_add_signed(our_funding_contribution.to_sat()) - .ok_or(format!( - "Channel {} cannot be spliced out; our remaining balance {} does not cover our negative funding contribution {}", - self.context.channel_id(), - holder_balance_remaining, - our_funding_contribution, - ))?, - ); - post_splice_holder_balance.checked_sub(counterparty_selected_channel_reserve) .ok_or(format!( "Channel {} cannot be {}; our post-splice channel balance {} is smaller than their selected v2 reserve {}", @@ -12848,17 +12829,6 @@ where } if their_funding_contribution != SignedAmount::ZERO { - let post_splice_counterparty_balance = Amount::from_sat( - counterparty_balance_remaining.to_sat() - .checked_add_signed(their_funding_contribution.to_sat()) - .ok_or(format!( - "Channel {} cannot be spliced out; their remaining balance {} does not cover their negative funding contribution {}", - self.context.channel_id(), - counterparty_balance_remaining, - their_funding_contribution, - ))?, - ); - post_splice_counterparty_balance.checked_sub(holder_selected_channel_reserve) .ok_or(format!( "Channel {} cannot be {}; their post-splice channel balance {} is smaller than our selected v2 reserve {}", @@ -12869,7 +12839,34 @@ where ))?; } - Ok(()) + #[cfg(debug_assertions)] + { + let (old_holder_balance_msat, old_counterparty_balance_msat) = + *self.funding.holder_prev_commitment_tx_balance.lock().unwrap(); + let (new_holder_balance_msat, new_counterparty_balance_msat) = + *candidate_scope.holder_prev_commitment_tx_balance.lock().unwrap(); + if new_holder_balance_msat < counterparty_selected_channel_reserve.to_sat() * 1000 { + debug_assert_eq!(new_holder_balance_msat, old_holder_balance_msat); + } + if new_counterparty_balance_msat < holder_selected_channel_reserve.to_sat() * 1000 { + debug_assert_eq!(new_counterparty_balance_msat, old_counterparty_balance_msat); + } + } + #[cfg(debug_assertions)] + { + let (old_holder_balance_msat, old_counterparty_balance_msat) = + *self.funding.counterparty_prev_commitment_tx_balance.lock().unwrap(); + let (new_holder_balance_msat, new_counterparty_balance_msat) = + *candidate_scope.counterparty_prev_commitment_tx_balance.lock().unwrap(); + if new_holder_balance_msat < counterparty_selected_channel_reserve.to_sat() * 1000 { + debug_assert_eq!(new_holder_balance_msat, old_holder_balance_msat); + } + if new_counterparty_balance_msat < holder_selected_channel_reserve.to_sat() * 1000 { + debug_assert_eq!(new_counterparty_balance_msat, old_counterparty_balance_msat); + } + } + + Ok(candidate_scope) } fn resolve_queued_contribution( @@ -12927,8 +12924,6 @@ where let our_funding_contribution = queued_net_value.unwrap_or(SignedAmount::ZERO); let their_funding_contribution = SignedAmount::from_sat(msg.funding_contribution_satoshis); - self.validate_splice_contributions(our_funding_contribution, their_funding_contribution) - .map_err(|e| self.quiescent_negotiation_err(ChannelError::WarnAndDisconnect(e)))?; // Rotate the pubkeys using the prev_funding_txid as a tweak let prev_funding_txid = self.funding.get_funding_txid(); @@ -12945,14 +12940,14 @@ where let mut holder_pubkeys = self.funding.get_holder_pubkeys().clone(); holder_pubkeys.funding_pubkey = funding_pubkey; - let splice_funding = FundingScope::for_splice( - &self.funding, - &self.context, - our_funding_contribution, - their_funding_contribution, - msg.funding_pubkey, - holder_pubkeys, - ); + let splice_funding = self + .validate_splice_contributions( + our_funding_contribution, + their_funding_contribution, + msg.funding_pubkey, + holder_pubkeys, + ) + .map_err(|e| self.quiescent_negotiation_err(ChannelError::WarnAndDisconnect(e)))?; // Adjust for the feerate and clone so we can store it for future RBF re-use. let (adjusted_contribution, our_funding_inputs, our_funding_outputs) = @@ -13126,17 +13121,15 @@ where Some(value) => SignedAmount::from_sat(value), None => SignedAmount::ZERO, }; - self.validate_splice_contributions(our_funding_contribution, their_funding_contribution) - .map_err(|e| self.quiescent_negotiation_err(ChannelError::WarnAndDisconnect(e)))?; - let rbf_funding = FundingScope::for_splice( - &self.funding, - &self.context, - our_funding_contribution, - their_funding_contribution, - counterparty_funding_pubkey, - holder_pubkeys, - ); + let rbf_funding = self + .validate_splice_contributions( + our_funding_contribution, + their_funding_contribution, + counterparty_funding_pubkey, + holder_pubkeys, + ) + .map_err(|e| self.quiescent_negotiation_err(ChannelError::WarnAndDisconnect(e)))?; // Consume the appropriate contribution source. let (our_funding_inputs, our_funding_outputs) = if queued_net_value.is_some() { @@ -13219,8 +13212,6 @@ where Some(value) => SignedAmount::from_sat(value), None => SignedAmount::ZERO, }; - self.validate_splice_contributions(our_funding_contribution, their_funding_contribution) - .map_err(|e| ChannelError::WarnAndDisconnect(e))?; let last_candidate = pending_splice.negotiated_candidates.last().ok_or_else(|| { ChannelError::WarnAndDisconnect("No negotiated splice candidates for RBF".to_owned()) @@ -13228,14 +13219,16 @@ where let holder_pubkeys = last_candidate.get_holder_pubkeys().clone(); let counterparty_funding_pubkey = *last_candidate.counterparty_funding_pubkey(); - Ok(FundingScope::for_splice( - &self.funding, - &self.context, - our_funding_contribution, - their_funding_contribution, - counterparty_funding_pubkey, - holder_pubkeys, - )) + let new_funding = self + .validate_splice_contributions( + our_funding_contribution, + their_funding_contribution, + counterparty_funding_pubkey, + holder_pubkeys, + ) + .map_err(|e| ChannelError::WarnAndDisconnect(e))?; + + Ok(new_funding) } pub(crate) fn tx_ack_rbf( @@ -13320,22 +13313,32 @@ where let our_funding_contribution = funding_negotiation_context.our_funding_contribution; let their_funding_contribution = SignedAmount::from_sat(msg.funding_contribution_satoshis); - self.validate_splice_contributions(our_funding_contribution, their_funding_contribution) - .map_err(|e| ChannelError::WarnAndDisconnect(e))?; let mut new_keys = self.funding.get_holder_pubkeys().clone(); new_keys.funding_pubkey = *new_holder_funding_key; - Ok(FundingScope::for_splice( - &self.funding, - &self.context, - our_funding_contribution, - their_funding_contribution, - msg.funding_pubkey, - new_keys, - )) + let new_funding = self + .validate_splice_contributions( + our_funding_contribution, + their_funding_contribution, + msg.funding_pubkey, + new_keys, + ) + .map_err(|e| ChannelError::WarnAndDisconnect(e))?; + + Ok(new_funding) } + /// The balances returned here should only be used to check that both parties still hold + /// their respective reserves *after* a splice. This function also checks that both local + /// and remote commitments still have at least one output after the splice, which is + /// particularly relevant for zero-reserve channels. + /// + /// Do NOT use this to determine how much the holder can splice out of the channel. The balance + /// of the holder after a splice is not necessarily equal to the funds they can splice out + /// of the channel due to the v2 reserve, and the zero-reserve-at-least-one-output + /// requirements. Note you cannot simply subtract out the reserve, as splicing funds out + /// of the channel changes the reserve the holder must keep in the channel. fn get_holder_counterparty_balances_floor_incl_fee( &self, funding: &FundingScope, ) -> Result<(Amount, Amount), String> { @@ -13356,6 +13359,16 @@ where self.context.feerate_per_kw }; + // Different dust limits on the local and remote commitments cause the commitment + // transaction fee to be different depending on the commitment, so we grab the floor + // of both balances across both commitments here. + // + // `get_channel_stats` also checks for at least one output on the commitment given + // these parameters. This is particularly relevant for zero-reserve channels. + // + // This "at-least-one-output" check is why we still run both checks on + // zero-fee-commitment channels, even though those channels don't suffer from the + // commitment transaction fee asymmetry. let (local_stats, _local_htlcs) = self .context .get_next_local_commitment_stats( @@ -14160,6 +14173,8 @@ where if let Err(e) = self.validate_splice_contributions( our_funding_contribution, SignedAmount::ZERO, + self.funding.get_counterparty_pubkeys().funding_pubkey, + self.funding.get_holder_pubkeys().clone(), ) { let failed = self.splice_funding_failed_for(contribution); return Err(( @@ -16825,7 +16840,7 @@ mod tests { use crate::chain::chaininterface::LowerBoundedFeeEstimator; use crate::chain::transaction::OutPoint; use crate::chain::BlockLocator; - use crate::ln::chan_utils::{self, commit_tx_fee_sat, ChannelTransactionParameters}; + use crate::ln::chan_utils::{self, commit_tx_fee_sat}; use crate::ln::channel::{ AwaitingChannelReadyFlags, ChannelState, FundedChannel, HTLCUpdateAwaitingACK, InboundHTLCOutput, InboundHTLCState, InboundUpdateAdd, InboundV1Channel, @@ -16843,6 +16858,7 @@ mod tests { use crate::sign::tx_builder::HTLCAmountDirection; #[cfg(ldk_test_vectors)] use crate::sign::{ChannelSigner, EntropySource, InMemorySigner, SignerProvider}; + #[cfg(ldk_test_vectors)] use crate::sync::Mutex; #[cfg(ldk_test_vectors)] use crate::types::features::ChannelTypeFeatures; @@ -19263,95 +19279,4 @@ mod tests { assert_eq!(node_a_chan.context.channel_state, ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::THEIR_CHANNEL_READY)); assert!(node_a_chan.check_get_channel_ready(0, &&logger).is_some()); } - - fn get_pre_and_post( - pre_channel_value: u64, our_funding_contribution: i64, their_funding_contribution: i64, - ) -> (u64, u64) { - use crate::ln::channel::{FundingScope, PredictedNextFee}; - - let funding = FundingScope { - value_to_self_msat: 0, - counterparty_selected_channel_reserve_satoshis: None, - holder_selected_channel_reserve_satoshis: 0, - - #[cfg(debug_assertions)] - holder_prev_commitment_tx_balance: Mutex::new((0, 0)), - #[cfg(debug_assertions)] - counterparty_prev_commitment_tx_balance: Mutex::new((0, 0)), - - #[cfg(any(test, fuzzing))] - next_local_fee: Mutex::new(PredictedNextFee::default()), - #[cfg(any(test, fuzzing))] - next_remote_fee: Mutex::new(PredictedNextFee::default()), - - channel_transaction_parameters: ChannelTransactionParameters::test_dummy( - pre_channel_value, - ), - funding_transaction: None, - funding_tx_confirmed_in: None, - funding_tx_confirmation_height: 0, - short_channel_id: None, - minimum_depth_override: None, - }; - let post_channel_value = - funding.compute_post_splice_value(our_funding_contribution, their_funding_contribution); - (pre_channel_value, post_channel_value) - } - - #[test] - fn test_compute_post_splice_value() { - { - // increase, small amounts - let (pre_channel_value, post_channel_value) = get_pre_and_post(9_000, 6_000, 0); - assert_eq!(pre_channel_value, 9_000); - assert_eq!(post_channel_value, 15_000); - } - { - // increase, small amounts - let (pre_channel_value, post_channel_value) = get_pre_and_post(9_000, 4_000, 2_000); - assert_eq!(pre_channel_value, 9_000); - assert_eq!(post_channel_value, 15_000); - } - { - // increase, small amounts - let (pre_channel_value, post_channel_value) = get_pre_and_post(9_000, 0, 6_000); - assert_eq!(pre_channel_value, 9_000); - assert_eq!(post_channel_value, 15_000); - } - { - // decrease, small amounts - let (pre_channel_value, post_channel_value) = get_pre_and_post(15_000, -6_000, 0); - assert_eq!(pre_channel_value, 15_000); - assert_eq!(post_channel_value, 9_000); - } - { - // decrease, small amounts - let (pre_channel_value, post_channel_value) = get_pre_and_post(15_000, -4_000, -2_000); - assert_eq!(pre_channel_value, 15_000); - assert_eq!(post_channel_value, 9_000); - } - { - // increase and decrease - let (pre_channel_value, post_channel_value) = get_pre_and_post(15_000, 4_000, -2_000); - assert_eq!(pre_channel_value, 15_000); - assert_eq!(post_channel_value, 17_000); - } - let base2: u64 = 2; - let huge63i3 = (base2.pow(63) - 3) as i64; - assert_eq!(huge63i3, 9223372036854775805); - assert_eq!(-huge63i3, -9223372036854775805); - { - // increase, large amount - let (pre_channel_value, post_channel_value) = get_pre_and_post(9_000, huge63i3, 3); - assert_eq!(pre_channel_value, 9_000); - assert_eq!(post_channel_value, 9223372036854784807); - } - { - // increase, large amounts - let (pre_channel_value, post_channel_value) = - get_pre_and_post(9_000, huge63i3, huge63i3); - assert_eq!(pre_channel_value, 9_000); - assert_eq!(post_channel_value, 9223372036854784807); - } - } } From 0bb9f39f61b1036e8b43cb14edf765aee4b19081 Mon Sep 17 00:00:00 2001 From: Leo Nash Date: Wed, 8 Apr 2026 20:53:03 +0000 Subject: [PATCH 2/6] Add `AvailableBalances::next_splice_out_maximum_sat` We previously determined this value by subtracting the htlcs, the anchors, and the commitment transaction fee. This ignored the reserve, as well as the at-least-one-output requirement in zero-reserve channels. This new field now accounts for both of these constraints. It can be seen as the total spliceable balance from the channel. --- lightning/src/ln/channel.rs | 86 ++++++++++++++++---- lightning/src/ln/channel_state.rs | 1 + lightning/src/ln/channelmanager.rs | 1 + lightning/src/ln/funding.rs | 69 ++++++++-------- lightning/src/sign/tx_builder.rs | 121 ++++++++++++++++++++++++++++- 5 files changed, 227 insertions(+), 51 deletions(-) diff --git a/lightning/src/ln/channel.rs b/lightning/src/ln/channel.rs index 86b34d65421..1160f0649fe 100644 --- a/lightning/src/ln/channel.rs +++ b/lightning/src/ln/channel.rs @@ -122,6 +122,8 @@ pub struct AvailableBalances { pub next_outbound_htlc_limit_msat: u64, /// The minimum value we can assign to the next outbound HTLC pub next_outbound_htlc_minimum_msat: u64, + /// The maximum value of the next splice-out + pub next_splice_out_maximum_sat: u64, } #[derive(Debug, Clone, Copy, PartialEq)] @@ -6756,7 +6758,7 @@ pub(crate) fn get_legacy_default_holder_selected_channel_reserve_satoshis( /// /// This is used both for outbound and inbound channels and has lower bound /// of `dust_limit_satoshis`. -fn get_v2_channel_reserve_satoshis( +pub(crate) fn get_v2_channel_reserve_satoshis( channel_value_satoshis: u64, dust_limit_satoshis: u64, is_0reserve: bool, ) -> u64 { if is_0reserve { @@ -12391,9 +12393,8 @@ where .as_ref() .and_then(|pending_splice| pending_splice.contributions.last()) { - let holder_balance = self - .get_holder_counterparty_balances_floor_incl_fee(&self.funding) - .map(|(h, _)| h) + let spliceable_balance = self + .get_next_splice_out_maximum(&self.funding) .map_err(|e| APIError::ChannelUnavailable { err: format!( "Channel {} cannot be spliced at this time: {}", @@ -12401,7 +12402,7 @@ where e ), })?; - Some(PriorContribution::new(prior.clone(), holder_balance)) + Some(PriorContribution::new(prior.clone(), spliceable_balance)) } else { None } @@ -12497,16 +12498,13 @@ where return contribution; } - let holder_balance = match self - .get_holder_counterparty_balances_floor_incl_fee(&self.funding) - .map(|(holder, _)| holder) - { + let spliceable_balance = match self.get_next_splice_out_maximum(&self.funding) { Ok(balance) => balance, Err(_) => return contribution, }; if let Err(e) = - contribution.net_value_for_initiator_at_feerate(min_rbf_feerate, holder_balance) + contribution.net_value_for_initiator_at_feerate(min_rbf_feerate, spliceable_balance) { log_info!( logger, @@ -12527,7 +12525,7 @@ where min_rbf_feerate, ); contribution - .for_initiator_at_feerate(min_rbf_feerate, holder_balance) + .for_initiator_at_feerate(min_rbf_feerate, spliceable_balance) .expect("feerate compatibility already checked") } @@ -12872,9 +12870,8 @@ where fn resolve_queued_contribution( &self, feerate: FeeRate, logger: &L, ) -> Result<(Option, Option), ChannelError> { - let holder_balance = self - .get_holder_counterparty_balances_floor_incl_fee(&self.funding) - .map(|(holder, _)| holder) + let spliceable_balance = self + .get_next_splice_out_maximum(&self.funding) .map_err(|e| { log_info!( logger, @@ -12886,9 +12883,9 @@ where }) .ok(); - let net_value = match holder_balance.and_then(|_| self.queued_funding_contribution()) { + let net_value = match spliceable_balance.and_then(|_| self.queued_funding_contribution()) { Some(c) => { - match c.net_value_for_acceptor_at_feerate(feerate, holder_balance.unwrap()) { + match c.net_value_for_acceptor_at_feerate(feerate, spliceable_balance.unwrap()) { Ok(net_value) => Some(net_value), Err(FeeRateAdjustmentError::FeeRateTooHigh { .. }) => { return Err(ChannelError::Abort(AbortReason::FeeRateTooHigh)); @@ -12908,7 +12905,7 @@ where None => None, }; - Ok((net_value, holder_balance)) + Ok((net_value, spliceable_balance)) } pub(crate) fn splice_init( @@ -13339,6 +13336,9 @@ where /// of the channel due to the v2 reserve, and the zero-reserve-at-least-one-output /// requirements. Note you cannot simply subtract out the reserve, as splicing funds out /// of the channel changes the reserve the holder must keep in the channel. + /// + /// See [`FundedChannel::get_next_splice_out_maximum`] for the maximum value of the next + /// splice out of the holder's balance. fn get_holder_counterparty_balances_floor_incl_fee( &self, funding: &FundingScope, ) -> Result<(Amount, Amount), String> { @@ -13409,6 +13409,55 @@ where Ok((holder_balance_floor, counterparty_balance_floor)) } + /// Determines the maximum value that the holder can splice out of the channel, accounting + /// for the updated reserves after said splice. This maximum also makes sure the local + /// commitment retains at least one output after the splice, which is particularly relevant + /// for zero-reserve channels. + fn get_next_splice_out_maximum(&self, funding: &FundingScope) -> Result { + let include_counterparty_unknown_htlcs = true; + // We are not interested in dust exposure + let dust_exposure_limiting_feerate = None; + + // When reading the available balances, we take the remote's view of the pending + // HTLCs, see `tx_builder` for further details + let (remote_stats, _remote_htlcs) = self + .context + .get_next_remote_commitment_stats( + funding, + None, // htlc_candidate + include_counterparty_unknown_htlcs, + 0, + self.context.feerate_per_kw, + dust_exposure_limiting_feerate, + ) + .map_err(|()| "Balance exhausted on remote commitment")?; + + let next_splice_out_maximum_sat = + remote_stats.available_balances.next_splice_out_maximum_sat; + + #[cfg(debug_assertions)] + { + // After this max splice out, validation passes, accounting for the updated reserves + self.validate_splice_contributions( + SignedAmount::from_sat(-(next_splice_out_maximum_sat as i64)), + SignedAmount::ZERO, + funding.counterparty_funding_pubkey().clone(), + funding.get_holder_pubkeys().clone(), + ) + .unwrap(); + // Splice-out an additional satoshi, and validation fails! + self.validate_splice_contributions( + SignedAmount::from_sat(-((next_splice_out_maximum_sat + 1) as i64)), + SignedAmount::ZERO, + funding.counterparty_funding_pubkey().clone(), + funding.get_holder_pubkeys().clone(), + ) + .unwrap_err(); + } + + Ok(Amount::from_sat(next_splice_out_maximum_sat)) + } + pub fn splice_locked( &mut self, msg: &msgs::SpliceLocked, node_signer: &NS, chain_hash: ChainHash, user_config: &UserConfig, block_height: u32, logger: &L, @@ -13634,6 +13683,9 @@ where next_outbound_htlc_minimum_msat: acc .next_outbound_htlc_minimum_msat .max(e.next_outbound_htlc_minimum_msat), + next_splice_out_maximum_sat: acc + .next_splice_out_maximum_sat + .min(e.next_splice_out_maximum_sat), }) }) } diff --git a/lightning/src/ln/channel_state.rs b/lightning/src/ln/channel_state.rs index 5547bee8f4c..720f8e7b789 100644 --- a/lightning/src/ln/channel_state.rs +++ b/lightning/src/ln/channel_state.rs @@ -533,6 +533,7 @@ impl ChannelDetails { outbound_capacity_msat: 0, next_outbound_htlc_limit_msat: 0, next_outbound_htlc_minimum_msat: u64::MAX, + next_splice_out_maximum_sat: 0, } }); let (to_remote_reserve_satoshis, to_self_reserve_satoshis) = diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index 1f32423507f..e19cd396357 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -8121,6 +8121,7 @@ impl< outbound_capacity_msat: 0, next_outbound_htlc_limit_msat: 0, next_outbound_htlc_minimum_msat: u64::MAX, + next_splice_out_maximum_sat: 0, } }); let is_in_range = (balances.next_outbound_htlc_minimum_msat diff --git a/lightning/src/ln/funding.rs b/lightning/src/ln/funding.rs index 20366fe772a..386aa3d92a3 100644 --- a/lightning/src/ln/funding.rs +++ b/lightning/src/ln/funding.rs @@ -192,7 +192,7 @@ impl core::fmt::Display for FundingContributionError { #[derive(Debug, Clone, PartialEq, Eq)] pub(super) struct PriorContribution { contribution: FundingContribution, - /// The holder's balance, used for feerate adjustment. + /// The holder's spliceable balance, used for feerate adjustment. /// /// This value is captured at [`ChannelManager::splice_channel`] time and may become stale /// if balances change before the contribution is used. Staleness is acceptable here because @@ -203,12 +203,12 @@ pub(super) struct PriorContribution { /// /// [`ChannelManager::splice_channel`]: crate::ln::channelmanager::ChannelManager::splice_channel /// [`ChannelManager::funding_contributed`]: crate::ln::channelmanager::ChannelManager::funding_contributed - holder_balance: Amount, + spliceable_balance: Amount, } impl PriorContribution { - pub(super) fn new(contribution: FundingContribution, holder_balance: Amount) -> Self { - Self { contribution, holder_balance } + pub(super) fn new(contribution: FundingContribution, spliceable_balance: Amount) -> Self { + Self { contribution, spliceable_balance } } } @@ -632,14 +632,14 @@ impl FundingContribution { /// `target_feerate`. If dropping change leaves surplus value, that surplus remains in the /// channel contribution. /// - /// For input-less contributions, `holder_balance` must be provided to cover the outputs and + /// For input-less contributions, `spliceable_balance` must be provided to cover the outputs and /// fees from the channel balance. /// /// Returns `None` if the request would require new wallet inputs or cannot accommodate the /// requested feerate. fn amend_without_coin_selection( self, inputs: FundingInputs, outputs: &[TxOut], target_feerate: FeeRate, - max_feerate: FeeRate, holder_balance: Amount, + max_feerate: FeeRate, spliceable_balance: Amount, ) -> Option { // NOTE: The contribution returned is not guaranteed to be valid. We defer doing so until // `compute_feerate_adjustment`. @@ -717,7 +717,7 @@ impl FundingContribution { let new_contribution_at_current_feerate = adjust_for_inputs_and_outputs(self, inputs, outputs)?; let mut new_contribution_at_target_feerate = new_contribution_at_current_feerate - .at_feerate(target_feerate, holder_balance, true) + .at_feerate(target_feerate, spliceable_balance, true) .ok()?; new_contribution_at_target_feerate.max_feerate = max_feerate; @@ -771,7 +771,7 @@ impl FundingContribution { /// /// Returns `Err` if the contribution cannot accommodate the target feerate. fn compute_feerate_adjustment( - &self, target_feerate: FeeRate, holder_balance: Amount, is_initiator: bool, + &self, target_feerate: FeeRate, spliceable_balance: Amount, is_initiator: bool, ) -> Result<(Amount, Option), FeeRateAdjustmentError> { if target_feerate < self.feerate { return Err(FeeRateAdjustmentError::FeeRateTooLow { @@ -864,10 +864,12 @@ impl FundingContribution { let total_cost = target_fee .checked_add(value_removed) .ok_or(FeeRateAdjustmentError::FeeBufferOverflow)?; - if total_cost > holder_balance { + if total_cost > spliceable_balance { return Err(FeeRateAdjustmentError::FeeBufferInsufficient { source: "channel balance - withdrawal outputs", - available: holder_balance.checked_sub(value_removed).unwrap_or(Amount::ZERO), + available: spliceable_balance + .checked_sub(value_removed) + .unwrap_or(Amount::ZERO), required: target_fee, }); } @@ -879,10 +881,10 @@ impl FundingContribution { /// estimate, and feerate. Returns the adjusted contribution, or an error if the feerate /// can't be accommodated. fn at_feerate( - mut self, feerate: FeeRate, holder_balance: Amount, is_initiator: bool, + mut self, feerate: FeeRate, spliceable_balance: Amount, is_initiator: bool, ) -> Result { let (new_estimated_fee, new_change) = - self.compute_feerate_adjustment(feerate, holder_balance, is_initiator)?; + self.compute_feerate_adjustment(feerate, spliceable_balance, is_initiator)?; match new_change { Some(value) => self.change_output.as_mut().unwrap().value = value, None => self.change_output = None, @@ -899,9 +901,9 @@ impl FundingContribution { /// This adjusts the change output so the acceptor pays their target fee at the target /// feerate. pub(super) fn for_acceptor_at_feerate( - self, feerate: FeeRate, holder_balance: Amount, + self, feerate: FeeRate, spliceable_balance: Amount, ) -> Result { - self.at_feerate(feerate, holder_balance, false) + self.at_feerate(feerate, spliceable_balance, false) } /// Adjusts the contribution's change output for the minimum RBF feerate. @@ -910,9 +912,9 @@ impl FundingContribution { /// below the minimum RBF feerate, this adjusts the change output so the initiator pays fees /// at the minimum RBF feerate. pub(super) fn for_initiator_at_feerate( - self, feerate: FeeRate, holder_balance: Amount, + self, feerate: FeeRate, spliceable_balance: Amount, ) -> Result { - self.at_feerate(feerate, holder_balance, true) + self.at_feerate(feerate, spliceable_balance, true) } /// Returns the net value at the given target feerate without mutating `self`. @@ -921,10 +923,10 @@ impl FundingContribution { /// can't be accommodated) and computes the adjusted net value (returning `Ok` with the value /// accounting for the target feerate). fn net_value_at_feerate( - &self, target_feerate: FeeRate, holder_balance: Amount, is_initiator: bool, + &self, target_feerate: FeeRate, spliceable_balance: Amount, is_initiator: bool, ) -> Result { let (new_estimated_fee, new_change) = - self.compute_feerate_adjustment(target_feerate, holder_balance, is_initiator)?; + self.compute_feerate_adjustment(target_feerate, spliceable_balance, is_initiator)?; let prev_fee = self .estimated_fee @@ -952,17 +954,17 @@ impl FundingContribution { /// Returns the net value at the given target feerate without mutating `self`, /// assuming acceptor fee responsibility. pub(super) fn net_value_for_acceptor_at_feerate( - &self, target_feerate: FeeRate, holder_balance: Amount, + &self, target_feerate: FeeRate, spliceable_balance: Amount, ) -> Result { - self.net_value_at_feerate(target_feerate, holder_balance, false) + self.net_value_at_feerate(target_feerate, spliceable_balance, false) } /// Returns the net value at the given target feerate without mutating `self`, /// assuming initiator fee responsibility. pub(super) fn net_value_for_initiator_at_feerate( - &self, target_feerate: FeeRate, holder_balance: Amount, + &self, target_feerate: FeeRate, spliceable_balance: Amount, ) -> Result { - self.net_value_at_feerate(target_feerate, holder_balance, true) + self.net_value_at_feerate(target_feerate, spliceable_balance, true) } /// The net value contributed to a channel by the splice. @@ -1059,13 +1061,13 @@ impl FundingBuilderInner { fn build_from_prior_contribution( &mut self, contribution: PriorContribution, ) -> Result { - let PriorContribution { contribution, holder_balance } = contribution; + let PriorContribution { contribution, spliceable_balance } = contribution; if self.request_matches_prior(&contribution) { // Same request, but the feerate may have changed. Adjust the prior contribution // to the new feerate if possible. return contribution - .for_initiator_at_feerate(self.feerate, holder_balance) + .for_initiator_at_feerate(self.feerate, spliceable_balance) .map(|mut adjusted| { adjusted.max_feerate = self.max_feerate; adjusted @@ -1084,7 +1086,7 @@ impl FundingBuilderInner { &self.outputs, self.feerate, self.max_feerate, - holder_balance, + spliceable_balance, ) .ok_or_else(|| FundingContributionError::MissingCoinSelectionSource); } @@ -2181,8 +2183,8 @@ mod tests { }; // Balance of 55,000 sats can't cover outputs (50,000) + target_fee at 50k sat/kwu. - let holder_balance = Amount::from_sat(55_000); - let result = contribution.for_acceptor_at_feerate(target_feerate, holder_balance); + let spliceable_balance = Amount::from_sat(55_000); + let result = contribution.for_acceptor_at_feerate(target_feerate, spliceable_balance); assert!(matches!(result, Err(FeeRateAdjustmentError::FeeBufferInsufficient { .. }))); } @@ -2601,8 +2603,8 @@ mod tests { }; // Balance of 40,000 sats is less than outputs (50,000) + target_fee. - let holder_balance = Amount::from_sat(40_000); - let result = contribution.for_acceptor_at_feerate(target_feerate, holder_balance); + let spliceable_balance = Amount::from_sat(40_000); + let result = contribution.for_acceptor_at_feerate(target_feerate, spliceable_balance); assert!(matches!(result, Err(FeeRateAdjustmentError::FeeBufferInsufficient { .. }))); } @@ -2627,9 +2629,9 @@ mod tests { }; // Balance of 100,000 sats is more than outputs (50,000) + target_fee. - let holder_balance = Amount::from_sat(100_000); + let spliceable_balance = Amount::from_sat(100_000); let contribution = - contribution.for_acceptor_at_feerate(target_feerate, holder_balance).unwrap(); + contribution.for_acceptor_at_feerate(target_feerate, spliceable_balance).unwrap(); let expected_target_fee = estimate_transaction_fee(&[], &outputs, None, false, true, target_feerate); assert_eq!(contribution.estimated_fee, expected_target_fee); @@ -2657,8 +2659,9 @@ mod tests { }; // Balance of 40,000 sats is less than outputs (50,000) + target_fee. - let holder_balance = Amount::from_sat(40_000); - let result = contribution.net_value_for_acceptor_at_feerate(target_feerate, holder_balance); + let spliceable_balance = Amount::from_sat(40_000); + let result = + contribution.net_value_for_acceptor_at_feerate(target_feerate, spliceable_balance); assert!(matches!(result, Err(FeeRateAdjustmentError::FeeBufferInsufficient { .. }))); } diff --git a/lightning/src/sign/tx_builder.rs b/lightning/src/sign/tx_builder.rs index f51759db5e9..ade54c603ca 100644 --- a/lightning/src/sign/tx_builder.rs +++ b/lightning/src/sign/tx_builder.rs @@ -9,7 +9,9 @@ use crate::ln::chan_utils::{ second_stage_tx_fees_sat, ChannelTransactionParameters, CommitmentTransaction, HTLCOutputInCommitment, }; -use crate::ln::channel::{CommitmentStats, ANCHOR_OUTPUT_VALUE_SATOSHI}; +use crate::ln::channel::{ + get_v2_channel_reserve_satoshis, CommitmentStats, ANCHOR_OUTPUT_VALUE_SATOSHI, +}; use crate::prelude::*; use crate::types::features::ChannelTypeFeatures; use crate::util::logger::Logger; @@ -315,6 +317,108 @@ fn get_next_commitment_stats( }) } +/// Determines the maximum value that the holder can splice out of the channel, accounting +/// for the updated reserves after said splice. This maximum also makes sure the local commitment +/// retains at least one output after the splice, which is particularly relevant for +/// zero-reserve channels. +// +// The equation to determine `max_splice_percentage_constraint_sat` is: +// 1) floor((c - s) / 100) == h - s - d +// We want the maximum value of s that will satisfy equation 1, therefore, we solve: +// 2) (c - s) / 100 < h - s - d + 1 +// where c: `channel_value_satoshis` +// s: `max_splice_percentage_constraint_sat` +// h: `local_balance_before_fee_sat` +// d: `post_splice_delta_above_reserve_sat` +// This results in: +// 3) s < (100h + 100 - 100d - c) / 99 +fn get_next_splice_out_maximum_sat( + is_outbound_from_holder: bool, channel_value_satoshis: u64, local_balance_before_fee_msat: u64, + remote_balance_before_fee_msat: u64, spiked_feerate: u32, + spiked_feerate_nondust_htlc_count: usize, post_splice_delta_above_reserve_sat: u64, + channel_constraints: &ChannelConstraints, channel_type: &ChannelTypeFeatures, +) -> u64 { + let local_balance_before_fee_sat = local_balance_before_fee_msat / 1000; + let mut next_splice_out_maximum_sat = if channel_constraints + .counterparty_selected_channel_reserve_satoshis + != 0 + { + let dividend_sat = local_balance_before_fee_sat + .saturating_mul(100) + .saturating_add(100) + .saturating_sub(post_splice_delta_above_reserve_sat.saturating_mul(100)) + .saturating_sub(channel_value_satoshis); + // Calculate the greatest integer that is strictly less than the RHS of inequality 3 above + let max_splice_percentage_constraint_sat = dividend_sat.saturating_sub(1) / 99; + let max_splice_dust_limit_constraint_sat = local_balance_before_fee_sat + .saturating_sub(channel_constraints.holder_dust_limit_satoshis) + .saturating_sub(post_splice_delta_above_reserve_sat); + // Both constraints must be satisfied, so take the minimum of the two maximums + let max_splice_out_sat = + cmp::min(max_splice_percentage_constraint_sat, max_splice_dust_limit_constraint_sat); + #[cfg(debug_assertions)] + if max_splice_out_sat == 0 { + let current_balance_sat = + local_balance_before_fee_sat.saturating_sub(post_splice_delta_above_reserve_sat); + let v2_reserve_sat = get_v2_channel_reserve_satoshis( + channel_value_satoshis, + channel_constraints.holder_dust_limit_satoshis, + false, + ); + // If the holder cannot splice out anything, they must be at or + // below the v2 reserve + debug_assert!(current_balance_sat <= v2_reserve_sat); + } else { + let post_splice_reserve_sat = get_v2_channel_reserve_satoshis( + channel_value_satoshis.saturating_sub(max_splice_out_sat), + channel_constraints.holder_dust_limit_satoshis, + false, + ); + // If the holder can splice out some maximum, splicing out that + // maximum lands them at exactly the new v2 reserve + the + // `post_splice_delta_above_reserve_sat` + debug_assert_eq!( + local_balance_before_fee_sat.saturating_sub(max_splice_out_sat), + post_splice_reserve_sat.saturating_add(post_splice_delta_above_reserve_sat) + ); + } + max_splice_out_sat + } else { + // In a zero-reserve channel, the holder is free to withdraw up to its `post_splice_delta_above_reserve_sat` + local_balance_before_fee_sat.saturating_sub(post_splice_delta_above_reserve_sat) + }; + + // We only bother to check the local commitment here, the counterparty will check its own commitment. + // + // If the current `next_splice_out_maximum_sat` would produce a local commitment with no + // outputs, bump this maximum such that, after the splice, the holder's balance covers at + // least `dust_limit_satoshis` and, if they are the funder, `current_spiked_tx_fee_sat`. + // We don't include an additional non-dust inbound HTLC in the `current_spiked_tx_fee_sat`, + // because we don't mind if the holder dips below their dust limit to cover the fee for that + // inbound non-dust HTLC. + if !has_output( + is_outbound_from_holder, + local_balance_before_fee_msat.saturating_sub(next_splice_out_maximum_sat * 1000), + remote_balance_before_fee_msat, + spiked_feerate, + spiked_feerate_nondust_htlc_count, + channel_constraints.holder_dust_limit_satoshis, + channel_type, + ) { + let dust_limit_satoshis = channel_constraints.holder_dust_limit_satoshis; + let current_spiked_tx_fee_sat = commit_tx_fee_sat(spiked_feerate, 0, channel_type); + let min_balance_sat = if is_outbound_from_holder { + dust_limit_satoshis.saturating_add(current_spiked_tx_fee_sat) + } else { + dust_limit_satoshis + }; + next_splice_out_maximum_sat = + (local_balance_before_fee_msat / 1000).saturating_sub(min_balance_sat); + } + + next_splice_out_maximum_sat +} + fn get_available_balances( is_outbound_from_holder: bool, channel_value_satoshis: u64, value_to_holder_msat: u64, pending_htlcs: &[HTLCAmountDirection], feerate_per_kw: u32, @@ -411,6 +515,20 @@ fn get_available_balances( total_anchors_sat.saturating_mul(1000), ); + let next_splice_out_maximum_sat = get_next_splice_out_maximum_sat( + is_outbound_from_holder, + channel_value_satoshis, + local_balance_before_fee_msat, + remote_balance_before_fee_msat, + spiked_feerate, + // The number of non-dust HTLCs on the local commitment at the spiked feerate + local_nondust_htlc_count, + // The post-splice minimum balance of the holder + if is_outbound_from_holder { local_min_commit_tx_fee_sat } else { 0 }, + &channel_constraints, + channel_type, + ); + let outbound_capacity_msat = local_balance_before_fee_msat .saturating_sub(channel_constraints.counterparty_selected_channel_reserve_satoshis * 1000); @@ -583,6 +701,7 @@ fn get_available_balances( outbound_capacity_msat, next_outbound_htlc_limit_msat: available_capacity_msat, next_outbound_htlc_minimum_msat, + next_splice_out_maximum_sat, } } From 7d6e683cab670a7985369d77a368d1cf48676ee6 Mon Sep 17 00:00:00 2001 From: Leo Nash Date: Thu, 9 Apr 2026 00:22:21 +0000 Subject: [PATCH 3/6] Use `next_splice_out_maximum_sat` to validate `funding_contributed` This is equivalent to the previous commit, see the debug assertions added in the previous commit. We now also get to communicate the exact maximum back to the user, instead of some "balance is lower than our reserve" message, which is hard to react to. --- lightning/src/ln/channel.rs | 29 ++++++++++++++++------------- lightning/src/ln/splicing_tests.rs | 4 ++-- 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/lightning/src/ln/channel.rs b/lightning/src/ln/channel.rs index 1160f0649fe..ca2714035d6 100644 --- a/lightning/src/ln/channel.rs +++ b/lightning/src/ln/channel.rs @@ -12596,13 +12596,14 @@ where } let our_funding_contribution = contribution.net_value(); - - if let Err(e) = self.validate_splice_contributions( - our_funding_contribution, - SignedAmount::ZERO, - self.funding.get_counterparty_pubkeys().funding_pubkey, - self.funding.get_holder_pubkeys().clone(), - ) { + let unsigned_contribution = our_funding_contribution.unsigned_abs(); + if let Err(e) = self.get_next_splice_out_maximum(&self.funding) + .and_then(|splice_max| splice_max + .to_sat() + .checked_add_signed(our_funding_contribution.to_sat()) + .ok_or(format!("Our splice-out value of {unsigned_contribution} is greater than the maximum {splice_max}")) + ) + { log_error!(logger, "Channel {} cannot be funded: {}", self.context.channel_id(), e); return Err(QuiescentError::FailSplice(self.splice_funding_failed_for(contribution))); } @@ -14222,12 +14223,14 @@ where // balance. If invalid, disconnect and return the contribution so // the user can reclaim their inputs. let our_funding_contribution = contribution.net_value(); - if let Err(e) = self.validate_splice_contributions( - our_funding_contribution, - SignedAmount::ZERO, - self.funding.get_counterparty_pubkeys().funding_pubkey, - self.funding.get_holder_pubkeys().clone(), - ) { + let unsigned_contribution = our_funding_contribution.unsigned_abs(); + if let Err(e) = self.get_next_splice_out_maximum(&self.funding) + .and_then(|splice_max| splice_max + .to_sat() + .checked_add_signed(our_funding_contribution.to_sat()) + .ok_or(format!("Our splice-out value of {unsigned_contribution} is greater than the maximum {splice_max}")) + ) + { let failed = self.splice_funding_failed_for(contribution); return Err(( ChannelError::WarnAndDisconnect(format!( diff --git a/lightning/src/ln/splicing_tests.rs b/lightning/src/ln/splicing_tests.rs index b2cb1eda375..33483e4cc54 100644 --- a/lightning/src/ln/splicing_tests.rs +++ b/lightning/src/ln/splicing_tests.rs @@ -4264,8 +4264,8 @@ fn do_test_splice_pending_htlcs(config: UserConfig) { format!("Channel {} cannot accept funding contribution", channel_id); assert_eq!(error, APIError::APIMisuseError { err: cannot_accept_contribution }); let cannot_be_funded = format!( - "Channel {} cannot be funded: Channel {} cannot be spliced out; our post-splice channel balance {} is smaller than their selected v2 reserve {}", - channel_id, channel_id, post_splice_reserve - Amount::ONE_SAT, post_splice_reserve + "Channel {} cannot be funded: Our splice-out value of {} is greater than the maximum {}", + channel_id, splice_out_incl_fees + Amount::ONE_SAT, splice_out_incl_fees, ); initiator.logger.assert_log("lightning::ln::channel", cannot_be_funded, 1); From bfc0e205a84c12bb6e9b14b76c3c3b5ea36c10c3 Mon Sep 17 00:00:00 2001 From: Leo Nash Date: Thu, 9 Apr 2026 07:06:07 +0000 Subject: [PATCH 4/6] Add `ChannelDetails::next_splice_out_maximum_sat` --- fuzz/src/router.rs | 1 + lightning/src/ln/channel_state.rs | 5 +++++ lightning/src/routing/router.rs | 2 ++ 3 files changed, 8 insertions(+) diff --git a/fuzz/src/router.rs b/fuzz/src/router.rs index 2e5b15fc7f4..5bf9650ebad 100644 --- a/fuzz/src/router.rs +++ b/fuzz/src/router.rs @@ -248,6 +248,7 @@ pub fn do_test(data: &[u8], out: Out) { outbound_capacity_msat: capacity.saturating_mul(1000), next_outbound_htlc_limit_msat: capacity.saturating_mul(1000), next_outbound_htlc_minimum_msat: 0, + next_splice_out_maximum_sat: capacity, inbound_htlc_minimum_msat: None, inbound_htlc_maximum_msat: None, config: None, diff --git a/lightning/src/ln/channel_state.rs b/lightning/src/ln/channel_state.rs index 720f8e7b789..9fd0df4a1bf 100644 --- a/lightning/src/ln/channel_state.rs +++ b/lightning/src/ln/channel_state.rs @@ -399,6 +399,8 @@ pub struct ChannelDetails { /// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a /// route which is valid. pub next_outbound_htlc_minimum_msat: u64, + /// The maximum value of the next splice out from our channel balance. + pub next_splice_out_maximum_sat: u64, /// The available inbound capacity for the remote peer to send HTLCs to us. This does not /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not /// available for inclusion in new inbound HTLCs). @@ -583,6 +585,7 @@ impl ChannelDetails { outbound_capacity_msat: balance.outbound_capacity_msat, next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat, next_outbound_htlc_minimum_msat: balance.next_outbound_htlc_minimum_msat, + next_splice_out_maximum_sat: balance.next_splice_out_maximum_sat, user_channel_id: context.get_user_id(), confirmations_required: channel.minimum_depth(), confirmations: Some(funding.get_funding_tx_confirmations(best_block_height)), @@ -622,6 +625,7 @@ impl_writeable_tlv_based!(ChannelDetails, { (20, inbound_capacity_msat, required), (21, next_outbound_htlc_minimum_msat, (default_value, 0)), (22, confirmations_required, option), + (23, next_splice_out_maximum_sat, (default_value, u64::from(outbound_capacity_msat.0.unwrap()) / 1000)), (24, force_close_spend_delay, option), (26, is_outbound, required), (28, is_channel_ready, required), @@ -726,6 +730,7 @@ mod tests { outbound_capacity_msat: 24_300, next_outbound_htlc_limit_msat: 20_000, next_outbound_htlc_minimum_msat: 132, + next_splice_out_maximum_sat: 20, inbound_capacity_msat: 42, unspendable_punishment_reserve: Some(8273), confirmations_required: Some(5), diff --git a/lightning/src/routing/router.rs b/lightning/src/routing/router.rs index edb048c8c7d..fce3996efa1 100644 --- a/lightning/src/routing/router.rs +++ b/lightning/src/routing/router.rs @@ -4150,6 +4150,7 @@ mod tests { outbound_capacity_msat, next_outbound_htlc_limit_msat: outbound_capacity_msat, next_outbound_htlc_minimum_msat: 0, + next_splice_out_maximum_sat: outbound_capacity_msat / 1000, inbound_capacity_msat: 42, unspendable_punishment_reserve: None, confirmations_required: None, @@ -9649,6 +9650,7 @@ pub(crate) mod bench_utils { outbound_capacity_msat: 10_000_000_000, next_outbound_htlc_minimum_msat: 0, next_outbound_htlc_limit_msat: 10_000_000_000, + next_splice_out_maximum_sat: 10_000_000, inbound_capacity_msat: 0, unspendable_punishment_reserve: None, confirmations_required: None, From a2cd4a348fe40313223ee61567de79427feb7e40 Mon Sep 17 00:00:00 2001 From: Leo Nash Date: Thu, 9 Apr 2026 06:33:02 +0000 Subject: [PATCH 5/6] Add `test_0reserve_splice` --- lightning/src/ln/htlc_reserve_unit_tests.rs | 2 +- lightning/src/ln/splicing_tests.rs | 354 +++++++++++++++++++- 2 files changed, 353 insertions(+), 3 deletions(-) diff --git a/lightning/src/ln/htlc_reserve_unit_tests.rs b/lightning/src/ln/htlc_reserve_unit_tests.rs index aaf81b87be7..45d3cf5950f 100644 --- a/lightning/src/ln/htlc_reserve_unit_tests.rs +++ b/lightning/src/ln/htlc_reserve_unit_tests.rs @@ -2581,7 +2581,7 @@ fn test_0reserve_no_outputs() { do_test_0reserve_no_outputs_p2a_anchor(); } -fn setup_0reserve_no_outputs_channels<'a, 'b, 'c, 'd>( +pub(crate) fn setup_0reserve_no_outputs_channels<'a, 'b, 'c, 'd>( nodes: &'a Vec>, channel_value_sat: u64, dust_limit_satoshis: u64, ) -> (ChannelId, Transaction) { let node_a_id = nodes[0].node.get_our_node_id(); diff --git a/lightning/src/ln/splicing_tests.rs b/lightning/src/ln/splicing_tests.rs index 33483e4cc54..986af7901dd 100644 --- a/lightning/src/ln/splicing_tests.rs +++ b/lightning/src/ln/splicing_tests.rs @@ -16,8 +16,8 @@ use crate::chain::ChannelMonitorUpdateStatus; use crate::events::{ClosureReason, Event, FundingInfo, HTLCHandlingFailureType}; use crate::ln::chan_utils; use crate::ln::channel::{ - CHANNEL_ANNOUNCEMENT_PROPAGATION_DELAY, DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, + ANCHOR_OUTPUT_VALUE_SATOSHI, CHANNEL_ANNOUNCEMENT_PROPAGATION_DELAY, + DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, }; use crate::ln::channelmanager::{provided_init_features, PaymentId, BREAKDOWN_TIMEOUT}; use crate::ln::functional_test_utils::*; @@ -7477,3 +7477,353 @@ fn test_no_disconnect_after_quiescence_on_reconnect() { assert!(!has_disconnect(&nodes[0].node.get_and_clear_pending_msg_events())); assert!(!has_disconnect(&nodes[1].node.get_and_clear_pending_msg_events())); } + +#[test] +fn test_0reserve_splice() { + let mut config = test_default_channel_config(); + config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = false; + config.channel_handshake_config.negotiate_anchor_zero_fee_commitments = false; + let a = do_test_0reserve_splice_holder_validation(false, false, false, config.clone()); + let _b = do_test_0reserve_splice_holder_validation(true, false, false, config.clone()); + let _c = do_test_0reserve_splice_holder_validation(false, true, false, config.clone()); + let _d = do_test_0reserve_splice_holder_validation(true, true, false, config.clone()); + + let _e = do_test_0reserve_splice_holder_validation(false, false, true, config.clone()); + let _f = do_test_0reserve_splice_holder_validation(true, false, true, config.clone()); + let _g = do_test_0reserve_splice_holder_validation(false, true, true, config.clone()); + let _h = do_test_0reserve_splice_holder_validation(true, true, true, config.clone()); + + assert_eq!(a, ChannelTypeFeatures::only_static_remote_key()); + + config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true; + config.channel_handshake_config.negotiate_anchor_zero_fee_commitments = false; + let a = do_test_0reserve_splice_holder_validation(false, false, false, config.clone()); + let _b = do_test_0reserve_splice_holder_validation(true, false, false, config.clone()); + let _c = do_test_0reserve_splice_holder_validation(false, true, false, config.clone()); + let _d = do_test_0reserve_splice_holder_validation(true, true, false, config.clone()); + + let _e = do_test_0reserve_splice_holder_validation(false, false, true, config.clone()); + let _f = do_test_0reserve_splice_holder_validation(true, false, true, config.clone()); + let _g = do_test_0reserve_splice_holder_validation(false, true, true, config.clone()); + let _h = do_test_0reserve_splice_holder_validation(true, true, true, config.clone()); + + assert_eq!(a, ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()); + + let mut config = test_default_channel_config(); + config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = false; + config.channel_handshake_config.negotiate_anchor_zero_fee_commitments = false; + let a = do_test_0reserve_splice_counterparty_validation(false, false, false, config.clone()); + let _b = do_test_0reserve_splice_counterparty_validation(true, false, false, config.clone()); + let _c = do_test_0reserve_splice_counterparty_validation(false, true, false, config.clone()); + let _d = do_test_0reserve_splice_counterparty_validation(true, true, false, config.clone()); + + let _e = do_test_0reserve_splice_counterparty_validation(false, false, true, config.clone()); + let _f = do_test_0reserve_splice_counterparty_validation(true, false, true, config.clone()); + let _g = do_test_0reserve_splice_counterparty_validation(false, true, true, config.clone()); + let _h = do_test_0reserve_splice_counterparty_validation(true, true, true, config.clone()); + assert_eq!(a, ChannelTypeFeatures::only_static_remote_key()); + + config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true; + config.channel_handshake_config.negotiate_anchor_zero_fee_commitments = false; + let a = do_test_0reserve_splice_counterparty_validation(false, false, false, config.clone()); + let _b = do_test_0reserve_splice_counterparty_validation(true, false, false, config.clone()); + let _c = do_test_0reserve_splice_counterparty_validation(false, true, false, config.clone()); + let _d = do_test_0reserve_splice_counterparty_validation(true, true, false, config.clone()); + + let _e = do_test_0reserve_splice_counterparty_validation(false, false, true, config.clone()); + let _f = do_test_0reserve_splice_counterparty_validation(true, false, true, config.clone()); + let _g = do_test_0reserve_splice_counterparty_validation(false, true, true, config.clone()); + let _h = do_test_0reserve_splice_counterparty_validation(true, true, true, config.clone()); + assert_eq!(a, ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()); + + // TODO: Skip 0FC channels for now as these always have an output on the commitment, the P2A + // output. We will be able to withdraw up to the dust limit of the funding script, which + // is checked in interactivetx. Still need to double check whether that's what we actually + // want. +} + +#[cfg(test)] +fn do_test_0reserve_splice_holder_validation( + splice_passes: bool, counterparty_has_output: bool, node_0_is_initiator: bool, + mut config: UserConfig, +) -> ChannelTypeFeatures { + use crate::ln::htlc_reserve_unit_tests::setup_0reserve_no_outputs_channels; + + let chanmon_cfgs = create_chanmon_cfgs(2); + let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); + config.channel_handshake_config.announced_channel_max_inbound_htlc_value_in_flight_percentage = + 100; + let node_chanmgrs = + create_node_chanmgrs(2, &node_cfgs, &[Some(config.clone()), Some(config.clone())]); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); + + let _node_id_0 = nodes[0].node.get_our_node_id(); + let _node_id_1 = nodes[1].node.get_our_node_id(); + + let channel_value_sat = 100_000; + // Some dust limit, does not matter + let dust_limit_satoshis = 546; + + let (channel_id, _tx) = + setup_0reserve_no_outputs_channels(&nodes, channel_value_sat, dust_limit_satoshis); + let details = &nodes[0].node.list_channels()[0]; + let channel_type = details.channel_type.clone().unwrap(); + + let feerate = 253; + let spiked_feerate = if channel_type == ChannelTypeFeatures::only_static_remote_key() { + feerate * FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32 + } else if channel_type == ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies() { + feerate + } else { + panic!("Unexpected channel type"); + }; + let anchors_sat = + if channel_type == ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies() { + ANCHOR_OUTPUT_VALUE_SATOSHI * 2 + } else { + 0 + }; + + let initiator_value_to_self_sat = if counterparty_has_output { + send_payment(&nodes[0], &[&nodes[1]], channel_value_sat / 2 * 1_000); + channel_value_sat / 2 + } else if !node_0_is_initiator { + let tx_fee_msat = chan_utils::commit_tx_fee_sat(spiked_feerate, 2, &channel_type) * 1000; + let node_0_details = &nodes[0].node.list_channels()[0]; + let outbound_capacity_msat = node_0_details.outbound_capacity_msat; + let available_capacity_msat = node_0_details.next_outbound_htlc_limit_msat; + assert_eq!(outbound_capacity_msat, (channel_value_sat - anchors_sat) * 1000); + assert_eq!(available_capacity_msat, outbound_capacity_msat - tx_fee_msat); + send_payment(&nodes[0], &[&nodes[1]], available_capacity_msat); + + // Make sure node 0 has no output on the commitment at this point + let node_0_to_local_output_msat = channel_value_sat * 1000 + - available_capacity_msat + - anchors_sat * 1000 + - chan_utils::commit_tx_fee_sat(feerate, 0, &channel_type) * 1000; + assert!(node_0_to_local_output_msat / 1000 < dust_limit_satoshis); + let commit_tx = &get_local_commitment_txn!(nodes[0], channel_id)[0]; + assert_eq!(commit_tx.output.len(), if anchors_sat == 0 { 1 } else { 2 }); + assert_eq!( + commit_tx.output.last().unwrap().value, + Amount::from_sat(available_capacity_msat / 1000) + ); + if anchors_sat != 0 { + assert_eq!(commit_tx.output[0].value, Amount::from_sat(330)); + } + + available_capacity_msat / 1000 + } else { + channel_value_sat + }; + + // The estimated fees to splice out a single output at 253sat/kw + let estimated_fees = 183; + let splice_out_max_value = if counterparty_has_output && node_0_is_initiator { + let commit_tx_fee_sat = chan_utils::commit_tx_fee_sat(spiked_feerate, 1, &channel_type); + Amount::from_sat( + initiator_value_to_self_sat - commit_tx_fee_sat - anchors_sat - estimated_fees, + ) + } else if !counterparty_has_output && node_0_is_initiator { + let commit_tx_fee_sat = chan_utils::commit_tx_fee_sat(spiked_feerate, 0, &channel_type); + Amount::from_sat( + initiator_value_to_self_sat + - commit_tx_fee_sat + - anchors_sat - estimated_fees + - dust_limit_satoshis, + ) + } else if counterparty_has_output && !node_0_is_initiator { + Amount::from_sat(initiator_value_to_self_sat - estimated_fees) + } else if !counterparty_has_output && !node_0_is_initiator { + Amount::from_sat(initiator_value_to_self_sat - estimated_fees - dust_limit_satoshis) + } else { + panic!("unexpected case!"); + }; + let outputs = vec![TxOut { + value: splice_out_max_value + if splice_passes { Amount::ZERO } else { Amount::ONE_SAT }, + script_pubkey: nodes[0].wallet_source.get_change_script().unwrap(), + }]; + + let (initiator, acceptor) = + if node_0_is_initiator { (&nodes[0], &nodes[1]) } else { (&nodes[1], &nodes[0]) }; + + let initiator_details = &initiator.node.list_channels()[0]; + assert_eq!( + initiator_details.next_splice_out_maximum_sat, + splice_out_max_value.to_sat() + estimated_fees + ); + + if splice_passes { + let contribution = initiate_splice_out(initiator, acceptor, channel_id, outputs).unwrap(); + + let (splice_tx, _) = splice_channel(initiator, acceptor, channel_id, contribution); + mine_transaction(initiator, &splice_tx); + mine_transaction(acceptor, &splice_tx); + lock_splice_after_blocks(initiator, acceptor, ANTI_REORG_DELAY - 1); + } else { + assert!(initiate_splice_out(initiator, acceptor, channel_id, outputs).is_err()); + let splice_out_value = + splice_out_max_value + Amount::from_sat(estimated_fees) + Amount::ONE_SAT; + let splice_out_max_value = splice_out_max_value + Amount::from_sat(estimated_fees); + let cannot_be_funded = format!( + "Channel {channel_id} cannot be funded: Our \ + splice-out value of {splice_out_value} is greater than the maximum \ + {splice_out_max_value}" + ); + initiator.logger.assert_log("lightning::ln::channel", cannot_be_funded, 1); + } + + channel_type +} + +#[cfg(test)] +fn do_test_0reserve_splice_counterparty_validation( + splice_passes: bool, counterparty_has_output: bool, node_0_is_initiator: bool, + mut config: UserConfig, +) -> ChannelTypeFeatures { + use crate::ln::htlc_reserve_unit_tests::setup_0reserve_no_outputs_channels; + + let chanmon_cfgs = create_chanmon_cfgs(2); + let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); + config.channel_handshake_config.announced_channel_max_inbound_htlc_value_in_flight_percentage = + 100; + let node_chanmgrs = + create_node_chanmgrs(2, &node_cfgs, &[Some(config.clone()), Some(config.clone())]); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); + + let _node_id_0 = nodes[0].node.get_our_node_id(); + let _node_id_1 = nodes[1].node.get_our_node_id(); + + let channel_value_sat = 100_000; + // Some dust limit, does not matter + let dust_limit_satoshis = 546; + + let (channel_id, _tx) = + setup_0reserve_no_outputs_channels(&nodes, channel_value_sat, dust_limit_satoshis); + let details = &nodes[0].node.list_channels()[0]; + let channel_type = details.channel_type.clone().unwrap(); + + let feerate = 253; + let spiked_feerate = if channel_type == ChannelTypeFeatures::only_static_remote_key() { + feerate * FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32 + } else if channel_type == ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies() { + feerate + } else { + panic!("Unexpected channel type"); + }; + let anchors_sat = + if channel_type == ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies() { + ANCHOR_OUTPUT_VALUE_SATOSHI * 2 + } else { + 0 + }; + + let initiator_value_to_self_sat = if counterparty_has_output { + send_payment(&nodes[0], &[&nodes[1]], channel_value_sat / 2 * 1_000); + channel_value_sat / 2 + } else if !node_0_is_initiator { + let tx_fee_msat = chan_utils::commit_tx_fee_sat(spiked_feerate, 2, &channel_type) * 1000; + let node_0_details = &nodes[0].node.list_channels()[0]; + let outbound_capacity_msat = node_0_details.outbound_capacity_msat; + let available_capacity_msat = node_0_details.next_outbound_htlc_limit_msat; + assert_eq!(outbound_capacity_msat, (channel_value_sat - anchors_sat) * 1000); + assert_eq!(available_capacity_msat, outbound_capacity_msat - tx_fee_msat); + send_payment(&nodes[0], &[&nodes[1]], available_capacity_msat); + + // Make sure node 0 has no output on the commitment at this point + let node_0_to_local_output_msat = channel_value_sat * 1000 + - available_capacity_msat + - anchors_sat * 1000 + - chan_utils::commit_tx_fee_sat(spiked_feerate, 0, &channel_type) * 1000; + assert!(node_0_to_local_output_msat / 1000 < dust_limit_satoshis); + let commit_tx = &get_local_commitment_txn!(nodes[0], channel_id)[0]; + assert_eq!(commit_tx.output.len(), if anchors_sat == 0 { 1 } else { 2 }); + assert_eq!( + commit_tx.output.last().unwrap().value, + Amount::from_sat(available_capacity_msat / 1000) + ); + if anchors_sat != 0 { + assert_eq!(commit_tx.output[0].value, Amount::from_sat(330)); + } + + available_capacity_msat / 1000 + } else { + channel_value_sat + }; + + let splice_out_value_incl_fees = if counterparty_has_output && node_0_is_initiator { + let commit_tx_fee_sat = chan_utils::commit_tx_fee_sat(spiked_feerate, 1, &channel_type); + Amount::from_sat(initiator_value_to_self_sat - commit_tx_fee_sat - anchors_sat) + } else if !counterparty_has_output && node_0_is_initiator { + let commit_tx_fee_sat = chan_utils::commit_tx_fee_sat(spiked_feerate, 0, &channel_type); + Amount::from_sat( + initiator_value_to_self_sat - commit_tx_fee_sat - anchors_sat - dust_limit_satoshis, + ) + } else if counterparty_has_output && !node_0_is_initiator { + Amount::from_sat(initiator_value_to_self_sat) + } else if !counterparty_has_output && !node_0_is_initiator { + Amount::from_sat(initiator_value_to_self_sat - dust_limit_satoshis) + } else { + panic!("unexpected case!"); + }; + + let (initiator, acceptor) = + if node_0_is_initiator { (&nodes[0], &nodes[1]) } else { (&nodes[1], &nodes[0]) }; + + let initiator_details = &initiator.node.list_channels()[0]; + assert_eq!(initiator_details.next_splice_out_maximum_sat, splice_out_value_incl_fees.to_sat()); + + let funding_contribution_sat = + -(splice_out_value_incl_fees.to_sat() as i64) - if splice_passes { 0 } else { 1 }; + let outputs = vec![TxOut { + // Splice out some dummy amount to get past the initiator's validation, + // we'll modify the message in-flight. + value: Amount::from_sat(1_000), + script_pubkey: nodes[0].wallet_source.get_change_script().unwrap(), + }]; + let _contribution = initiate_splice_out(initiator, acceptor, channel_id, outputs).unwrap(); + + let node_id_initiator = initiator.node.get_our_node_id(); + let node_id_acceptor = acceptor.node.get_our_node_id(); + + let stfu_init = get_event_msg!(initiator, MessageSendEvent::SendStfu, node_id_acceptor); + acceptor.node.handle_stfu(node_id_initiator, &stfu_init); + let stfu_ack = get_event_msg!(acceptor, MessageSendEvent::SendStfu, node_id_initiator); + initiator.node.handle_stfu(node_id_acceptor, &stfu_ack); + + let mut splice_init = + get_event_msg!(initiator, MessageSendEvent::SendSpliceInit, node_id_acceptor); + // Make the modification here + splice_init.funding_contribution_satoshis = funding_contribution_sat; + + if splice_passes { + acceptor.node.handle_splice_init(node_id_initiator, &splice_init); + let _splice_ack = + get_event_msg!(acceptor, MessageSendEvent::SendSpliceAck, node_id_initiator); + } else { + acceptor.node.handle_splice_init(node_id_initiator, &splice_init); + let msg_events = acceptor.node.get_and_clear_pending_msg_events(); + assert_eq!(msg_events.len(), 1); + if let MessageSendEvent::HandleError { action, .. } = &msg_events[0] { + assert!(matches!(action, msgs::ErrorAction::DisconnectPeerWithWarning { .. })); + } else { + panic!("Expected MessageSendEvent::HandleError"); + } + let cannot_splice_out = if u64::try_from(funding_contribution_sat.abs()).unwrap() + > initiator_value_to_self_sat + { + format!( + "Got non-closing error: Their contribution candidate {funding_contribution_sat}sat \ + is greater than their total balance in the channel {initiator_value_to_self_sat}sat" + ) + } else { + format!( + "Got non-closing error: Channel {channel_id} cannot \ + be spliced; Balance exhausted on local commitment" + ) + }; + acceptor.logger.assert_log("lightning::ln::channelmanager", cannot_splice_out, 1); + } + + channel_type +} From 89ee5a1c182790b0a733b41044db864544b1d882 Mon Sep 17 00:00:00 2001 From: Leo Nash Date: Tue, 28 Apr 2026 19:39:26 +0000 Subject: [PATCH 6/6] Always enforce the 1000sat min channel value in zero-reserve channels We did not enforce this minimum when accepting 0-reserve channels. This is because we depended on the `MIN_THEIR_CHAN_RESERVE_SATOSHIS` constant to guarantee this minimum channel value, but this value is no longer read in 0-reserve channels. Note that the user's `min_funding_satoshis` value would still be respected in this case. When splicing 0-reserve channels, we only enforced that the commitment transaction retained at least one output after the splice, which could produce a channel value lower than 1000sats. Along the way, we also now enforce this 1000sat minimum when splicing reserve-enabled channels. We previously correctly enforced the reserves after the splice, but this could still result in a channel value smaller than 1000sats. This case is now rejected during splice validation. Note that the user's `min_funding_satoshis` is not respected when validating splice contributions, we leave this for follow-up work. --- lightning/src/ln/channel.rs | 25 +++++-- lightning/src/ln/channelmanager.rs | 2 +- lightning/src/ln/splicing_tests.rs | 113 ++++++++++++++++++++++------- lightning/src/sign/tx_builder.rs | 6 ++ lightning/src/util/config.rs | 3 +- 5 files changed, 115 insertions(+), 34 deletions(-) diff --git a/lightning/src/ln/channel.rs b/lightning/src/ln/channel.rs index ca2714035d6..a475ee564bd 100644 --- a/lightning/src/ln/channel.rs +++ b/lightning/src/ln/channel.rs @@ -1003,6 +1003,9 @@ pub const MIN_CHAN_DUST_LIMIT_SATOSHIS: u64 = 354; // Just a reasonable implementation-specific safe lower bound, higher than the dust limit. pub const MIN_THEIR_CHAN_RESERVE_SATOSHIS: u64 = 1000; +// Just a reasonable implementation-specific safe lower bound. +pub const MIN_CHANNEL_VALUE_SATOSHIS: u64 = 1000; + /// Used to return a simple Error back to ChannelManager. Will get converted to a /// msgs::ErrorAction::SendErrorMessage or msgs::ErrorAction::IgnoreError as appropriate with our /// channel_id in ChannelManager. @@ -2777,10 +2780,15 @@ impl FundingScope { ), )?; - let post_channel_value = prev_funding.get_value_satoshis() + let post_channel_value_sat = prev_funding.get_value_satoshis() .checked_add_signed(our_funding_contribution.to_sat()) .and_then(|v| v.checked_add_signed(their_funding_contribution.to_sat())) .ok_or(format!("The sum of contributions {our_funding_contribution} and {their_funding_contribution} is greater than the channel's value"))?; + if post_channel_value_sat < MIN_CHANNEL_VALUE_SATOSHIS { + return Err(format!( + "Spliced channel value must be at least 1000 satoshis. It would be {post_channel_value_sat}", + )); + } let channel_parameters = &prev_funding.channel_transaction_parameters; let mut post_channel_transaction_parameters = ChannelTransactionParameters { @@ -2792,7 +2800,7 @@ impl FundingScope { funding_outpoint: None, // filled later splice_parent_funding_txid: prev_funding.get_funding_txid(), channel_type_features: channel_parameters.channel_type_features.clone(), - channel_value_satoshis: post_channel_value, + channel_value_satoshis: post_channel_value_sat, }; post_channel_transaction_parameters .counterparty_parameters @@ -2803,7 +2811,7 @@ impl FundingScope { // New reserve values are based on the new channel value and are v2-specific let counterparty_selected_channel_reserve_satoshis = get_v2_channel_reserve_satoshis( - post_channel_value, + post_channel_value_sat, MIN_CHAN_DUST_LIMIT_SATOSHIS, prev_funding .counterparty_selected_channel_reserve_satoshis @@ -2811,7 +2819,7 @@ impl FundingScope { == 0, ); let holder_selected_channel_reserve_satoshis = get_v2_channel_reserve_satoshis( - post_channel_value, + post_channel_value_sat, context.counterparty_dust_limit_satoshis, prev_funding.holder_selected_channel_reserve_satoshis == 0, ); @@ -3739,6 +3747,11 @@ impl ChannelContext { let channel_value_satoshis = our_funding_satoshis.saturating_add(open_channel_fields.funding_satoshis); + if channel_value_satoshis < MIN_CHANNEL_VALUE_SATOSHIS { + return Err(ChannelError::close(format!( + "Channel value must be at least 1000 satoshis. It was {channel_value_satoshis}", + ))); + } let channel_keys_id = signer_provider.generate_channel_keys_id(true, user_id); let holder_signer = signer_provider.derive_channel_signer(channel_keys_id); @@ -3887,7 +3900,7 @@ impl ChannelContext { && holder_selected_channel_reserve_satoshis != 0 { // Protocol level safety check in place, although it should never happen because - // of `MIN_THEIR_CHAN_RESERVE_SATOSHIS` + // of `MIN_THEIR_CHAN_RESERVE_SATOSHIS` and `MIN_CHANNEL_VALUE_SATOSHIS` return Err(ChannelError::close(format!( "Suitable channel reserve not found. remote_channel_reserve was ({holder_selected_channel_reserve_satoshis}). dust_limit_satoshis is ({MIN_CHAN_DUST_LIMIT_SATOSHIS})." ))); @@ -14443,7 +14456,7 @@ impl OutboundV1Channel { ); if holder_selected_channel_reserve_satoshis < MIN_CHAN_DUST_LIMIT_SATOSHIS && !is_0reserve { // Protocol level safety check in place, although it should never happen because - // of `MIN_THEIR_CHAN_RESERVE_SATOSHIS` + // of `MIN_THEIR_CHAN_RESERVE_SATOSHIS` and `MIN_CHANNEL_VALUE_SATOSHIS` return Err(APIError::APIMisuseError { err: format!( "Holder selected channel reserve below implementation limit dust_limit_satoshis {holder_selected_channel_reserve_satoshis}" diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index e19cd396357..6ce25ae8090 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -3887,7 +3887,7 @@ impl< override_config: Option, trusted_channel_features: Option, ) -> Result { - if channel_value_satoshis < 1000 { + if channel_value_satoshis < crate::ln::channel::MIN_CHANNEL_VALUE_SATOSHIS { return Err(APIError::APIMisuseError { err: format!( "Channel value must be at least 1000 satoshis. It was {channel_value_satoshis}" diff --git a/lightning/src/ln/splicing_tests.rs b/lightning/src/ln/splicing_tests.rs index 986af7901dd..a5361358653 100644 --- a/lightning/src/ln/splicing_tests.rs +++ b/lightning/src/ln/splicing_tests.rs @@ -18,6 +18,7 @@ use crate::ln::chan_utils; use crate::ln::channel::{ ANCHOR_OUTPUT_VALUE_SATOSHI, CHANNEL_ANNOUNCEMENT_PROPAGATION_DELAY, DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, + MIN_CHANNEL_VALUE_SATOSHIS, }; use crate::ln::channelmanager::{provided_init_features, PaymentId, BREAKDOWN_TIMEOUT}; use crate::ln::functional_test_utils::*; @@ -7509,6 +7510,20 @@ fn test_0reserve_splice() { assert_eq!(a, ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()); + config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = false; + config.channel_handshake_config.negotiate_anchor_zero_fee_commitments = true; + let a = do_test_0reserve_splice_holder_validation(false, false, false, config.clone()); + let _b = do_test_0reserve_splice_holder_validation(true, false, false, config.clone()); + let _c = do_test_0reserve_splice_holder_validation(false, true, false, config.clone()); + let _d = do_test_0reserve_splice_holder_validation(true, true, false, config.clone()); + + let _e = do_test_0reserve_splice_holder_validation(false, false, true, config.clone()); + let _f = do_test_0reserve_splice_holder_validation(true, false, true, config.clone()); + let _g = do_test_0reserve_splice_holder_validation(false, true, true, config.clone()); + let _h = do_test_0reserve_splice_holder_validation(true, true, true, config.clone()); + + assert_eq!(a, ChannelTypeFeatures::anchors_zero_fee_commitments()); + let mut config = test_default_channel_config(); config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = false; config.channel_handshake_config.negotiate_anchor_zero_fee_commitments = false; @@ -7521,6 +7536,7 @@ fn test_0reserve_splice() { let _f = do_test_0reserve_splice_counterparty_validation(true, false, true, config.clone()); let _g = do_test_0reserve_splice_counterparty_validation(false, true, true, config.clone()); let _h = do_test_0reserve_splice_counterparty_validation(true, true, true, config.clone()); + assert_eq!(a, ChannelTypeFeatures::only_static_remote_key()); config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true; @@ -7534,12 +7550,22 @@ fn test_0reserve_splice() { let _f = do_test_0reserve_splice_counterparty_validation(true, false, true, config.clone()); let _g = do_test_0reserve_splice_counterparty_validation(false, true, true, config.clone()); let _h = do_test_0reserve_splice_counterparty_validation(true, true, true, config.clone()); + assert_eq!(a, ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()); - // TODO: Skip 0FC channels for now as these always have an output on the commitment, the P2A - // output. We will be able to withdraw up to the dust limit of the funding script, which - // is checked in interactivetx. Still need to double check whether that's what we actually - // want. + config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = false; + config.channel_handshake_config.negotiate_anchor_zero_fee_commitments = true; + let a = do_test_0reserve_splice_counterparty_validation(false, false, false, config.clone()); + let _b = do_test_0reserve_splice_counterparty_validation(true, false, false, config.clone()); + let _c = do_test_0reserve_splice_counterparty_validation(false, true, false, config.clone()); + let _d = do_test_0reserve_splice_counterparty_validation(true, true, false, config.clone()); + + let _e = do_test_0reserve_splice_counterparty_validation(false, false, true, config.clone()); + let _f = do_test_0reserve_splice_counterparty_validation(true, false, true, config.clone()); + let _g = do_test_0reserve_splice_counterparty_validation(false, true, true, config.clone()); + let _h = do_test_0reserve_splice_counterparty_validation(true, true, true, config.clone()); + + assert_eq!(a, ChannelTypeFeatures::anchors_zero_fee_commitments()); } #[cfg(test)] @@ -7569,13 +7595,12 @@ fn do_test_0reserve_splice_holder_validation( let details = &nodes[0].node.list_channels()[0]; let channel_type = details.channel_type.clone().unwrap(); - let feerate = 253; + let feerate = + if channel_type == ChannelTypeFeatures::anchors_zero_fee_commitments() { 0 } else { 253 }; let spiked_feerate = if channel_type == ChannelTypeFeatures::only_static_remote_key() { feerate * FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32 - } else if channel_type == ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies() { - feerate } else { - panic!("Unexpected channel type"); + feerate }; let anchors_sat = if channel_type == ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies() { @@ -7603,13 +7628,18 @@ fn do_test_0reserve_splice_holder_validation( - chan_utils::commit_tx_fee_sat(feerate, 0, &channel_type) * 1000; assert!(node_0_to_local_output_msat / 1000 < dust_limit_satoshis); let commit_tx = &get_local_commitment_txn!(nodes[0], channel_id)[0]; - assert_eq!(commit_tx.output.len(), if anchors_sat == 0 { 1 } else { 2 }); + assert_eq!( + commit_tx.output.len(), + if channel_type == ChannelTypeFeatures::only_static_remote_key() { 1 } else { 2 } + ); assert_eq!( commit_tx.output.last().unwrap().value, Amount::from_sat(available_capacity_msat / 1000) ); - if anchors_sat != 0 { + if channel_type == ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies() { assert_eq!(commit_tx.output[0].value, Amount::from_sat(330)); + } else if channel_type == ChannelTypeFeatures::anchors_zero_fee_commitments() { + assert_eq!(commit_tx.output[0].value, Amount::ZERO); } available_capacity_msat / 1000 @@ -7618,27 +7648,36 @@ fn do_test_0reserve_splice_holder_validation( }; // The estimated fees to splice out a single output at 253sat/kw - let estimated_fees = 183; - let splice_out_max_value = if counterparty_has_output && node_0_is_initiator { + let estimated_fees_sat = 183; + let mut splice_out_max_value = if counterparty_has_output && node_0_is_initiator { let commit_tx_fee_sat = chan_utils::commit_tx_fee_sat(spiked_feerate, 1, &channel_type); Amount::from_sat( - initiator_value_to_self_sat - commit_tx_fee_sat - anchors_sat - estimated_fees, + initiator_value_to_self_sat - commit_tx_fee_sat - anchors_sat - estimated_fees_sat, ) } else if !counterparty_has_output && node_0_is_initiator { let commit_tx_fee_sat = chan_utils::commit_tx_fee_sat(spiked_feerate, 0, &channel_type); Amount::from_sat( initiator_value_to_self_sat - commit_tx_fee_sat - - anchors_sat - estimated_fees + - anchors_sat - estimated_fees_sat - dust_limit_satoshis, ) } else if counterparty_has_output && !node_0_is_initiator { - Amount::from_sat(initiator_value_to_self_sat - estimated_fees) + Amount::from_sat(initiator_value_to_self_sat - estimated_fees_sat) } else if !counterparty_has_output && !node_0_is_initiator { - Amount::from_sat(initiator_value_to_self_sat - estimated_fees - dust_limit_satoshis) + Amount::from_sat(initiator_value_to_self_sat - estimated_fees_sat - dust_limit_satoshis) } else { panic!("unexpected case!"); }; + + if channel_value_sat + < splice_out_max_value.to_sat() + estimated_fees_sat + MIN_CHANNEL_VALUE_SATOSHIS + { + splice_out_max_value = Amount::from_sat( + channel_value_sat.saturating_sub(estimated_fees_sat + MIN_CHANNEL_VALUE_SATOSHIS), + ); + } + let outputs = vec![TxOut { value: splice_out_max_value + if splice_passes { Amount::ZERO } else { Amount::ONE_SAT }, script_pubkey: nodes[0].wallet_source.get_change_script().unwrap(), @@ -7650,7 +7689,7 @@ fn do_test_0reserve_splice_holder_validation( let initiator_details = &initiator.node.list_channels()[0]; assert_eq!( initiator_details.next_splice_out_maximum_sat, - splice_out_max_value.to_sat() + estimated_fees + splice_out_max_value.to_sat() + estimated_fees_sat ); if splice_passes { @@ -7663,8 +7702,8 @@ fn do_test_0reserve_splice_holder_validation( } else { assert!(initiate_splice_out(initiator, acceptor, channel_id, outputs).is_err()); let splice_out_value = - splice_out_max_value + Amount::from_sat(estimated_fees) + Amount::ONE_SAT; - let splice_out_max_value = splice_out_max_value + Amount::from_sat(estimated_fees); + splice_out_max_value + Amount::from_sat(estimated_fees_sat) + Amount::ONE_SAT; + let splice_out_max_value = splice_out_max_value + Amount::from_sat(estimated_fees_sat); let cannot_be_funded = format!( "Channel {channel_id} cannot be funded: Our \ splice-out value of {splice_out_value} is greater than the maximum \ @@ -7703,13 +7742,12 @@ fn do_test_0reserve_splice_counterparty_validation( let details = &nodes[0].node.list_channels()[0]; let channel_type = details.channel_type.clone().unwrap(); - let feerate = 253; + let feerate = + if channel_type == ChannelTypeFeatures::anchors_zero_fee_commitments() { 0 } else { 253 }; let spiked_feerate = if channel_type == ChannelTypeFeatures::only_static_remote_key() { feerate * FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32 - } else if channel_type == ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies() { - feerate } else { - panic!("Unexpected channel type"); + feerate }; let anchors_sat = if channel_type == ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies() { @@ -7737,13 +7775,18 @@ fn do_test_0reserve_splice_counterparty_validation( - chan_utils::commit_tx_fee_sat(spiked_feerate, 0, &channel_type) * 1000; assert!(node_0_to_local_output_msat / 1000 < dust_limit_satoshis); let commit_tx = &get_local_commitment_txn!(nodes[0], channel_id)[0]; - assert_eq!(commit_tx.output.len(), if anchors_sat == 0 { 1 } else { 2 }); + assert_eq!( + commit_tx.output.len(), + if channel_type == ChannelTypeFeatures::only_static_remote_key() { 1 } else { 2 } + ); assert_eq!( commit_tx.output.last().unwrap().value, Amount::from_sat(available_capacity_msat / 1000) ); - if anchors_sat != 0 { + if channel_type == ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies() { assert_eq!(commit_tx.output[0].value, Amount::from_sat(330)); + } else if channel_type == ChannelTypeFeatures::anchors_zero_fee_commitments() { + assert_eq!(commit_tx.output[0].value, Amount::ZERO); } available_capacity_msat / 1000 @@ -7751,7 +7794,7 @@ fn do_test_0reserve_splice_counterparty_validation( channel_value_sat }; - let splice_out_value_incl_fees = if counterparty_has_output && node_0_is_initiator { + let mut splice_out_value_incl_fees = if counterparty_has_output && node_0_is_initiator { let commit_tx_fee_sat = chan_utils::commit_tx_fee_sat(spiked_feerate, 1, &channel_type); Amount::from_sat(initiator_value_to_self_sat - commit_tx_fee_sat - anchors_sat) } else if !counterparty_has_output && node_0_is_initiator { @@ -7767,6 +7810,10 @@ fn do_test_0reserve_splice_counterparty_validation( panic!("unexpected case!"); }; + if channel_value_sat < splice_out_value_incl_fees.to_sat() + MIN_CHANNEL_VALUE_SATOSHIS { + splice_out_value_incl_fees = + Amount::from_sat(channel_value_sat.saturating_sub(MIN_CHANNEL_VALUE_SATOSHIS)); + } let (initiator, acceptor) = if node_0_is_initiator { (&nodes[0], &nodes[1]) } else { (&nodes[1], &nodes[0]) }; @@ -7775,6 +7822,9 @@ fn do_test_0reserve_splice_counterparty_validation( let funding_contribution_sat = -(splice_out_value_incl_fees.to_sat() as i64) - if splice_passes { 0 } else { 1 }; + let post_channel_value_sat = + channel_value_sat.checked_add_signed(funding_contribution_sat).unwrap(); + let outputs = vec![TxOut { // Splice out some dummy amount to get past the initiator's validation, // we'll modify the message in-flight. @@ -7812,11 +7862,22 @@ fn do_test_0reserve_splice_counterparty_validation( let cannot_splice_out = if u64::try_from(funding_contribution_sat.abs()).unwrap() > initiator_value_to_self_sat { + // They obviously can't afford their contribution, so we fail before even + // querying `TxBuilder` format!( "Got non-closing error: Their contribution candidate {funding_contribution_sat}sat \ is greater than their total balance in the channel {initiator_value_to_self_sat}sat" ) + } else if post_channel_value_sat < MIN_CHANNEL_VALUE_SATOSHIS { + // We require all spliced channels to have a value of at least 1000 satoshis after the splice + format!( + "Got non-closing error: Spliced channel value must be at least {MIN_CHANNEL_VALUE_SATOSHIS} satoshis. \ + It would be {post_channel_value_sat}" + ) } else { + // Last but not least, `TxBuilder` decides whether all parties can afford + // HTLCs, anchors, and transaction fees while retaining at least one + // output on the commitments format!( "Got non-closing error: Channel {channel_id} cannot \ be spliced; Balance exhausted on local commitment" diff --git a/lightning/src/sign/tx_builder.rs b/lightning/src/sign/tx_builder.rs index ade54c603ca..00daccd09ee 100644 --- a/lightning/src/sign/tx_builder.rs +++ b/lightning/src/sign/tx_builder.rs @@ -11,6 +11,7 @@ use crate::ln::chan_utils::{ }; use crate::ln::channel::{ get_v2_channel_reserve_satoshis, CommitmentStats, ANCHOR_OUTPUT_VALUE_SATOSHI, + MIN_CHANNEL_VALUE_SATOSHIS, }; use crate::prelude::*; use crate::types::features::ChannelTypeFeatures; @@ -416,6 +417,11 @@ fn get_next_splice_out_maximum_sat( (local_balance_before_fee_msat / 1000).saturating_sub(min_balance_sat); } + if channel_value_satoshis < next_splice_out_maximum_sat + MIN_CHANNEL_VALUE_SATOSHIS { + next_splice_out_maximum_sat = + channel_value_satoshis.saturating_sub(MIN_CHANNEL_VALUE_SATOSHIS); + } + next_splice_out_maximum_sat } diff --git a/lightning/src/util/config.rs b/lightning/src/util/config.rs index c83eb697461..78ab45d58c2 100644 --- a/lightning/src/util/config.rs +++ b/lightning/src/util/config.rs @@ -326,7 +326,8 @@ pub struct ChannelHandshakeLimits { /// only applies to inbound channels. /// /// Default value: `1000` - /// (Minimum of [`ChannelHandshakeConfig::their_channel_reserve_proportional_millionths`]) + /// + /// Minimum value: `1000` (Any values less will be treated as `1000` instead.) pub min_funding_satoshis: u64, /// The remote node sets a limit on the minimum size of HTLCs we can send to them. This allows /// you to limit the maximum minimum-size they can require.