diff --git a/CHANGELOG.md b/CHANGELOG.md index 0bfbebcfd9..008576c8bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,9 @@ The format is loosely based on [Keep a Changelog](https://keepachangelog.com/en/ as the target is met, and among equally economical solutions the one spending fewer inputs is preferred, so default sends spend fewer UTXOs and produce smaller change. + - coin selection now prefers confirmed UTXOs, reducing the chance that a + send is rejected for forming an oversized mempool cluster; the full UTXO set + is still used when the confirmed UTXOs cannot cover the payment. - Node: - `node-daemon` and `node-gui`: the "reckless" mode of the chainstate database is now @@ -50,7 +53,6 @@ The format is loosely based on [Keep a Changelog](https://keepachangelog.com/en/ option distinguishable from an explicit opt-out, so a value from the configuration file is no longer silently overridden by the command line or the environment. - ## [1.4.5] - 2026-11-10 ### Added @@ -128,6 +130,7 @@ The format is loosely based on [Keep a Changelog](https://keepachangelog.com/en/ non-interactive mode the process would exit before the background rescan could run, leaving the wallet stuck at genesis so that every subsequent wallet open had to rescan the whole blockchain. + ## [1.4.0] - 2026-07-09 ### Added diff --git a/wallet/src/account/mod.rs b/wallet/src/account/mod.rs index 7d5735fcfb..7fd4931ddb 100644 --- a/wallet/src/account/mod.rs +++ b/wallet/src/account/mod.rs @@ -85,7 +85,7 @@ use wallet_types::{ use crate::{ SendRequest, WalletError, WalletResult, account::output_cache::StaleInMempool, - account::utxo_selector::{OutputGroup, select_coins}, + account::utxo_selector::{OutputGroup, select_coins_preferring_confirmed}, destination_getters::{HtlcSpendingCondition, get_tx_output_destination}, key_chain::{AccountKeyChains, KeyChainError, VRFAccountKeyChains}, send_request::{ @@ -113,7 +113,7 @@ pub use self::{ utxo_selector::{CoinSelectionAlgo, UtxoSelectorError}, }; -#[derive(Debug)] +#[derive(Debug, Clone, Copy)] pub struct CurrentFeeRate { pub current_fee_rate: FeeRate, pub consolidate_fee_rate: FeeRate, @@ -278,39 +278,72 @@ impl Account { Ok(()) })?; - let (utxos, selection_algo) = if input_utxos.is_empty() { - ( + let (utxos, confirmed_utxos, selection_algo) = if input_utxos.is_empty() { + let utxo_types = UtxoType::Transfer | UtxoType::LockThenTransfer | UtxoType::IssueNft; + let utxos = self.get_utxos( + utxo_types, + median_time, + UtxoState::Confirmed | UtxoState::InMempool | UtxoState::Inactive, + WithLocked::Unlocked, + ); + // Prefer confirmed utxos during selection: spending an unconfirmed utxo forms a + // mempool cluster, which is size limited, so building on top of confirmed utxos + // reduces the chance of producing a tx that the mempool would reject (see issue + // #2066). The confirmed-only set is tried first, with a fallback to the full set. + // + // The confirmed-only query filters by the state of the transaction that produced + // an utxo, and its state mask is also used to decide whether an utxo has already + // been consumed. That mask alone would therefore re-admit utxos of confirmed + // transactions that the wallet has already spent in its own pending (in-mempool) + // or evicted transactions. Intersecting with the full set keeps the confirmed + // pool a subset of it, so such utxos stay excluded from selection. + let confirmed_utxos = { + let full_outpoints: BTreeSet<_> = + utxos.iter().map(|(outpoint, _)| outpoint.clone()).collect(); self.get_utxos( - UtxoType::Transfer | UtxoType::LockThenTransfer | UtxoType::IssueNft, + utxo_types, median_time, - UtxoState::Confirmed | UtxoState::InMempool | UtxoState::Inactive, + UtxoState::Confirmed.into(), WithLocked::Unlocked, - ), + ) + .into_iter() + .filter(|(outpoint, _)| full_outpoints.contains(outpoint)) + .collect() + }; + ( + utxos, + Some(confirmed_utxos), selection_algo.unwrap_or(CoinSelectionAlgo::Randomize), ) } else { let selection_algo = selection_algo.unwrap_or(CoinSelectionAlgo::UsePreselected); - match input_utxos { + let utxos = match input_utxos { SelectedInputs::Utxos(input_utxos) => { let current_block_info = BlockInfo { height: self.account_info.best_block_height(), timestamp: median_time, }; - ( - self.output_cache.find_utxos(current_block_info, input_utxos)?, - selection_algo, - ) + self.output_cache.find_utxos(current_block_info, input_utxos)? } - SelectedInputs::Inputs(ref inputs) => ( - inputs.iter().map(|(outpoint, utxo)| (outpoint.clone(), utxo)).collect(), - selection_algo, - ), - } + SelectedInputs::Inputs(ref inputs) => { + inputs.iter().map(|(outpoint, utxo)| (outpoint.clone(), utxo)).collect() + } + }; + (utxos, None, selection_algo) }; let current_fee_rate = fee_rates.current_fee_rate; let mut utxos_by_currency = self.utxo_output_groups_by_currency(fee_rates, &pay_fee_with_currency, utxos)?; + let mut confirmed_utxos_by_currency = confirmed_utxos + .map(|confirmed_utxos| { + self.utxo_output_groups_by_currency( + fee_rates, + &pay_fee_with_currency, + confirmed_utxos, + ) + }) + .transpose()?; let amount_to_be_paid_in_currency_with_fees = output_currency_amounts.remove(&pay_fee_with_currency).unwrap_or(Amount::ZERO); @@ -343,6 +376,9 @@ impl Account { .iter() .map(|(currency, output_amount)| -> WalletResult<_> { let utxos = utxos_by_currency.remove(currency).unwrap_or(vec![]); + let confirmed_utxos = confirmed_utxos_by_currency + .as_mut() + .map(|by_currency| by_currency.remove(currency).unwrap_or_default()); let preselected_amount = preselected_inputs .amounts .remove(currency) @@ -355,7 +391,8 @@ impl Account { change_address.clone(), )?; - let selection_result = select_coins( + let selection_result = select_coins_preferring_confirmed( + confirmed_utxos, utxos, output_amount.sub(preselected_amount).unwrap_or(Amount::ZERO), PayFee::DoNotPayFeeWithThisCurrency, @@ -394,6 +431,9 @@ impl Account { .try_collect()?; let utxos = utxos_by_currency.remove(&pay_fee_with_currency).unwrap_or(vec![]); + let confirmed_utxos = confirmed_utxos_by_currency + .as_mut() + .map(|by_currency| by_currency.remove(&pay_fee_with_currency).unwrap_or_default()); let num_inputs = selected_inputs .values() @@ -439,7 +479,8 @@ impl Account { change_address.clone(), )?; - let selection_result = select_coins( + let selection_result = select_coins_preferring_confirmed( + confirmed_utxos, utxos, (amount_to_be_paid_in_currency_with_fees - preselected_amount).unwrap_or(Amount::ZERO), PayFee::PayFeeWithThisCurrency, diff --git a/wallet/src/account/utxo_selector/mod.rs b/wallet/src/account/utxo_selector/mod.rs index 3def738284..670109ee5f 100644 --- a/wallet/src/account/utxo_selector/mod.rs +++ b/wallet/src/account/utxo_selector/mod.rs @@ -746,6 +746,52 @@ pub fn select_coins( } } +/// Select coins, preferring confirmed utxos. +/// +/// A transaction that spends an unconfirmed (in-mempool) utxo forms a cluster with the +/// transaction that produced it, and the mempool limits how big such a cluster may be. To +/// reduce the chance of building a transaction that the mempool would reject, this first tries +/// to reach the target using `confirmed_pool` alone. Only if that doesn't work (for example +/// because the confirmed utxos aren't enough) does it fall back to `full_pool`, which also +/// contains the unconfirmed utxos. +/// +/// `confirmed_pool` is `None` when there is no preference to apply, for example when the caller +/// selected the inputs explicitly; in that case `full_pool` is used directly. +/// +/// This deliberately ignores waste: a selection from the confirmed pool is used even when the +/// full pool admits a cheaper one. +pub fn select_coins_preferring_confirmed( + confirmed_pool: Option>, + full_pool: Vec, + selection_target: Amount, + pay_fees: PayFee, + cost_of_change: Amount, + coin_selection_algo: CoinSelectionAlgo, + max_tx_weight: usize, +) -> Result { + if let Some(confirmed_pool) = confirmed_pool + && let Ok(result) = select_coins( + confirmed_pool, + selection_target, + pay_fees, + cost_of_change, + coin_selection_algo, + max_tx_weight, + ) + { + return Ok(result); + } + + select_coins( + full_pool, + selection_target, + pay_fees, + cost_of_change, + coin_selection_algo, + max_tx_weight, + ) +} + fn select_random_coins( mut utxo_pool: Vec, selection_target: Amount, diff --git a/wallet/src/account/utxo_selector/tests.rs b/wallet/src/account/utxo_selector/tests.rs index ed0b9bcd0a..3abad3be14 100644 --- a/wallet/src/account/utxo_selector/tests.rs +++ b/wallet/src/account/utxo_selector/tests.rs @@ -23,6 +23,24 @@ use test_utils::random::{Seed, make_seedable_rng}; use super::*; +fn add_output_with_weight(value: Amount, weight: usize, groups: &mut Vec) { + let outpoint = UtxoOutPoint::new( + OutPointSourceId::BlockReward(Id::::new(Uint256::from_u64(1).into())), + 0, + ); + let tx_output = TxOutput::Transfer(OutputValue::Coin(value), Destination::AnyoneCanSpend); + + let outputs = vec![(outpoint.into(), tx_output)]; + + groups.push(OutputGroup { + outputs, + value, + fee: Amount::ZERO, + long_term_fee: Amount::ZERO, + weight, + }); +} + fn add_output(value: Amount, groups: &mut Vec) { let outpoint = UtxoOutPoint::new( OutPointSourceId::BlockReward(Id::::new(Uint256::from_u64(1).into())), @@ -451,6 +469,118 @@ fn test_srd_solver_max_weight(#[case] seed: Seed) { assert_eq!(result.unwrap_err(), UtxoSelectorError::MaxWeightExceeded); } +#[test] +fn test_prefer_confirmed_uses_confirmed_when_sufficient() { + // The confirmed pool alone can cover the target, so it must be used and the full pool + // (deliberately given a different, larger value) must be left untouched. + let mut confirmed = vec![]; + add_output(Amount::from_atoms(60), &mut confirmed); + let mut full = vec![]; + add_output(Amount::from_atoms(1000), &mut full); + + let result = select_coins_preferring_confirmed( + Some(confirmed), + full, + Amount::from_atoms(50), + PayFee::PayFeeWithThisCurrency, + Amount::ZERO, + CoinSelectionAlgo::Randomize, + 100, + ) + .unwrap(); + + assert_eq!(result.effective_value, Amount::from_atoms(60)); +} + +#[test] +fn test_prefer_confirmed_falls_back_when_confirmed_insufficient() { + // The confirmed pool can't reach the target on its own, so selection must fall back to the + // full pool, which additionally contains a larger (unconfirmed) utxo. + let mut confirmed = vec![]; + add_output(Amount::from_atoms(10), &mut confirmed); + let mut full = vec![]; + add_output(Amount::from_atoms(10), &mut full); + add_output(Amount::from_atoms(90), &mut full); + + let result = select_coins_preferring_confirmed( + Some(confirmed), + full, + Amount::from_atoms(50), + PayFee::PayFeeWithThisCurrency, + Amount::ZERO, + CoinSelectionAlgo::Randomize, + 100, + ) + .unwrap(); + + assert!(result.effective_value >= Amount::from_atoms(50)); +} + +#[test] +fn test_prefer_confirmed_without_preference_uses_full_pool() { + // With no confirmed pool the full pool is used directly. + let mut full = vec![]; + add_output(Amount::from_atoms(70), &mut full); + + let result = select_coins_preferring_confirmed( + None, + full, + Amount::from_atoms(50), + PayFee::PayFeeWithThisCurrency, + Amount::ZERO, + CoinSelectionAlgo::Randomize, + 100, + ) + .unwrap(); + + assert_eq!(result.effective_value, Amount::from_atoms(70)); +} + +#[test] +fn test_prefer_confirmed_falls_back_when_confirmed_exceeds_weight_cap() { + // Every confirmed utxo is too heavy for the weight cap, so selection from the + // confirmed pool fails; the full pool's lighter utxos cover the target. + let mut confirmed = vec![]; + add_output_with_weight(Amount::from_atoms(100), 2, &mut confirmed); + let mut full = vec![]; + add_output_with_weight(Amount::from_atoms(60), 1, &mut full); + + let result = select_coins_preferring_confirmed( + Some(confirmed), + full, + Amount::from_atoms(50), + PayFee::PayFeeWithThisCurrency, + Amount::ZERO, + CoinSelectionAlgo::Randomize, + 1, + ) + .unwrap(); + + // The exact full-pool value proves the fallback produced this selection. + assert_eq!(result.effective_value, Amount::from_atoms(60)); +} + +#[test] +fn test_prefer_confirmed_falls_back_on_empty_confirmed_bucket() { + // An empty confirmed bucket (no confirmed utxos of this currency) is not a + // preference failure: selection falls back to the full pool. + let mut full = vec![]; + add_output(Amount::from_atoms(70), &mut full); + + let result = select_coins_preferring_confirmed( + Some(vec![]), + full, + Amount::from_atoms(50), + PayFee::PayFeeWithThisCurrency, + Amount::ZERO, + CoinSelectionAlgo::Randomize, + 100, + ) + .unwrap(); + + assert_eq!(result.effective_value, Amount::from_atoms(70)); +} + #[rstest] #[trace] #[case(Seed::from_entropy())]