Repository navigation
Description
TL;DR
Asking the wallet's coin selector for an amount close to the wallet's whole balance — the normal shape of a "send everything" / "Max" request — can take thousands of times longer than an ordinary payment, and in practice never finishes once a wallet has around 30 or more UTXOs. The same code path is used by every real fund-moving transaction (Shield, identity registration, identity top-up, invitations), not just balance previews, so this can hang a real send with no attacker involved.
User story
As a wallet integrator (e.g. dash-evo-tool), I want selecting inputs for a "send everything" style request to complete in reasonable time regardless of how many UTXOs the wallet holds, so that an ordinary drain/consolidate send never hangs the wallet.
As a wallet integrator, I want any coin-selection strategy that does an exhaustive/branch-and-bound search to bound its own cost (a feasibility prune, a node budget, or a depth cap), so a legitimate caller can't accidentally trigger unbounded work just by asking for a target close to the total.
Scenario
Actual behavior: CoinSelector::select_coins with the default SelectionStrategy::BranchAndBound strategy calls branch_and_bound_with_size → find_exact_match (coin_selection.rs:360-413, 606-660). That recursive search's only pruning rule is an overshoot check — if new_total > required + dust_threshold * 10 { continue; }. There is no undershoot / feasibility prune ("even taking every remaining UTXO, can this branch ever reach the target?"), no recursion-depth cap, and no node or time budget.
For a target close to the wallet's total balance, almost nothing overshoots by more than the tolerance, so the one prune that exists barely fires, and the search degenerates toward exploring the full 2^N subset lattice of the UTXO set. A second, independent trigger: one large UTXO plus many small ones, with the target reachable from the large UTXO alone — the large UTXO gets skipped at the very first branch (using it alone overshoots the tolerance), and once skipped it can never be picked again in any later branch, so the rest of the search exhaustively (and pointlessly) tries every combination of the small UTXOs, none of which can reach the target.
Measured directly with a standalone extraction of the real control flow (not an approximation):
| UTXOs | search nodes visited |
|---|---|
| 20 | 1,048,576 |
| 24 | 16,777,216 |
| 28 | 268,435,456 |
| 32 | does not terminate in reasonable time |
An ordinary small-payment target over the same UTXO sets: 5 nodes, regardless of size.
Measured against the real CoinSelector (not the standalone extraction — see the committed test below), 22 near-equal, non-power-of-two UTXO values, comparing an ordinary target against a near-total-balance target over the same set:
- Against
18c68d4c(the revdash-evo-toolcurrently pins): 2.99s vs 60µs (~50,000x) - Against current
dev(9c87ccb3): 3.05s vs 134µs (~22,700x)
Both confirm the bug is present on dev today, not just on an older pinned commit.
Expected behavior: Selecting inputs for a target close to the wallet's total should not be dramatically more expensive than selecting for an ordinary target over the same UTXO set. find_exact_match needs a real bound — at minimum a feasibility/undershoot prune (skip a branch once the maximum reachable sum from here, taking every remaining UTXO, can't meet required), and ideally also a node or depth budget as defense in depth, falling back to the existing accumulate_coins_with_size path (as the function already does on failure) rather than exhausting the search space.
Detailed discussion
Repro test, committed locally, not yet pushed (happy to open a PR if useful) — key-wallet/src/wallet/managed_wallet_info/coin_selection.rs, mod tests:
#[test]
fn branch_and_bound_near_total_balance_target_is_exponentially_slower() {
// `find_exact_match`'s only prune is an overshoot check
// (`new_total > required + dust_threshold * 10`). There is no undershoot /
// feasibility prune ("even taking every remaining UTXO, can this branch ever
// reach the target?"), no depth cap, no node budget. A target close to the
// wallet's total balance defeats the one prune that exists almost completely,
// and the recursive search degenerates toward exploring the full 2^N subset
// lattice. An ordinary payment target over the same UTXO set is unaffected --
// this is purely a function of how close the target sits to what's achievable,
// not of UTXO count on its own.
//
// Deliberately modest N: even at N=22 the asymmetry is already drastic, and it
// gets exponentially worse with every additional UTXO (independently measured:
// N=20 -> 1,048,576 search nodes, N=24 -> 16,777,216, N=28 -> 268,435,456,
// N=32 -> does not terminate in a reasonable time at all). Values are
// near-equal but distinct (no power-of-two ladder), so no branch is a cheap
// free exact match that would mask the effect.
const N: u8 = 22;
let utxos: Vec<Utxo> = (0..N)
.map(|i| Utxo::dummy(i, 1_000_000 + i as u64 * 137_711, 100, false, true))
.collect();
let total: u64 = utxos.iter().map(|u| u.value()).sum();
let fee_rate = FeeRate::new(1000);
let selector = CoinSelector::new(SelectionStrategy::BranchAndBound);
let t0 = std::time::Instant::now();
let _ = selector.select_coins(&utxos, 1_500_000, fee_rate, 200);
let ordinary_elapsed = t0.elapsed();
// The exact shape a "send my full balance" request produces for ANY caller of
// this selector -- not contrived, not caller-specific.
let near_total_target = total.saturating_sub(10_000);
let t1 = std::time::Instant::now();
let _ = selector.select_coins(&utxos, near_total_target, fee_rate, 200);
let near_total_elapsed = t1.elapsed();
// A correctly-pruned exact-match search should not be highly sensitive to how
// close the target sits to the total -- both calls search the same N UTXOs.
// 50x is a deliberately generous, hardware-independent margin; the real ratio
// measured here is several orders of magnitude larger, and only worsens with N.
assert!(
near_total_elapsed
< ordinary_elapsed.saturating_mul(50).max(std::time::Duration::from_millis(50)),
"near-total-balance target took {near_total_elapsed:?} vs {ordinary_elapsed:?} for \
an ordinary target over the same {N} UTXOs -- find_exact_match's missing \
undershoot/feasibility prune turns a target close to the wallet's balance into a \
near-exhaustive 2^N search over the whole UTXO set."
);
}Result on current dev (9c87ccb3):
thread '...::branch_and_bound_near_total_balance_target_is_exponentially_slower' panicked:
near-total-balance target took 3.051467381s vs 134.384µs for an ordinary target over the
same 22 UTXOs -- find_exact_match's missing undershoot/feasibility prune turns a target
close to the wallet's balance into a near-exhaustive 2^N search over the whole UTXO set.
Why this reaches real, fund-moving transactions, not just balance previews: rs-platform-wallet's build_asset_lock_transaction (build.rs:56-151) — the function behind every real Shield / identity-registration / identity-topup / invitation send — delegates straight to ManagedWalletInfo::build_asset_lock_with_signer (asset_lock_builder.rs:256) with no .set_selection_strategy() override anywhere in the chain, so it uses TransactionBuilder's default (BranchAndBound) unguarded. An ordinary "send my full balance" on a wallet with ~25-30+ spendable UTXOs is enough to hit this on a real transaction build — no special access or crafted input needed. It also runs under the caller's wallet-manager write lock in every consumer I've checked, so a hang there blocks all other wallet operations, not just the one send, until the process is killed.
Related but distinct: #911 (closed) is the same file and a neighboring symptom (near-total-balance sends misbehaving), but a different function (accumulate_coins_with_size's change-output sizing) and a different specific defect — already fixed on dev. This issue is about find_exact_match's missing prune, which #911's fix did not touch.
Suggested fix direction
Add a feasibility/undershoot prune to find_exact_match: before recursing into utxos[i], check whether the maximum possible sum from index.. (precomputed once, e.g. a suffix-sum array) can still reach required; if not, prune the whole remaining suffix at this depth rather than trying each element individually. That alone collapses the dust-only-subtree case from 2^N to roughly linear. A node/time budget as defense in depth (falling back to accumulate_coins_with_size, as the function already does on total failure) would guard against any other pathological input shape that a feasibility prune alone doesn't anticipate.
🤖 Co-authored by Claudius the Magnificent AI Agent
Activity
fix(key-wallet): rewrite branch-and-bound coin selection (#918)
fix(key-wallet): rewrite branch-and-bound coin selection (#918)
fix(key-wallet): rewrite branch-and-bound coin selection (#918)
fix(key-wallet): rewrite branch-and-bound coin selection (#918) (#919)
fix(wallets): use selector ceiling for asset-lock Max (#937)