Privacy: randomized coin selection (BnB changeless + single random draw) (#3408)

* 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

Cindy committed Aug 19, 2026 at 07:51 UTC 3b098e35ff45fa8b35ad31fdeea754c8ca498923
5 files changed +301 -4
.github/workflows/pr_test_build_linux.yml
+4
@@ -12,6 +12,10 @@ defaults:
12
13 jobs:
14 PR_test_build:
15 + # Fork PRs don't have access to repository secrets, so the generated
16 + # lib/.secrets.g.dart would be empty and the build fails to compile.
17 + # Skip for forks, mirroring the Android workflow's internal-build guard.
18 + if: github.event.pull_request.head.repo.fork == false
19 runs-on: [Linux, amd64, forlinux]
20 container:
21 image: ghcr.io/cake-tech/cake_wallet:debian13-flutter3.41.9-ndkr28-go1.24.1-ruststablenightly
cw_bitcoin/lib/coin_selection.dart new
+88
@@ -0,0 +1,88 @@
1 +import 'dart:math';
2 +
3 +int effectiveValue(int value, int inputCost) => value - inputCost;
4 +
5 +class SelectedCoins {
6 + final List<int> indices;
7 + final bool hasChange;
8 + const SelectedCoins(this.indices, this.hasChange);
9 +}
10 +
11 +SelectedCoins? branchAndBound(List<int> effValues, int target, int costOfChange,
12 + {int maxTries = 100000}) {
13 + final n = effValues.length;
14 + final order = List<int>.generate(n, (i) => i)
15 + ..sort((a, b) => effValues[b].compareTo(effValues[a]));
16 + final sorted = [for (final i in order) effValues[i]];
17 + final suffix = List<int>.filled(n + 1, 0);
18 + for (var i = n - 1; i >= 0; i--) suffix[i] = suffix[i + 1] + sorted[i];
19 + final upper = target + costOfChange;
20 + List<int>? best;
21 + final picked = <int>[];
22 + var tries = 0;
23 + void dfs(int i, int sum) {
24 + if (best != null || tries++ >= maxTries) return;
25 + if (sum > upper) return;
26 + if (sum >= target) { best = List.of(picked); return; }
27 + if (i >= n || sum + suffix[i] < target) return;
28 + picked.add(order[i]); dfs(i + 1, sum + sorted[i]); picked.removeLast();
29 + dfs(i + 1, sum);
30 + }
31 + dfs(0, 0);
32 + return best == null ? null : SelectedCoins(best!, false);
33 +}
34 +
35 +SelectedCoins? singleRandomDraw(List<int> effValues, int target, int minChange, Random rng) {
36 + final order = List<int>.generate(effValues.length, (i) => i)..shuffle(rng);
37 + final picked = <int>[]; var sum = 0;
38 + for (final i in order) {
39 + picked.add(i); sum += effValues[i];
40 + if (sum >= target + minChange) return SelectedCoins(picked, true);
41 + }
42 + return null;
43 +}
44 +
45 +/// Branch-and-bound over effective values (value minus the cost of spending the
46 +/// input at the current fee rate). [inputCosts] is parallel to [values] so each
47 +/// input pays for its own script type's size. A match means the excess over
48 +/// [target] stays within [window], so the remainder can be absorbed into the fee
49 +/// instead of creating a change output. Returns null when no such subset exists.
50 +SelectedCoins? changelessMatch({
51 + required List<int> values,
52 + required int target,
53 + required List<int> inputCosts,
54 + required int window,
55 + int maxTries = 100000,
56 +}) {
57 + assert(values.length == inputCosts.length);
58 + final keep = <int>[];
59 + final eff = <int>[];
60 + for (var i = 0; i < values.length; i++) {
61 + final e = effectiveValue(values[i], inputCosts[i]);
62 + if (e > 0) {
63 + keep.add(i);
64 + eff.add(e);
65 + }
66 + }
67 + final match = branchAndBound(eff, target, window, maxTries: maxTries);
68 + if (match == null) return null;
69 + return SelectedCoins([for (final i in match.indices) keep[i]], false);
70 +}
71 +
72 +class InsufficientFundsException implements Exception { const InsufficientFundsException(); }
73 +
74 +SelectedCoins selectCoins({required List<int> values, required int target,
75 + required int inputCost, required int costOfChange, required int minChange, Random? rng}) {
76 + final keep = <int>[]; final eff = <int>[];
77 + for (var i = 0; i < values.length; i++) {
78 + final e = effectiveValue(values[i], inputCost);
79 + if (e > 0) { keep.add(i); eff.add(e); }
80 + }
81 + SelectedCoins? map(SelectedCoins? s) =>
82 + s == null ? null : SelectedCoins([for (final i in s.indices) keep[i]], s.hasChange);
83 + final bnb = map(branchAndBound(eff, target, costOfChange));
84 + if (bnb != null) return bnb;
85 + final srd = map(singleRandomDraw(eff, target, minChange, rng ?? Random.secure()));
86 + if (srd != null) return srd;
87 + throw const InsufficientFundsException();
88 +}
cw_bitcoin/lib/electrum_wallet.dart
+106 -4
@@ -1,6 +1,7 @@
1 import 'dart:async';
2 import 'dart:convert';
3 import 'dart:isolate';
4 +import 'dart:math' show Random;
5
6 import 'package:bitcoin_base/bitcoin_base.dart';
7 import 'package:cw_bitcoin/lightning/lightning_wallet.dart';
@@ -10,6 +11,7 @@ import 'package:cw_core/root_dir.dart';
11 import 'package:cw_core/utils/proxy_wrapper.dart';
12 import 'package:cw_core/utils/print_verbose.dart';
13 import 'package:cw_bitcoin/bitcoin_wallet.dart';
14 +import 'package:cw_bitcoin/coin_selection.dart';
15 import 'package:cw_bitcoin/litecoin_wallet.dart';
16 import 'package:shared_preferences/shared_preferences.dart';
17 import 'package:blockchain_utils/blockchain_utils.dart';
@@ -261,6 +263,29 @@ abstract class ElectrumWalletBase
263 static int estimatedTransactionSize(int inputsCount, int outputsCounts) =>
264 inputsCount * 68 + outputsCounts * 34 + 10;
265
266 + // vbytes an input of the given script type adds to a transaction. The generic
267 + // estimate above assumes P2WPKH (68); legacy and taproot inputs differ enough
268 + // to break changeless-match arithmetic if not accounted for.
269 + static int estimatedInputSize(BitcoinAddressType type) {
270 + if (type == P2pkhAddressType.p2pkh) return 148;
271 + if (type == P2shAddressType.p2wpkhInP2sh) return 91;
272 + if (type == SegwitAddresType.p2tr) return 58;
273 + if (type == SegwitAddresType.p2wsh) return 105;
274 + if (type == SilentPaymentsAddresType.p2sp) return 58; // spent via taproot
275 + return 68;
276 + }
277 +
278 + // vbytes an output of the given script type adds to a transaction. Silent
279 + // payment outputs are delivered as taproot.
280 + static int estimatedOutputSize(BitcoinAddressType type) {
281 + if (type == P2pkhAddressType.p2pkh) return 34;
282 + if (type == P2shAddressType.p2wpkhInP2sh) return 32;
283 + if (type == SegwitAddresType.p2tr) return 43;
284 + if (type == SegwitAddresType.p2wsh) return 43;
285 + if (type == SilentPaymentsAddresType.p2sp) return 43;
286 + return 31;
287 + }
288 +
289 // Parses the account index from a BIP-44/49/84/86 derivation path.
290 // e.g. "m/84'/0'/1'" → 1. Returns 0 for unrecognised formats.
291 static int _parseAccountIndex(String? derivationPath) {
@@ -881,11 +906,23 @@ abstract class ElectrumWalletBase
906 bool _isBelowDust(BigInt amount) =>
907 amount <= networkDustAmount && network != BitcoinNetwork.testnet;
908
909 + // Random draw priority per outpoint. Assigned lazily with a secure RNG and kept
910 + // until the next createTransaction call, so the recursive estimate passes of one
911 + // transaction build all see the same input order (reshuffling between passes made
912 + // fee estimation unstable). Cleared per transaction so each send is a fresh draw.
913 + final Random _coinSelectionRng = Random.secure();
914 + final Map<String, int> _coinSelectionOrder = {};
915 +
916 + int _coinSelectionPriority(BitcoinUnspent utx) => _coinSelectionOrder.putIfAbsent(
917 + '${utx.hash}:${utx.vout}', () => _coinSelectionRng.nextInt(1 << 32));
918 +
919 UtxoDetails _createUTXOS({
920 required bool sendAll,
921 required bool paysToSilentPayment,
922 int credentialsAmount = 0,
923 int? inputsCount,
924 + int feeRate = 0,
925 + int? outputsVBytes,
926 UnspentCoinType coinTypeToSpendFrom = UnspentCoinType.any,
927 }) {
928 List<UtxoWithAddress> utxos = [];
@@ -914,8 +951,52 @@ abstract class ElectrumWalletBase
951 }).toList();
952 final unconfirmedCoins = availableInputs.where((utx) => utx.confirmations == 0).toList();
953
917 - // sort the unconfirmed coins so that mweb coins are last:
918 - availableInputs.sort((a, b) => a.bitcoinAddressRecord.type == SegwitAddresType.mweb ? 1 : -1);
954 + // Single Random Draw: order the pool by each coin's random priority so selection is
955 + // non-deterministic, removing the predictable address/scan order (a fingerprint).
956 + // The priority is stable across the repeated calls of one transaction build.
957 + // MWEB coins are kept last afterwards.
958 + availableInputs.sort((a, b) {
959 + final byPriority = _coinSelectionPriority(a).compareTo(_coinSelectionPriority(b));
960 + if (byPriority != 0) return byPriority;
961 + return '${a.hash}:${a.vout}'.compareTo('${b.hash}:${b.vout}');
962 + });
963 + availableInputs = [
964 + ...availableInputs.where((u) => u.bitcoinAddressRecord.type != SegwitAddresType.mweb),
965 + ...availableInputs.where((u) => u.bitcoinAddressRecord.type == SegwitAddresType.mweb),
966 + ];
967 +
968 + // Branch-and-bound: prefer an input set whose excess over the amount plus its own fee
969 + // stays below dust, so the caller drops the change output and the send is changeless.
970 + // When no such set exists, the shuffled pool below acts as a single random draw.
971 + final canTryChangeless = !sendAll &&
972 + inputsCount == null &&
973 + credentialsAmount > 0 &&
974 + feeRate > 0 &&
975 + outputsVBytes != null &&
976 + outputsVBytes > 0 &&
977 + !availableInputs.any((u) => u.bitcoinAddressRecord.type == SegwitAddresType.mweb);
978 + if (canTryChangeless) {
979 + final match = changelessMatch(
980 + values: [for (final u in availableInputs) u.value],
981 + // estimatedTransactionSize(0, 0) is the fixed tx overhead (version,
982 + // counters, locktime); the outputs' own vbytes come pre-computed per type.
983 + target: credentialsAmount + (estimatedTransactionSize(0, 0) + outputsVBytes!) * feeRate,
984 + inputCosts: [
985 + for (final u in availableInputs)
986 + estimatedInputSize(u.bitcoinAddressRecord.type) * feeRate
987 + ],
988 + window: networkDustAmount.toInt(),
989 + );
990 + if (match != null) {
991 + final chosen = match.indices.toSet();
992 + availableInputs = [
993 + for (final i in match.indices) availableInputs[i],
994 + for (var i = 0; i < availableInputs.length; i++)
995 + if (!chosen.contains(i)) availableInputs[i],
996 + ];
997 + inputsCount = match.indices.length;
998 + }
999 + }
1000
1001 for (int i = 0; i < availableInputs.length; i++) {
1002 final utx = availableInputs[i];
@@ -1131,10 +1212,25 @@ abstract class ElectrumWalletBase
1212 }
1213 }
1214
1215 + // Per-type output sizes for the changeless target. MWEB outputs follow a
1216 + // different size model entirely, so they disable the changeless path (null).
1217 + int? outputsVBytes = 0;
1218 + for (final out in outputs) {
1219 + final type =
1220 + out.isSilentPayment == true ? SilentPaymentsAddresType.p2sp : _getScriptType(out.address);
1221 + if (type == SegwitAddresType.mweb) {
1222 + outputsVBytes = null;
1223 + break;
1224 + }
1225 + outputsVBytes = outputsVBytes! + estimatedOutputSize(type);
1226 + }
1227 +
1228 final utxoDetails = _createUTXOS(
1229 sendAll: false,
1230 credentialsAmount: credentialsAmount.amount.toInt(),
1231 inputsCount: inputsCount,
1232 + feeRate: feeRate,
1233 + outputsVBytes: outputsVBytes,
1234 paysToSilentPayment: hasSilentPayment,
1235 coinTypeToSpendFrom: coinTypeToSpendFrom,
1236 );
@@ -1397,6 +1493,10 @@ abstract class ElectrumWalletBase
1493 @override
1494 Future<PendingTransaction> createTransaction(Object credentials) async {
1495 try {
1496 + // New transaction, new random draw: drop the previous input ordering so this
1497 + // build gets fresh priorities, then keep them fixed for all estimate passes.
1498 + _coinSelectionOrder.clear();
1499 +
1500 // start by updating unspent coins
1501 await updateAllUnspents();
1502
@@ -2220,11 +2320,13 @@ abstract class ElectrumWalletBase
2320 }
2321 }
2322
2223 - // If still not enough, add UTXOs until the fee is covered
2323 + // If still not enough, add UTXOs until the fee is covered, drawing them at
2324 + // random instead of in the predictable wallet scan order (address, then age).
2325 if (remainingFee > BigInt.zero) {
2326 final unusedUtxos = unspentCoins
2327 .where((utxo) => utxo.isSending && !utxo.isFrozen && utxo.confirmations! > 0)
2227 - .toList();
2328 + .toList()
2329 + ..shuffle(Random.secure());
2330
2331 for (final utxo in unusedUtxos) {
2332 final address = RegexUtils.addressTypeFromStr(utxo.address, network);
cw_bitcoin/lib/payjoin/manager.dart
+3
@@ -295,6 +295,9 @@ class PayjoinManager {
295 await _wallet.updateAllUnspents();
296 utxos = _wallet.getUtxoWithPrivateKeys(confirmedOnly: true);
297 }
298 + // Candidates arrive in wallet scan order (address, then age), which is
299 + // predictable; shuffle so the receiver's input choice can't mirror it.
300 + utxos.shuffle(Random.secure());
301 mainToIsolateSendPort?.send({
302 'requestId': message['requestId'],
303 'result': utxos,
cw_bitcoin/test/coin_selection_test.dart new
+100
@@ -0,0 +1,100 @@
1 +import 'dart:math';
2 +import "package:cw_bitcoin/coin_selection.dart";
3 +import "package:flutter_test/flutter_test.dart";
4 +void main() {
5 + test('effectiveValue', () {
6 + expect(effectiveValue(10000, 136), 9864);
7 + expect(effectiveValue(100, 136), -36);
8 + });
9 + test('BnB finds changeless match in window', () {
10 + final r = branchAndBound([200,100,90,80], 300, 50);
11 + expect(r, isNotNull); expect(r!.hasChange, isFalse);
12 + final vals=[200,100,90,80]; final sum=r.indices.map((i)=>vals[i]).reduce((a,b)=>a+b);
13 + expect(sum>=300 && sum<=350, isTrue);
14 + });
15 + test('BnB null when no subset in window', () {
16 + expect(branchAndBound([1000,900], 300, 5), isNull);
17 + });
18 + test('SRD with change', () {
19 + final r = singleRandomDraw([500,500,500,500], 700, 50, Random(1));
20 + expect(r, isNotNull); expect(r!.hasChange, isTrue);
21 + });
22 + test('SRD randomizes across seeds', () {
23 + final a = (singleRandomDraw([100,101,102,103,104,105],150,10,Random(1))!.indices..sort());
24 + final b = (singleRandomDraw([100,101,102,103,104,105],150,10,Random(9))!.indices..sort());
25 + expect(a, isNot(equals(b)));
26 + });
27 + test('SRD null on insufficient funds', () {
28 + expect(singleRandomDraw([100,100], 500, 10, Random(1)), isNull);
29 + });
30 + test('selectCoins prefers changeless BnB, else SRD', () {
31 + expect(selectCoins(values:[200,100,90],target:300,inputCost:0,costOfChange:20,minChange:10).hasChange, isFalse);
32 + expect(selectCoins(values:[500,500,500],target:700,inputCost:0,costOfChange:5,minChange:10,rng:Random(1)).hasChange, isTrue);
33 + });
34 + test('selectCoins drops non-positive effective values', () {
35 + // coin of value 50 with inputCost 136 -> effective -86 -> dropped; only the 1000 usable
36 + final r = selectCoins(values:[50,1000],target:500,inputCost:136,costOfChange:5,minChange:10,rng:Random(1));
37 + expect(r.indices, equals([1]));
38 + });
39 + test('changelessMatch finds a set whose effective sum lands in the window', () {
40 + // inputCost 100: values [50, 400, 300, 200] -> eff [dropped, 300, 200, 100]
41 + // target 500, window 46: eff {300, 200} = 500, exact
42 + final r = changelessMatch(
43 + values: [50, 400, 300, 200], target: 500, inputCosts: [100, 100, 100, 100], window: 46);
44 + expect(r, isNotNull);
45 + expect(r!.hasChange, isFalse);
46 + final effSum = r.indices.map((i) => [50, 400, 300, 200][i] - 100).reduce((a, b) => a + b);
47 + expect(effSum >= 500 && effSum <= 546, isTrue);
48 + expect(r.indices.contains(0), isFalse); // negative-eff coin never selected
49 + });
50 + test('changelessMatch returns null when no subset lands in the window', () {
51 + expect(
52 + changelessMatch(values: [10000, 9000], target: 500, inputCosts: [100, 100], window: 46),
53 + isNull);
54 + });
55 + test('selectCoins throws when insufficient', () {
56 + expect(() => selectCoins(values:[100,100],target:500,inputCost:0,costOfChange:5,minChange:10),
57 + throwsA(isA<InsufficientFundsException>()));
58 + });
59 + test('changeless pipeline: leftover absorbed into fee is non-negative and below dust', () {
60 + // Mirrors the _createUTXOS / estimateTxForAmount arithmetic with the wallet's
61 + // 68*inputs + 34*outputs + 10 vBytes model, at 10 sat/vB with 1 recipient output.
62 + const feeRate = 10;
63 + const amount = 50000;
64 + final values = [60700, 30000, 21800, 9000, 5000];
65 + const target = amount + (34 * 1 + 10) * feeRate;
66 + final r = changelessMatch(
67 + values: values,
68 + target: target,
69 + inputCosts: List.filled(values.length, 68 * feeRate),
70 + window: 546);
71 + expect(r, isNotNull);
72 + final inAmount = r!.indices.map((i) => values[i]).reduce((a, b) => a + b);
73 + final feeNoChange = (68 * r.indices.length + 34 * 1 + 10) * feeRate;
74 + final leftover = inAmount - amount - feeNoChange;
75 + expect(leftover >= 0, isTrue); // the caller never recurses for more inputs
76 + expect(leftover <= 546, isTrue); // fee overpay is bounded by the dust limit
77 + });
78 + test('BnB terminates and returns null on large pools with no possible match', () {
79 + // 300 even effective values, odd target, zero window: no subset can ever match,
80 + // so the search must stop at maxTries instead of exploring 2^300 branches.
81 + final values = List<int>.generate(300, (i) => 1000000 + i * 2);
82 + final r = changelessMatch(
83 + values: values, target: 1500001, inputCosts: List.filled(300, 10), window: 0);
84 + expect(r, isNull);
85 + });
86 + test('changelessMatch charges each input its own script-type cost', () {
87 + // Legacy input (148 vB) vs segwit input (68 vB) at 10 sat/vB: same value, but
88 + // the legacy coin's effective value is 800 lower. Target only reachable when
89 + // the cheaper segwit coin is chosen: eff segwit = 10000-680 = 9320.
90 + const feeRate = 10;
91 + final r = changelessMatch(
92 + values: [10000, 10000],
93 + target: 9320,
94 + inputCosts: [148 * feeRate, 68 * feeRate],
95 + window: 0,
96 + );
97 + expect(r, isNotNull);
98 + expect(r!.indices, equals([1]));
99 + });
100 +}