LCOV - code coverage report
Current view: top level - src/wallet/test/fuzz - coinselection.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 75.2 % 307 231
Test Date: 2026-02-13 04:14:00 Functions: 95.0 % 20 19
Branches: 47.3 % 450 213

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

Generated by: LCOV version 2.0-1