Bitcoin Core  25.99.0
P2P Digital Currency
coinselection.cpp
Go to the documentation of this file.
1 // Copyright (c) 2022 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <policy/feerate.h>
6 #include <policy/policy.h>
9 #include <test/fuzz/fuzz.h>
10 #include <test/fuzz/util.h>
11 #include <test/util/setup_common.h>
12 #include <wallet/coinselection.h>
13 
14 #include <vector>
15 
16 namespace wallet {
17 
18 static void AddCoin(const CAmount& value, int n_input, int n_input_bytes, int locktime, std::vector<COutput>& coins, CFeeRate fee_rate)
19 {
21  tx.vout.resize(n_input + 1);
22  tx.vout[n_input].nValue = value;
23  tx.nLockTime = locktime; // all transactions get different hashes
24  coins.emplace_back(COutPoint(tx.GetHash(), n_input), tx.vout.at(n_input), /*depth=*/0, n_input_bytes, /*spendable=*/true, /*solvable=*/true, /*safe=*/true, /*time=*/0, /*from_me=*/true, fee_rate);
25 }
26 
27 // Randomly distribute coins to instances of OutputGroup
28 static void GroupCoins(FuzzedDataProvider& fuzzed_data_provider, const std::vector<COutput>& coins, const CoinSelectionParams& coin_params, bool positive_only, std::vector<OutputGroup>& output_groups)
29 {
30  auto output_group = OutputGroup(coin_params);
31  bool valid_outputgroup{false};
32  for (auto& coin : coins) {
33  if (!positive_only || (positive_only && coin.GetEffectiveValue() > 0)) {
34  output_group.Insert(std::make_shared<COutput>(coin), /*ancestors=*/0, /*descendants=*/0);
35  }
36  // If positive_only was specified, nothing was inserted, leading to an empty output group
37  // that would be invalid for the BnB algorithm
38  valid_outputgroup = !positive_only || output_group.GetSelectionAmount() > 0;
39  if (valid_outputgroup && fuzzed_data_provider.ConsumeBool()) {
40  output_groups.push_back(output_group);
41  output_group = OutputGroup(coin_params);
42  valid_outputgroup = false;
43  }
44  }
45  if (valid_outputgroup) output_groups.push_back(output_group);
46 }
47 
48 // Returns true if the result contains an error and the message is not empty
49 static bool HasErrorMsg(const util::Result<SelectionResult>& res) { return !util::ErrorString(res).empty(); }
50 
51 FUZZ_TARGET(coinselection)
52 {
53  FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
54  std::vector<COutput> utxo_pool;
55 
56  const CFeeRate long_term_fee_rate{ConsumeMoney(fuzzed_data_provider, /*max=*/COIN)};
57  const CFeeRate effective_fee_rate{ConsumeMoney(fuzzed_data_provider, /*max=*/COIN)};
58  const CAmount cost_of_change{ConsumeMoney(fuzzed_data_provider, /*max=*/COIN)};
59  const CAmount target{fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(1, MAX_MONEY)};
60  const bool subtract_fee_outputs{fuzzed_data_provider.ConsumeBool()};
61 
62  FastRandomContext fast_random_context{ConsumeUInt256(fuzzed_data_provider)};
63  CoinSelectionParams coin_params{fast_random_context};
64  coin_params.m_subtract_fee_outputs = subtract_fee_outputs;
65  coin_params.m_long_term_feerate = long_term_fee_rate;
66  coin_params.m_effective_feerate = effective_fee_rate;
67  coin_params.change_output_size = fuzzed_data_provider.ConsumeIntegralInRange<int>(10, 1000);
68  coin_params.m_change_fee = effective_fee_rate.GetFee(coin_params.change_output_size);
69 
70  // Create some coins
71  CAmount total_balance{0};
72  int next_locktime{0};
73  LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000)
74  {
75  const int n_input{fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 10)};
76  const int n_input_bytes{fuzzed_data_provider.ConsumeIntegralInRange<int>(100, 10000)};
77  const CAmount amount{fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(1, MAX_MONEY)};
78  if (total_balance + amount >= MAX_MONEY) {
79  break;
80  }
81  AddCoin(amount, n_input, n_input_bytes, ++next_locktime, utxo_pool, coin_params.m_effective_feerate);
82  total_balance += amount;
83  }
84 
85  std::vector<OutputGroup> group_pos;
86  GroupCoins(fuzzed_data_provider, utxo_pool, coin_params, /*positive_only=*/true, group_pos);
87  std::vector<OutputGroup> group_all;
88  GroupCoins(fuzzed_data_provider, utxo_pool, coin_params, /*positive_only=*/false, group_all);
89 
90  // Run coinselection algorithms
91  const auto result_bnb = SelectCoinsBnB(group_pos, target, cost_of_change, MAX_STANDARD_TX_WEIGHT);
92 
93  auto result_srd = SelectCoinsSRD(group_pos, target, fast_random_context, MAX_STANDARD_TX_WEIGHT);
94  if (result_srd) result_srd->ComputeAndSetWaste(cost_of_change, cost_of_change, 0);
95 
96  CAmount change_target{GenerateChangeTarget(target, coin_params.m_change_fee, fast_random_context)};
97  auto result_knapsack = KnapsackSolver(group_all, target, change_target, fast_random_context, MAX_STANDARD_TX_WEIGHT);
98  if (result_knapsack) result_knapsack->ComputeAndSetWaste(cost_of_change, cost_of_change, 0);
99 
100  // If the total balance is sufficient for the target and we are not using
101  // effective values, Knapsack should always find a solution (unless the selection exceeded the max tx weight).
102  if (total_balance >= target && subtract_fee_outputs && !HasErrorMsg(result_knapsack)) {
103  assert(result_knapsack);
104  }
105 }
106 
107 } // namespace wallet
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:26
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:33
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:36
Fast randomness source.
Definition: random.h:144
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
Definition: fuzz.h:18
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:81
util::Result< SelectionResult > SelectCoinsBnB(std::vector< OutputGroup > &utxo_pool, const CAmount &selection_target, const CAmount &cost_of_change, int max_weight)
static void AddCoin(const CAmount &value, int n_input, int n_input_bytes, int locktime, std::vector< COutput > &coins, CFeeRate fee_rate)
CAmount GenerateChangeTarget(const CAmount payment_value, const CAmount change_fee, FastRandomContext &rng)
Choose a random change target for each transaction to make it harder to fingerprint the Core wallet b...
std::vector< OutputGroup > & GroupCoins(const std::vector< COutput > &available_coins, bool subtract_fee_outputs=false)
util::Result< SelectionResult > KnapsackSolver(std::vector< OutputGroup > &groups, const CAmount &nTargetValue, CAmount change_target, FastRandomContext &rng, int max_weight)
util::Result< SelectionResult > SelectCoinsSRD(const std::vector< OutputGroup > &utxo_pool, CAmount target_value, FastRandomContext &rng, int max_weight)
Select coins by Single Random Draw.
FUZZ_TARGET(coinselection)
static bool HasErrorMsg(const util::Result< SelectionResult > &res)
Definition: spend.cpp:528
static constexpr unsigned int MAX_STANDARD_TX_WEIGHT
The maximum weight for transactions we're willing to relay/mine.
Definition: policy.h:27
A mutable version of CTransaction.
Definition: transaction.h:380
uint256 GetHash() const
Compute the hash of this CMutableTransaction.
Definition: transaction.cpp:68
std::vector< CTxOut > vout
Definition: transaction.h:382
bool empty() const
Definition: translation.h:29
Parameters for one iteration of Coin Selection.
bool m_subtract_fee_outputs
Indicate that we are subtracting the fee from outputs.
A group of UTXOs paid to the same output script.
CAmount ConsumeMoney(FuzzedDataProvider &fuzzed_data_provider, const std::optional< CAmount > &max) noexcept
Definition: util.cpp:17
uint256 ConsumeUInt256(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.h:148
assert(!tx.IsCoinBase())