Skip to content

Commit

Permalink
Add random and inOrderUntilEnough selection algorithms
Browse files Browse the repository at this point in the history
  • Loading branch information
MatthewLM committed Nov 22, 2023
1 parent 409319f commit 7d2f895
Show file tree
Hide file tree
Showing 2 changed files with 129 additions and 21 deletions.
76 changes: 63 additions & 13 deletions coinlib/lib/src/tx/coin_selection.dart
Original file line number Diff line number Diff line change
Expand Up @@ -124,23 +124,24 @@ class CoinSelection {
}

/// A simple selection algorithm that selects inputs from the [candidates]
/// starting from the largest value until the required amount has been
/// reached and then the selected inputs are given a random order.
factory CoinSelection.largestFirst({
/// in the order that they are given until the required amount has been
/// reached. If there are not enough coins, all shall be selected and
/// [enoughFunds] shall be false.
/// If [randomise] is set to true, the order of inputs shall be randomised
/// after being selected. This is useful for candidates that are not already
/// randomised as it may avoid giving clues to the algorithm being used.
factory CoinSelection.inOrderUntilEnough({
int version = Transaction.currentVersion,
required Iterable<InputCandidate> candidates,
required Iterable<Output> recipients,
required Program changeProgram,
required BigInt feePerKb,
required BigInt minFee,
required BigInt minChange,
bool randomise = false,
int locktime = 0,
}) {

final sorted = candidates.toList().sorted(
(a, b) => b.value.compareTo(a.value),
);

CoinSelection trySelection(Iterable<InputCandidate> selected)
=> CoinSelection(
version: version,
Expand All @@ -153,19 +154,68 @@ class CoinSelection {
locktime: locktime,
);

final list = candidates.toList();

CoinSelection selection = trySelection([]);
for (int i = 0; i < sorted.length; i++) {
selection = trySelection(sorted.take(i+1));
for (int i = 0; i < list.length; i++) {
selection = trySelection(list.take(i+1));
if (selection.enoughFunds) break;
}

// Randomising makes it less obvious this algo is being used
final selected = selection.selected.toList();
selected.shuffle();
return trySelection(selected);
return randomise
? trySelection(selection.selected.toList()..shuffle())
: selection;

}

/// A simple selection algorithm that selects inputs randomly from the
/// [candidates] until the required amount has been reached.
factory CoinSelection.random({
int version = Transaction.currentVersion,
required Iterable<InputCandidate> candidates,
required Iterable<Output> recipients,
required Program changeProgram,
required BigInt feePerKb,
required BigInt minFee,
required BigInt minChange,
int locktime = 0,
}) => CoinSelection.inOrderUntilEnough(
version: version,
candidates: candidates.toList()..shuffle(),
recipients: recipients,
changeProgram: changeProgram,
feePerKb: feePerKb,
minFee: minFee,
minChange: minChange,
locktime: locktime,
);

/// A simple selection algorithm that selects inputs from the [candidates]
/// starting from the largest value until the required amount has been
/// reached. The order of the selected inputs are randomised.
factory CoinSelection.largestFirst({
int version = Transaction.currentVersion,
required Iterable<InputCandidate> candidates,
required Iterable<Output> recipients,
required Program changeProgram,
required BigInt feePerKb,
required BigInt minFee,
required BigInt minChange,
int locktime = 0,
}) => CoinSelection.inOrderUntilEnough(
version: version,
candidates: candidates.toList().sorted(
(a, b) => b.value.compareTo(a.value),
),
recipients: recipients,
changeProgram: changeProgram,
feePerKb: feePerKb,
minFee: minFee,
minChange: minChange,
randomise: true,
locktime: locktime,
);

/// Obtains the transaction with selected inputs and outputs including any
/// change at a random location, ready to be signed. Throws
/// [InsufficientFunds] if there is not enough input value to meet the output
Expand Down
74 changes: 66 additions & 8 deletions coinlib/test/tx/coin_selection_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -272,14 +272,74 @@ void main() {

});

void expectSelectedValues(CoinSelection selection, List<int> values) => expect(
selection.selected.map((candidate) => candidate.value.toInt()),
unorderedEquals(values),
);
void expectSelectedValues(CoinSelection selection, List<int> values) {
print(selection.selected.map((candidate) => candidate.value.toInt()));
expect(
selection.selected.map((candidate) => candidate.value.toInt()),
unorderedEquals(values),
);
expect(selection.version, 1234);
expect(selection.locktime, 0xabcd1234);
}

test(".largestFirst()", () {
final candidates = [coin*4, coin, coin*3, coin, coin*2];

test(".inOrderUntilEnough()", () {

void expectInOrder(List<int> selected, int outValue) {
final selection = CoinSelection.inOrderUntilEnough(
version: 1234,
candidates: candidates.map((value) => candidateForValue(value)),
recipients: [outputForValue(outValue)],
changeProgram: changeProgram,
feePerKb: feePerKb, minFee: minFee, minChange: minChange,
locktime: 0xabcd1234,
);
expectSelectedValues(selection, selected);
}

final candidates = [coin*4, coin, coin*3, coin, coin*2];
// Single input required
expectInOrder(candidates.sublist(0, 1), coin*3);
// Covers with first three, even if only two needed
expectInOrder(candidates.sublist(0, 3), coin*5);
// Need all
expectInOrder(candidates, coin*10);
// Select all even though not enough
expectInOrder(candidates, coin*12);

});

test(".random", () {

CoinSelection getRandom(int outValue) => CoinSelection.random(
version: 1234,
candidates: candidates.map((value) => candidateForValue(value)),
recipients: [outputForValue(outValue)],
changeProgram: changeProgram,
feePerKb: feePerKb, minFee: minFee, minChange: minChange,
locktime: 0xabcd1234,
);

// Only need one
{
final selected = getRandom(coin~/2).selected;
expect(selected.length, 1);
expect(selected[0].value.toInt(), isIn(candidates));
}
// Need multiple
{
final selection = getRandom(coin*2);
expect(selection.selected.length, lessThanOrEqualTo(3));
expect(selection.inputValue.toInt(), greaterThan(coin*2));
}
// Need all
expectSelectedValues(getRandom(coin*10), candidates);
// Select all even though not enough
expectSelectedValues(getRandom(coin*12), candidates);

});

test(".largestFirst()", () {

void expectLargestFirst(List<int> selected, int outValue) {
final selection = CoinSelection.largestFirst(
Expand All @@ -291,8 +351,6 @@ void main() {
locktime: 0xabcd1234,
);
expectSelectedValues(selection, selected);
expect(selection.version, 1234);
expect(selection.locktime, 0xabcd1234);
}

// Can cover with single largest
Expand Down

0 comments on commit 7d2f895

Please sign in to comment.