LCOV - code coverage report
Current view: top level - src/wallet/test/fuzz - coinselection.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 99.7 % 306 305
Test Date: 2026-11-03 06:39:55 Functions: 100.0 % 20 20
Branches: 62.3 % 570 355

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2022-present 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>
       7                 :             : #include <primitives/transaction.h>
       8                 :             : #include <test/fuzz/FuzzedDataProvider.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 <numeric>
      15                 :             : #include <span>
      16                 :             : #include <vector>
      17                 :             : 
      18                 :             : namespace wallet {
      19                 :             : 
      20                 :     1784791 : static void AddCoin(const CAmount& value, int n_input, int n_input_bytes, int locktime, std::vector<COutput>& coins, CFeeRate fee_rate)
      21                 :             : {
      22                 :     1784791 :     CMutableTransaction tx;
      23         [ +  - ]:     1784791 :     tx.vout.resize(n_input + 1);
      24         [ +  - ]:     1784791 :     tx.vout[n_input].nValue = value;
      25                 :     1784791 :     tx.nLockTime = locktime; // all transactions get different hashes
      26   [ +  -  +  -  :     1784791 :     coins.emplace_back(COutPoint(tx.GetHash(), n_input), tx.vout.at(n_input), /*depth=*/0, n_input_bytes, /*solvable=*/true, /*safe=*/true, /*time=*/0, /*from_me=*/true, fee_rate);
                   +  - ]
      27                 :     1784791 : }
      28                 :             : 
      29                 :             : // Randomly distribute coins to instances of OutputGroup
      30                 :        2426 : static void GroupCoins(FuzzedDataProvider& fuzzed_data_provider, const std::vector<COutput>& coins, const CoinSelectionParams& coin_params, bool positive_only, std::vector<OutputGroup>& output_groups)
      31                 :             : {
      32                 :        2426 :     auto output_group = OutputGroup(coin_params);
      33                 :        2426 :     bool valid_outputgroup{false};
      34         [ +  + ]:     1850735 :     for (auto& coin : coins) {
      35   [ +  +  +  + ]:     1848309 :         if (!positive_only || (positive_only && coin.GetEffectiveValue() > 0)) {
      36   [ +  -  +  - ]:     3482912 :             output_group.Insert(std::make_shared<COutput>(coin), /*ancestors=*/0, /*cluster_count=*/0);
      37                 :             :         }
      38                 :             :         // If positive_only was specified, nothing was inserted, leading to an empty output group
      39                 :             :         // that would be invalid for the BnB algorithm
      40   [ +  +  +  -  :     1848309 :         valid_outputgroup = !positive_only || output_group.GetSelectionAmount() > 0;
                   +  + ]
      41         [ +  + ]:     1744444 :         if (valid_outputgroup && fuzzed_data_provider.ConsumeBool()) {
      42         [ +  - ]:      917227 :             output_groups.push_back(output_group);
      43                 :      917227 :             output_group = OutputGroup(coin_params);
      44                 :      917227 :             valid_outputgroup = false;
      45                 :             :         }
      46                 :             :     }
      47   [ +  +  +  - ]:        2426 :     if (valid_outputgroup) output_groups.push_back(output_group);
      48                 :        2426 : }
      49                 :             : 
      50                 :        3756 : static CAmount CreateCoins(FuzzedDataProvider& fuzzed_data_provider, std::vector<COutput>& utxo_pool, CoinSelectionParams& coin_params, int& next_locktime)
      51                 :             : {
      52                 :        3756 :     CAmount total_balance{0};
      53   [ +  +  +  + ]:     1364340 :     LIMITED_WHILE (fuzzed_data_provider.ConsumeBool(), 10000) {
      54                 :     1361153 :         const int n_input{fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 10)};
      55                 :     1361153 :         const int n_input_bytes{fuzzed_data_provider.ConsumeIntegralInRange<int>(41, 10000)};
      56                 :     1361153 :         const CAmount amount{fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(1, MAX_MONEY)};
      57         [ +  + ]:     1361153 :         if (total_balance + amount >= MAX_MONEY) {
      58                 :             :             break;
      59                 :             :         }
      60                 :     1360584 :         AddCoin(amount, n_input, n_input_bytes, ++next_locktime, utxo_pool, coin_params.m_effective_feerate);
      61                 :     1360584 :         total_balance += amount;
      62                 :             :     }
      63                 :             : 
      64                 :        3756 :     return total_balance;
      65                 :             : }
      66                 :             : 
      67                 :         312 : static SelectionResult ManualSelection(std::vector<COutput>& utxos, const CAmount& total_amount, const bool& subtract_fee_outputs)
      68                 :             : {
      69                 :         312 :     SelectionResult result(total_amount, SelectionAlgorithm::MANUAL);
      70                 :         312 :     OutputSet utxo_pool;
      71         [ +  + ]:      161648 :     for (const auto& utxo : utxos) {
      72   [ +  -  +  - ]:      322672 :         utxo_pool.insert(std::make_shared<COutput>(utxo));
      73                 :             :     }
      74         [ +  - ]:         312 :     result.AddInputs(utxo_pool, subtract_fee_outputs);
      75                 :         312 :     return result;
      76                 :         312 : }
      77                 :             : 
      78                 :             : // Returns true if the result contains an error and the message is not empty
      79                 :         880 : static bool HasErrorMsg(const util::Result<SelectionResult>& res) { return !util::ErrorString(res).empty(); }
      80                 :             : 
      81         [ +  - ]:        1157 : FUZZ_TARGET(coin_grinder)
      82                 :             : {
      83                 :         681 :     FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
      84                 :         681 :     std::vector<COutput> utxo_pool;
      85                 :             : 
      86                 :         681 :     const CAmount target{fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(1, MAX_MONEY)};
      87                 :             : 
      88                 :         681 :     FastRandomContext fast_random_context{ConsumeUInt256(fuzzed_data_provider)};
      89                 :         681 :     CoinSelectionParams coin_params{fast_random_context};
      90                 :         681 :     coin_params.m_subtract_fee_outputs = fuzzed_data_provider.ConsumeBool();
      91                 :         681 :     coin_params.m_long_term_feerate = CFeeRate{ConsumeMoney(fuzzed_data_provider, /*max=*/COIN)};
      92                 :         681 :     coin_params.m_effective_feerate = CFeeRate{ConsumeMoney(fuzzed_data_provider, /*max=*/COIN)};
      93                 :         681 :     coin_params.change_output_size = fuzzed_data_provider.ConsumeIntegralInRange<int>(10, 1000);
      94                 :         681 :     coin_params.change_spend_size = fuzzed_data_provider.ConsumeIntegralInRange<int>(10, 1000);
      95         [ +  - ]:         681 :     coin_params.m_change_fee = coin_params.m_effective_feerate.GetFee(coin_params.change_output_size);
      96                 :             :     // For other results to be comparable to SRD, we must align the change_target with SRD’s hardcoded behavior
      97                 :         681 :     coin_params.m_min_change_target = CHANGE_LOWER + coin_params.m_change_fee;
      98                 :             : 
      99                 :             :     // Create some coins
     100                 :         681 :     CAmount total_balance{0};
     101                 :         681 :     CAmount max_spendable{0};
     102                 :         681 :     int next_locktime{0};
     103   [ +  +  +  + ]:      420808 :     LIMITED_WHILE (fuzzed_data_provider.ConsumeBool(), 10000) {
     104                 :      420400 :         const int n_input{fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 10)};
     105                 :      420400 :         const int n_input_bytes{fuzzed_data_provider.ConsumeIntegralInRange<int>(41, 10000)};
     106                 :      420400 :         const CAmount amount{fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(1, MAX_MONEY)};
     107         [ +  + ]:      420400 :         if (total_balance + amount >= MAX_MONEY) {
     108                 :             :             break;
     109                 :             :         }
     110         [ +  - ]:      420127 :         AddCoin(amount, n_input, n_input_bytes, ++next_locktime, utxo_pool, coin_params.m_effective_feerate);
     111                 :      420127 :         total_balance += amount;
     112         [ +  - ]:      420127 :         CAmount eff_value = amount - coin_params.m_effective_feerate.GetFee(n_input_bytes);
     113                 :      420127 :         max_spendable += eff_value;
     114                 :             :     }
     115                 :             : 
     116                 :         681 :     std::vector<OutputGroup> group_pos;
     117         [ +  - ]:         681 :     GroupCoins(fuzzed_data_provider, utxo_pool, coin_params, /*positive_only=*/true, group_pos);
     118                 :             : 
     119                 :             :     // Run coinselection algorithms
     120         [ +  - ]:         681 :     auto result_cg = CoinGrinder(group_pos, target, coin_params.m_min_change_target, MAX_STANDARD_TX_WEIGHT);
     121   [ +  +  +  -  :         681 :     if (target + coin_params.m_min_change_target > max_spendable || HasErrorMsg(result_cg)) return; // We only need to compare algorithms if CoinGrinder has a solution
                   +  + ]
     122         [ -  + ]:         629 :     assert(result_cg);
     123   [ +  -  +  + ]:         629 :     if (!result_cg->GetAlgoCompleted()) return; // Bail out if CoinGrinder solution is not optimal
     124                 :             : 
     125         [ +  - ]:         619 :     auto result_srd = SelectCoinsSRD(group_pos, target, coin_params.m_change_fee, fast_random_context, MAX_STANDARD_TX_WEIGHT);
     126   [ +  +  +  -  :        1215 :     if (result_srd && result_srd->GetChange(CHANGE_LOWER, coin_params.m_change_fee) > 0) { // exclude any srd solutions that don’t have change, err on excluding
                   +  - ]
     127         [ -  + ]:         596 :         assert(result_srd->GetWeight() >= result_cg->GetWeight());
     128                 :             :     }
     129                 :             : 
     130         [ +  - ]:         619 :     auto result_knapsack = KnapsackSolver(group_pos, target, coin_params.m_min_change_target, fast_random_context, MAX_STANDARD_TX_WEIGHT);
     131   [ +  +  +  -  :        1226 :     if (result_knapsack && result_knapsack->GetChange(CHANGE_LOWER, coin_params.m_change_fee) > 0) { // exclude any knapsack solutions that don’t have change, err on excluding
                   +  + ]
     132         [ -  + ]:         564 :         assert(result_knapsack->GetWeight() >= result_cg->GetWeight());
     133                 :             :     }
     134                 :         681 : }
     135                 :             : 
     136         [ +  - ]:         707 : FUZZ_TARGET(coin_grinder_is_optimal)
     137                 :             : {
     138                 :         231 :     FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
     139                 :             : 
     140                 :         231 :     FastRandomContext fast_random_context{ConsumeUInt256(fuzzed_data_provider)};
     141                 :         231 :     CoinSelectionParams coin_params{fast_random_context};
     142                 :         231 :     coin_params.m_subtract_fee_outputs = false;
     143                 :             :     // Set effective feerate up to MAX_MONEY sats per 1'000'000 vB (2'100'000'000 sat/vB = 21'000 BTC/kvB).
     144         [ +  - ]:         231 :     coin_params.m_effective_feerate = CFeeRate{ConsumeMoney(fuzzed_data_provider, MAX_MONEY), 1'000'000};
     145                 :         231 :     coin_params.m_min_change_target = ConsumeMoney(fuzzed_data_provider);
     146                 :             : 
     147                 :             :     // Create some coins
     148                 :         231 :     CAmount max_spendable{0};
     149                 :         231 :     int next_locktime{0};
     150                 :         231 :     static constexpr unsigned max_output_groups{16};
     151                 :         231 :     std::vector<OutputGroup> group_pos;
     152   [ +  +  +  + ]:        2490 :     LIMITED_WHILE (fuzzed_data_provider.ConsumeBool(), max_output_groups) {
     153                 :             :         // With maximum m_effective_feerate and n_input_bytes = 1'000'000, input_fee <= MAX_MONEY.
     154                 :        2259 :         const int n_input_bytes{fuzzed_data_provider.ConsumeIntegralInRange<int>(1, 1'000'000)};
     155                 :             :         // Only make UTXOs with positive effective value
     156         [ +  - ]:        2259 :         const CAmount input_fee = coin_params.m_effective_feerate.GetFee(n_input_bytes);
     157                 :             :         // Ensure that each UTXO has at least an effective value of 1 sat
     158         [ -  + ]:        2259 :         const CAmount eff_value{fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(1, MAX_MONEY + group_pos.size() - max_spendable - max_output_groups)};
     159                 :        2259 :         const CAmount amount{eff_value + input_fee};
     160                 :        2259 :         std::vector<COutput> temp_utxo_pool;
     161                 :             : 
     162         [ +  - ]:        2259 :         AddCoin(amount, /*n_input=*/0, n_input_bytes, ++next_locktime, temp_utxo_pool, coin_params.m_effective_feerate);
     163                 :        2259 :         max_spendable += eff_value;
     164                 :             : 
     165         [ +  - ]:        2259 :         auto output_group = OutputGroup(coin_params);
     166   [ +  -  +  -  :        2259 :         output_group.Insert(std::make_shared<COutput>(temp_utxo_pool.at(0)), /*ancestors=*/0, /*cluster_count=*/0);
                   +  - ]
     167         [ +  - ]:        2259 :         group_pos.push_back(output_group);
     168                 :        2259 :     }
     169         [ -  + ]:         231 :     size_t num_groups = group_pos.size();
     170         [ -  + ]:         231 :     assert(num_groups <= max_output_groups);
     171                 :             : 
     172                 :             :     // Only choose targets below max_spendable
     173         [ +  + ]:         280 :     const CAmount target{fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(1, std::max(CAmount{1}, max_spendable - coin_params.m_min_change_target))};
     174                 :             : 
     175                 :             :     // Brute force optimal solution
     176                 :         231 :     CAmount best_amount{MAX_MONEY};
     177                 :         231 :     int best_weight{std::numeric_limits<int>::max()};
     178         [ +  + ]:     5631457 :     for (uint32_t pattern = 1; (pattern >> num_groups) == 0; ++pattern) {
     179                 :             :         CAmount subset_amount{0};
     180                 :             :         int subset_weight{0};
     181         [ +  + ]:    94856281 :         for (unsigned i = 0; i < num_groups; ++i) {
     182         [ +  + ]:    89225055 :             if ((pattern >> i) & 1) {
     183         [ +  - ]:    44613657 :                 subset_amount += group_pos[i].GetSelectionAmount();
     184                 :    44613657 :                 subset_weight += group_pos[i].m_weight;
     185                 :             :             }
     186                 :             :         }
     187   [ +  +  +  +  :     5631226 :         if ((subset_amount >= target + coin_params.m_min_change_target) && (subset_weight < best_weight || (subset_weight == best_weight && subset_amount < best_amount))) {
                   +  + ]
     188                 :        1343 :             best_weight = subset_weight;
     189                 :        1343 :             best_amount = subset_amount;
     190                 :             :         }
     191                 :             :     }
     192                 :             : 
     193         [ +  + ]:         231 :     if (best_weight < std::numeric_limits<int>::max()) {
     194                 :             :         // Sufficient funds and acceptable weight: CoinGrinder should find at least one solution
     195                 :         193 :         int high_max_selection_weight = fuzzed_data_provider.ConsumeIntegralInRange<int>(best_weight, std::numeric_limits<int>::max());
     196                 :             : 
     197         [ +  - ]:         193 :         auto result_cg = CoinGrinder(group_pos, target, coin_params.m_min_change_target, high_max_selection_weight);
     198         [ -  + ]:         193 :         assert(result_cg);
     199         [ -  + ]:         193 :         assert(result_cg->GetWeight() <= high_max_selection_weight);
     200   [ +  -  -  + ]:         193 :         assert(result_cg->GetSelectedEffectiveValue() >= target + coin_params.m_min_change_target);
     201   [ +  -  +  -  :         193 :         assert(best_weight < result_cg->GetWeight() || (best_weight == result_cg->GetWeight() && best_amount <= result_cg->GetSelectedEffectiveValue()));
             +  -  -  + ]
     202   [ +  -  +  - ]:         193 :         if (result_cg->GetAlgoCompleted()) {
     203                 :             :             // If CoinGrinder exhausted the search space, it must return the optimal solution
     204         [ -  + ]:         193 :             assert(best_weight == result_cg->GetWeight());
     205   [ +  -  -  + ]:         193 :             assert(best_amount == result_cg->GetSelectedEffectiveValue());
     206                 :             :         }
     207                 :         193 :     }
     208                 :             : 
     209                 :             :     // CoinGrinder cannot ever find a better solution than the brute-forced best, or there is none in the first place
     210                 :         231 :     int low_max_selection_weight = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, best_weight - 1);
     211         [ +  - ]:         231 :     auto result_cg = CoinGrinder(group_pos, target, coin_params.m_min_change_target, low_max_selection_weight);
     212                 :             :     // Max_weight should have been exceeded, or there were insufficient funds
     213         [ -  + ]:         231 :     assert(!result_cg);
     214                 :         231 : }
     215                 :             : 
     216         [ +  - ]:         680 : FUZZ_TARGET(bnb_finds_min_waste)
     217                 :             : {
     218                 :         204 :     FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
     219                 :             : 
     220                 :         204 :     FastRandomContext fast_random_context{ConsumeUInt256(fuzzed_data_provider)};
     221                 :         204 :     CoinSelectionParams coin_params{fast_random_context};
     222                 :         204 :     coin_params.m_subtract_fee_outputs = false;
     223                 :             :     // Set effective feerate up to 10'000'000 sats per kvB (10'000 sat/vB).
     224         [ +  - ]:         204 :     coin_params.m_effective_feerate = CFeeRate{ConsumeMoney(fuzzed_data_provider, 10'000'000), 1'000};
     225         [ +  - ]:         204 :     coin_params.m_long_term_feerate = CFeeRate{ConsumeMoney(fuzzed_data_provider, 10'000'000), 1'000};
     226         [ +  - ]:         204 :     coin_params.m_discard_feerate = CFeeRate{ConsumeMoney(fuzzed_data_provider, 10'000'000), 1'000};
     227                 :         204 :     coin_params.m_cost_of_change = ConsumeMoney(fuzzed_data_provider);
     228                 :             : 
     229                 :         204 :     coin_params.change_output_size = fuzzed_data_provider.ConsumeIntegralInRange(1, MAX_SCRIPT_SIZE);
     230         [ +  - ]:         204 :     coin_params.m_change_fee = coin_params.m_effective_feerate.GetFee(coin_params.change_output_size);
     231                 :         204 :     coin_params.change_spend_size = fuzzed_data_provider.ConsumeIntegralInRange<int>(41, 1000);
     232         [ +  - ]:         204 :     const auto change_spend_fee{coin_params.m_discard_feerate.GetFee(coin_params.change_spend_size)};
     233                 :         204 :     coin_params.m_cost_of_change = coin_params.m_change_fee + change_spend_fee;
     234         [ +  - ]:         408 :     CScript change_out_script = CScript() << std::vector<unsigned char>(coin_params.change_output_size, OP_TRUE);
     235   [ +  -  +  - ]:         204 :     const auto dust{GetDustThreshold(CTxOut{/*nValueIn=*/0, change_out_script}, coin_params.m_discard_feerate)};
     236         [ +  + ]:         204 :     coin_params.min_viable_change = std::max(change_spend_fee + 1, dust);
     237                 :             : 
     238                 :             :     // Create some coins
     239                 :         204 :     CAmount max_spendable{0};
     240                 :         204 :     int next_locktime{0};
     241                 :             :     // Too many output groups (>17?) would make it possible to generate UTXO
     242                 :             :     // pool and target combinations that cannot be completely searched by BnB
     243                 :             :     // before running into the attempt limit (see BnB "Exhaust..." test). The
     244                 :             :     // brute force search also gets exponentially more expensive with bigger
     245                 :             :     // UTXO pools.
     246                 :             :     // Choose 1–16 of 16 provides ample fuzzing space.
     247                 :         204 :     static constexpr unsigned max_output_groups{16};
     248                 :         204 :     std::vector<OutputGroup> group_pos;
     249   [ +  +  +  + ]:        2025 :     LIMITED_WHILE (fuzzed_data_provider.ConsumeBool(), max_output_groups) {
     250                 :             :         // With maximum m_effective_feerate 10'000 s/vB and n_input_bytes = 20'000 B, input_fee <= MAX_MONEY.
     251                 :        1821 :         const int n_input_bytes{fuzzed_data_provider.ConsumeIntegralInRange<int>(1, 20'000)};
     252         [ +  - ]:        1821 :         const CAmount input_fee = coin_params.m_effective_feerate.GetFee(n_input_bytes);
     253                 :             :         // Ensure that each UTXO has at least an effective value of 1 sat
     254         [ -  + ]:        1821 :         const CAmount eff_value{fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(1, MAX_MONEY + group_pos.size() - max_spendable - max_output_groups)};
     255                 :        1821 :         const CAmount amount{eff_value + input_fee};
     256                 :        1821 :         std::vector<COutput> temp_utxo_pool;
     257                 :             : 
     258         [ +  - ]:        1821 :         AddCoin(amount, /*n_input=*/0, n_input_bytes, ++next_locktime, temp_utxo_pool, coin_params.m_effective_feerate);
     259                 :        1821 :         max_spendable += eff_value;
     260                 :             : 
     261         [ +  - ]:        1821 :         auto output_group = OutputGroup(coin_params);
     262   [ +  -  +  -  :        1821 :         output_group.Insert(std::make_shared<COutput>(temp_utxo_pool.at(0)), /*ancestors=*/0, /*cluster_count=*/0);
                   +  - ]
     263         [ +  - ]:        1821 :         group_pos.push_back(output_group);
     264                 :        1821 :     }
     265         [ -  + ]:         204 :     size_t num_groups = group_pos.size();
     266         [ -  + ]:         204 :     assert(num_groups <= max_output_groups);
     267                 :             : 
     268                 :             :     // Only choose targets below max_spendable
     269         [ +  + ]:         237 :     const CAmount target{fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(1, std::max(CAmount{1}, max_spendable - coin_params.m_cost_of_change))};
     270                 :             : 
     271                 :             :     // Brute force optimal solution (lowest waste, but cannot be superset of another solution)
     272                 :         204 :     std::vector<uint32_t> solutions;
     273                 :         204 :     CAmount best_waste{std::numeric_limits<int64_t>::max()};
     274                 :         204 :     int best_weight{std::numeric_limits<int>::max()};
     275         [ +  + ]:     3905302 :     for (uint32_t pattern = 1; (pattern >> num_groups) == 0; ++pattern) {
     276                 :             :         // BnB does not permit adding more inputs to a solution, i.e. a superset of a solution cannot ever be a solution.
     277                 :             :         // The search pattern guarantees that any superset will only be visited after all its subsets have been traversed.
     278                 :     3905098 :         bool is_superset = false;
     279         [ +  + ]:   277837448 :         for (uint32_t sol : solutions) {
     280         [ +  + ]:   275624799 :             if ((pattern & sol) == sol) {
     281                 :             :                 is_superset = true;
     282                 :             :                 break;
     283                 :             :             }
     284                 :             :         }
     285         [ +  + ]:     3905098 :         if (is_superset) {
     286                 :     1692449 :             continue;
     287                 :             :         }
     288                 :             : 
     289                 :             :         CAmount subset_amount{0};
     290                 :             :         CAmount subset_waste{0};
     291                 :             :         int subset_weight{0};
     292         [ +  + ]:    37215177 :         for (unsigned i = 0; i < num_groups; ++i) {
     293         [ +  + ]:    35002528 :             if ((pattern >> i) & 1) {
     294         [ +  - ]:    16541488 :                 subset_amount += group_pos[i].GetSelectionAmount();
     295                 :    16541488 :                 subset_waste += group_pos[i].fee - group_pos[i].long_term_fee;
     296                 :    16541488 :                 subset_weight += group_pos[i].m_weight;
     297                 :             :             }
     298                 :             :         }
     299   [ +  +  +  + ]:     2212649 :         if (subset_amount >= target && subset_amount <= target + coin_params.m_cost_of_change) {
     300         [ +  - ]:       15138 :             solutions.push_back(pattern);
     301                 :             :             // Add the excess (overselection that gets dropped to fees) to waste score
     302                 :       15138 :             CAmount excess = subset_amount - target;
     303                 :       15138 :             subset_waste += excess;
     304                 :       15138 :             SelectionResult result_bf(target, SelectionAlgorithm::MANUAL);
     305                 :             : 
     306         [ +  + ]:      246721 :             for (unsigned i = 0; i < num_groups; ++i) {
     307         [ +  + ]:      231583 :                 if ((pattern >> i) & 1) {
     308         [ +  - ]:      104881 :                     result_bf.AddInput(group_pos[i]);
     309                 :             :                 }
     310                 :             :             }
     311         [ +  + ]:       15138 :             if (subset_waste < best_waste) {
     312                 :        1205 :                 best_waste = subset_waste;
     313         [ +  - ]:        1205 :                 result_bf.RecalculateWaste(coin_params.min_viable_change, coin_params.m_cost_of_change, coin_params.m_change_fee);
     314   [ +  -  -  + ]:        1205 :                 assert(result_bf.GetWaste() == best_waste);
     315                 :             :                 best_weight = subset_weight;
     316                 :             :             }
     317                 :       15138 :         }
     318                 :             :     }
     319                 :             : 
     320                 :         204 :     int high_max_selection_weight = fuzzed_data_provider.ConsumeIntegralInRange<int>(best_weight, std::numeric_limits<int>::max());
     321         [ +  - ]:         204 :     auto result_bnb = SelectCoinsBnB(group_pos, target, coin_params.m_cost_of_change, high_max_selection_weight);
     322                 :             : 
     323   [ -  +  +  +  :         204 :     if (!solutions.size() || !result_bnb) {
                   +  - ]
     324                 :             :         // Either both BnB and Brute Force find a solution or neither does.
     325         [ -  + ]:          49 :         assert(!result_bnb == !solutions.size());
     326                 :             :     } else {
     327                 :             :         // If brute forcing found a solution with an acceptable weight, BnB must find at least one solution with at most 16 output groups
     328                 :         155 :         assert(result_bnb);
     329         [ +  - ]:         155 :         result_bnb->RecalculateWaste(coin_params.min_viable_change, coin_params.m_cost_of_change, coin_params.m_change_fee);
     330         [ -  + ]:         155 :         assert(result_bnb->GetWeight() <= high_max_selection_weight);
     331   [ +  -  -  + ]:         155 :         assert(result_bnb->GetSelectedEffectiveValue() >= target);
     332   [ +  -  -  + ]:         155 :         assert(result_bnb->GetSelectedEffectiveValue() <= target + coin_params.m_cost_of_change);
     333   [ +  -  -  + ]:         155 :         assert(best_waste <= result_bnb->GetWaste());
     334   [ +  -  +  - ]:         155 :         if (result_bnb->GetAlgoCompleted()) {
     335                 :             :             // If BnB exhausted the search space, it must return an optimal solution (tied on waste score)
     336   [ +  -  -  + ]:         155 :             assert(best_waste == result_bnb->GetWaste());
     337                 :             :         }
     338                 :             :     }
     339                 :         204 : }
     340                 :             : 
     341                 :             : enum class CoinSelectionAlgorithm {
     342                 :             :     BNB,
     343                 :             :     SRD,
     344                 :             :     KNAPSACK,
     345                 :             : };
     346                 :             : 
     347                 :             : template<CoinSelectionAlgorithm Algorithm>
     348                 :        1252 : void FuzzCoinSelectionAlgorithm(std::span<const uint8_t> buffer) {
     349                 :        1252 :     SeedRandomStateForTest(SeedRand::ZEROS);
     350                 :        1252 :     FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
     351                 :        1252 :     std::vector<COutput> utxo_pool;
     352                 :             : 
     353                 :        1252 :     const CFeeRate long_term_fee_rate{ConsumeMoney(fuzzed_data_provider, /*max=*/COIN)};
     354                 :        1252 :     const CFeeRate effective_fee_rate{ConsumeMoney(fuzzed_data_provider, /*max=*/COIN)};
     355                 :             :     // Discard feerate must be at least dust relay feerate
     356                 :        1252 :     const CFeeRate discard_fee_rate{fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(DUST_RELAY_TX_FEE, COIN)};
     357                 :        1252 :     const CAmount target{fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(1, MAX_MONEY)};
     358                 :        1252 :     const bool subtract_fee_outputs{fuzzed_data_provider.ConsumeBool()};
     359                 :             : 
     360                 :        1252 :     FastRandomContext fast_random_context{ConsumeUInt256(fuzzed_data_provider)};
     361                 :        1252 :     CoinSelectionParams coin_params{fast_random_context};
     362                 :        1252 :     coin_params.m_subtract_fee_outputs = subtract_fee_outputs;
     363                 :        1252 :     coin_params.m_long_term_feerate = long_term_fee_rate;
     364                 :        1252 :     coin_params.m_effective_feerate = effective_fee_rate;
     365                 :        1252 :     coin_params.change_output_size = fuzzed_data_provider.ConsumeIntegralInRange(1, MAX_SCRIPT_SIZE);
     366 [ +  - ][ +  - ]:        1252 :     coin_params.m_change_fee = effective_fee_rate.GetFee(coin_params.change_output_size);
                 [ +  - ]
     367                 :        1252 :     coin_params.m_discard_feerate = discard_fee_rate;
     368                 :        1252 :     coin_params.change_spend_size = fuzzed_data_provider.ConsumeIntegralInRange<int>(41, 1000);
     369 [ +  - ][ +  - ]:        1252 :     const auto change_spend_fee{coin_params.m_discard_feerate.GetFee(coin_params.change_spend_size)};
                 [ +  - ]
     370                 :        1252 :     coin_params.m_cost_of_change = coin_params.m_change_fee + change_spend_fee;
     371 [ +  - ][ +  - ]:        2504 :     CScript change_out_script = CScript() << std::vector<unsigned char>(coin_params.change_output_size, OP_TRUE);
                 [ +  - ]
     372   [ +  -  +  - ]:        1252 :     const auto dust{GetDustThreshold(CTxOut{/*nValueIn=*/0, change_out_script}, coin_params.m_discard_feerate)};
           [ +  -  +  - ]
           [ +  -  +  - ]
     373         [ +  + ]:        1252 :     coin_params.min_viable_change = std::max(change_spend_fee + 1, dust);
     374                 :             : 
     375                 :        1252 :     int next_locktime{0};
     376 [ +  - ][ +  - ]:        1252 :     CAmount total_balance{CreateCoins(fuzzed_data_provider, utxo_pool, coin_params, next_locktime)};
                 [ +  - ]
     377                 :             : 
     378                 :        1252 :     std::vector<OutputGroup> group_pos;
     379 [ +  - ][ +  - ]:        1252 :     GroupCoins(fuzzed_data_provider, utxo_pool, coin_params, /*positive_only=*/true, group_pos);
                 [ +  - ]
     380                 :             : 
     381                 :        1252 :     int max_selection_weight = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, std::numeric_limits<int>::max());
     382                 :             : 
     383                 :        1252 :     std::optional<SelectionResult> result;
     384                 :             : 
     385                 :             :     if constexpr (Algorithm == CoinSelectionAlgorithm::BNB) {
     386         [ +  + ]:         408 :         if (!coin_params.m_subtract_fee_outputs) {
     387         [ +  - ]:         364 :             auto result_bnb = SelectCoinsBnB(group_pos, target, coin_params.m_cost_of_change, max_selection_weight);
     388         [ +  + ]:         364 :             if (result_bnb) {
     389         [ +  - ]:         187 :                 result = *result_bnb;
     390   [ +  -  -  + ]:         187 :                 assert(result_bnb->GetChange(coin_params.min_viable_change, coin_params.m_change_fee) == 0);
     391   [ +  -  -  + ]:         187 :                 assert(result_bnb->GetSelectedValue() >= target);
     392         [ -  + ]:         187 :                 assert(result_bnb->GetWeight() <= max_selection_weight);
     393         [ +  - ]:         187 :                 (void)result_bnb->GetShuffledInputVector();
     394         [ +  - ]:         187 :                 (void)result_bnb->GetInputSet();
     395                 :             :             }
     396                 :         364 :         }
     397                 :             :     }
     398                 :             : 
     399                 :             :     if constexpr (Algorithm == CoinSelectionAlgorithm::SRD) {
     400         [ +  - ]:         351 :         auto result_srd = SelectCoinsSRD(group_pos, target, coin_params.m_change_fee, fast_random_context, max_selection_weight);
     401         [ +  + ]:         351 :         if (result_srd) {
     402         [ +  - ]:         179 :             result = *result_srd;
     403   [ +  -  -  + ]:         179 :             assert(result_srd->GetSelectedValue() >= target);
     404   [ +  -  -  + ]:         179 :             assert(result_srd->GetChange(CHANGE_LOWER, coin_params.m_change_fee) > 0);
     405         [ -  + ]:         179 :             assert(result_srd->GetWeight() <= max_selection_weight);
     406         [ +  - ]:         179 :             result_srd->SetBumpFeeDiscount(ConsumeMoney(fuzzed_data_provider));
     407         [ +  - ]:         179 :             result_srd->RecalculateWaste(coin_params.min_viable_change, coin_params.m_cost_of_change, coin_params.m_change_fee);
     408         [ +  - ]:         179 :             (void)result_srd->GetShuffledInputVector();
     409         [ +  - ]:         179 :             (void)result_srd->GetInputSet();
     410                 :             :         }
     411                 :           0 :     }
     412                 :             : 
     413                 :             :     if constexpr (Algorithm == CoinSelectionAlgorithm::KNAPSACK) {
     414                 :         493 :         std::vector<OutputGroup> group_all;
     415         [ +  - ]:         493 :         GroupCoins(fuzzed_data_provider, utxo_pool, coin_params, /*positive_only=*/false, group_all);
     416                 :             : 
     417         [ +  + ]:      214067 :         for (const OutputGroup& group : group_all) {
     418         [ +  - ]:      213574 :             const CoinEligibilityFilter filter{fuzzed_data_provider.ConsumeIntegral<int>(), fuzzed_data_provider.ConsumeIntegral<int>(), fuzzed_data_provider.ConsumeIntegral<uint64_t>()};
     419         [ +  - ]:      213574 :             (void)group.EligibleForSpending(filter);
     420                 :             :         }
     421                 :             : 
     422         [ +  - ]:         493 :         CAmount change_target{GenerateChangeTarget(target, coin_params.m_change_fee, fast_random_context)};
     423         [ +  - ]:         493 :         auto result_knapsack = KnapsackSolver(group_all, target, change_target, fast_random_context, max_selection_weight);
     424                 :             :         // If the total balance is sufficient for the target and we are not using
     425                 :             :         // effective values, Knapsack should always find a solution (unless the selection exceeded the max tx weight).
     426   [ +  +  +  +  :         493 :         if (total_balance >= target && subtract_fee_outputs && !HasErrorMsg(result_knapsack)) {
             +  -  +  + ]
     427         [ -  + ]:         218 :             assert(result_knapsack);
     428                 :             :         }
     429         [ +  + ]:         493 :         if (result_knapsack) {
     430         [ +  - ]:         392 :             result = *result_knapsack;
     431   [ +  -  -  + ]:         392 :             assert(result_knapsack->GetSelectedValue() >= target);
     432         [ -  + ]:         392 :             assert(result_knapsack->GetWeight() <= max_selection_weight);
     433         [ +  - ]:         392 :             result_knapsack->SetBumpFeeDiscount(ConsumeMoney(fuzzed_data_provider));
     434         [ +  - ]:         392 :             result_knapsack->RecalculateWaste(coin_params.min_viable_change, coin_params.m_cost_of_change, coin_params.m_change_fee);
     435         [ +  - ]:         392 :             (void)result_knapsack->GetShuffledInputVector();
     436         [ +  - ]:         392 :             (void)result_knapsack->GetInputSet();
     437                 :             :         }
     438                 :         493 :     }
     439                 :             : 
     440                 :        1252 :     std::vector<COutput> utxos;
     441 [ +  - ][ +  - ]:        1252 :     CAmount new_total_balance{CreateCoins(fuzzed_data_provider, utxos, coin_params, next_locktime)};
                 [ +  - ]
     442 [ +  + ][ +  + ]:        1252 :     if (new_total_balance > 0) {
                 [ +  + ]
     443                 :         407 :         OutputSet new_utxo_pool;
     444   [ +  -  +  + ]:      183763 :         for (const auto& utxo : utxos) {
           [ +  -  +  + ]
           [ +  -  +  + ]
     445 [ +  - ][ +  - ]:      366712 :             new_utxo_pool.insert(std::make_shared<COutput>(utxo));
                 [ +  - ]
     446                 :             :         }
     447 [ +  + ][ +  + ]:         407 :         if (result) {
                 [ +  + ]
     448 [ +  - ][ +  - ]:         289 :             const auto weight{result->GetWeight()};
                 [ +  - ]
     449 [ +  - ][ +  - ]:         289 :             result->AddInputs(new_utxo_pool, subtract_fee_outputs);
                 [ +  - ]
     450 [ -  + ][ -  + ]:         289 :             assert(result->GetWeight() > weight);
                 [ -  + ]
     451                 :             :         }
     452                 :         407 :     }
     453                 :             : 
     454                 :        1252 :     std::vector<COutput> manual_inputs;
     455 [ +  - ][ +  - ]:        1252 :     CAmount manual_balance{CreateCoins(fuzzed_data_provider, manual_inputs, coin_params, next_locktime)};
                 [ +  - ]
     456 [ +  + ][ +  + ]:        1252 :     if (manual_balance == 0) return;
                 [ +  + ]
     457 [ +  - ][ +  - ]:         312 :     auto manual_selection{ManualSelection(manual_inputs, manual_balance, coin_params.m_subtract_fee_outputs)};
                 [ +  - ]
     458 [ +  + ][ +  + ]:         312 :     if (result) {
                 [ +  + ]
     459 [ +  - ][ +  - ]:         225 :         const CAmount old_target{result->GetTarget()};
                 [ +  - ]
     460   [ +  -  +  -  :         225 :         const OutputSet input_set{result->GetInputSet()};
           +  - ][ +  -  
             +  -  +  - ]
           [ +  -  +  -  
                   +  - ]
     461 [ +  - ][ +  - ]:         225 :         const int old_weight{result->GetWeight()};
                 [ +  - ]
     462 [ +  - ][ +  - ]:         225 :         result->Merge(manual_selection);
                 [ +  - ]
     463   [ +  -  -  +  :         225 :         assert(result->GetInputSet().size() == input_set.size() + manual_inputs.size());
           -  + ][ +  -  
             -  +  -  + ]
           [ +  -  -  +  
                   -  + ]
     464 [ -  + ][ -  + ]:         225 :         assert(result->GetTarget() == old_target + manual_selection.GetTarget());
                 [ -  + ]
     465 [ -  + ][ -  + ]:         225 :         assert(result->GetWeight() == old_weight + manual_selection.GetWeight());
                 [ -  + ]
     466                 :         225 :     }
     467                 :        1252 : }
     468                 :             : 
     469         [ +  - ]:         884 : FUZZ_TARGET(coinselection_bnb) {
     470                 :         408 :     FuzzCoinSelectionAlgorithm<CoinSelectionAlgorithm::BNB>(buffer);
     471                 :         408 : }
     472                 :             : 
     473         [ +  - ]:         827 : FUZZ_TARGET(coinselection_srd) {
     474                 :         351 :     FuzzCoinSelectionAlgorithm<CoinSelectionAlgorithm::SRD>(buffer);
     475                 :         351 : }
     476                 :             : 
     477         [ +  - ]:         969 : FUZZ_TARGET(coinselection_knapsack) {
     478                 :         493 :     FuzzCoinSelectionAlgorithm<CoinSelectionAlgorithm::KNAPSACK>(buffer);
     479                 :         493 : }
     480                 :             : 
     481                 :             : } // namespace wallet
        

Generated by: LCOV version 2.5.0-full