mirror of
https://github.com/Such-Software/hash-wallet.git
synced 2026-10-26 06:08:40 +01:00
* Randomize coin selection with single random draw The greedy selection walked the unspent pool in a predictable order (address generation order, then per-address server order), a fingerprint an analyst can exploit. Shuffle the pool before the accumulate-until-covered loop so the input set is chosen non-deterministically (single random draw). MWEB coins are still kept last. Branch-and-bound (changeless exact match) is a larger follow-up. * Add BnB + SRD coin selection primitives Pure, wallet-independent coin selector: branch-and-bound for an exact changeless match within the cost-of-change window, single-random-draw fallback (shuffled, injectable RNG) when no exact match exists, and selectCoins tying them together over effective values. This is the basis for replacing the greedy accumulation in _createUTXOS so sends produce no change when possible and a non-deterministic selection otherwise. Validated with dart test (9 cases); wiring into _createUTXOS is a separate step. * Use BnB changeless matching in coin selection Before the shuffled greedy walk, run branch-and-bound over effective values (value minus per-input fee cost) looking for an input set whose excess over amount plus fee stays below dust. When found, order those inputs first and cap the walk at their count: the caller then computes a change below dust, drops the change output, and absorbs the residue into the fee, producing a changeless transaction with no residual change fingerprint. When no match exists, selection falls back to the shuffled pool, which the greedy walk turns into a single random draw. BnB is skipped for sendAll, forced input counts and pools holding MWEB coins. changelessMatch filters non-positive effective values and maps indices back to the original pool. * Cover changeless fee bounds and BnB termination Assert the end-to-end arithmetic the wallet performs around a branch-and-bound match: with the 68/34/10 vBytes model, the leftover the caller absorbs into the fee is never negative (no re-selection loop) and never exceeds the dust limit (bounded fee overpay). Also pin termination: a large pool with no possible match returns null through the maxTries cap instead of exploring the full search tree. * Use a secure RNG for coin selection randomness The selection shuffle and the single-random-draw fallback exist to be unpredictable, so seed them from Random.secure() instead of the default PRNG, matching what Core and bdk use for coin selection. Pool sizes are small, so the cost is negligible. Tests keep injecting a seeded Random for determinism. * Randomize RBF and payjoin input candidate order Two secondary paths still consumed unspentCoins in wallet scan order (address generation order, then per-address age), the same predictable order removed from the main selection path: - replaceByFee walked the unused-UTXO list in scan order when the fee bump needed extra inputs - the payjoin receiver handed input candidates to the payjoin library in scan order, letting ties inside its selection mirror that order Shuffle both with a secure RNG so no input-selection path exposes the wallet's address or coin age ordering. * ci: skip Linux PR build on forks (no secrets access) * Account for script-type sizes in changeless matching * Keep coin selection order stable within a transaction build
89 lines
3.3 KiB
Dart
89 lines
3.3 KiB
Dart
import 'dart:math';
|
|
|
|
int effectiveValue(int value, int inputCost) => value - inputCost;
|
|
|
|
class SelectedCoins {
|
|
final List<int> indices;
|
|
final bool hasChange;
|
|
const SelectedCoins(this.indices, this.hasChange);
|
|
}
|
|
|
|
SelectedCoins? branchAndBound(List<int> effValues, int target, int costOfChange,
|
|
{int maxTries = 100000}) {
|
|
final n = effValues.length;
|
|
final order = List<int>.generate(n, (i) => i)
|
|
..sort((a, b) => effValues[b].compareTo(effValues[a]));
|
|
final sorted = [for (final i in order) effValues[i]];
|
|
final suffix = List<int>.filled(n + 1, 0);
|
|
for (var i = n - 1; i >= 0; i--) suffix[i] = suffix[i + 1] + sorted[i];
|
|
final upper = target + costOfChange;
|
|
List<int>? best;
|
|
final picked = <int>[];
|
|
var tries = 0;
|
|
void dfs(int i, int sum) {
|
|
if (best != null || tries++ >= maxTries) return;
|
|
if (sum > upper) return;
|
|
if (sum >= target) { best = List.of(picked); return; }
|
|
if (i >= n || sum + suffix[i] < target) return;
|
|
picked.add(order[i]); dfs(i + 1, sum + sorted[i]); picked.removeLast();
|
|
dfs(i + 1, sum);
|
|
}
|
|
dfs(0, 0);
|
|
return best == null ? null : SelectedCoins(best!, false);
|
|
}
|
|
|
|
SelectedCoins? singleRandomDraw(List<int> effValues, int target, int minChange, Random rng) {
|
|
final order = List<int>.generate(effValues.length, (i) => i)..shuffle(rng);
|
|
final picked = <int>[]; var sum = 0;
|
|
for (final i in order) {
|
|
picked.add(i); sum += effValues[i];
|
|
if (sum >= target + minChange) return SelectedCoins(picked, true);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// Branch-and-bound over effective values (value minus the cost of spending the
|
|
/// input at the current fee rate). [inputCosts] is parallel to [values] so each
|
|
/// input pays for its own script type's size. A match means the excess over
|
|
/// [target] stays within [window], so the remainder can be absorbed into the fee
|
|
/// instead of creating a change output. Returns null when no such subset exists.
|
|
SelectedCoins? changelessMatch({
|
|
required List<int> values,
|
|
required int target,
|
|
required List<int> inputCosts,
|
|
required int window,
|
|
int maxTries = 100000,
|
|
}) {
|
|
assert(values.length == inputCosts.length);
|
|
final keep = <int>[];
|
|
final eff = <int>[];
|
|
for (var i = 0; i < values.length; i++) {
|
|
final e = effectiveValue(values[i], inputCosts[i]);
|
|
if (e > 0) {
|
|
keep.add(i);
|
|
eff.add(e);
|
|
}
|
|
}
|
|
final match = branchAndBound(eff, target, window, maxTries: maxTries);
|
|
if (match == null) return null;
|
|
return SelectedCoins([for (final i in match.indices) keep[i]], false);
|
|
}
|
|
|
|
class InsufficientFundsException implements Exception { const InsufficientFundsException(); }
|
|
|
|
SelectedCoins selectCoins({required List<int> values, required int target,
|
|
required int inputCost, required int costOfChange, required int minChange, Random? rng}) {
|
|
final keep = <int>[]; final eff = <int>[];
|
|
for (var i = 0; i < values.length; i++) {
|
|
final e = effectiveValue(values[i], inputCost);
|
|
if (e > 0) { keep.add(i); eff.add(e); }
|
|
}
|
|
SelectedCoins? map(SelectedCoins? s) =>
|
|
s == null ? null : SelectedCoins([for (final i in s.indices) keep[i]], s.hasChange);
|
|
final bnb = map(branchAndBound(eff, target, costOfChange));
|
|
if (bnb != null) return bnb;
|
|
final srd = map(singleRandomDraw(eff, target, minChange, rng ?? Random.secure()));
|
|
if (srd != null) return srd;
|
|
throw const InsufficientFundsException();
|
|
}
|