Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2022-present The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.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>14#include <numeric>15#include <span>16#include <vector>18namespace wallet {20static void AddCoin(const CAmount& value, int n_input, int n_input_bytes, int locktime, std::vector<COutput>& coins, CFeeRate fee_rate)21{22CMutableTransaction tx;23tx.vout.resize(n_input + 1);24tx.vout[n_input].nValue = value;25tx.nLockTime = locktime; // all transactions get different hashes26coins.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}29// Randomly distribute coins to instances of OutputGroup30static void GroupCoins(FuzzedDataProvider& fuzzed_data_provider, const std::vector<COutput>& coins, const CoinSelectionParams& coin_params, bool positive_only, std::vector<OutputGroup>& output_groups)31{32auto output_group = OutputGroup(coin_params);33bool valid_outputgroup{false};34for (auto& coin : coins) {35if (!positive_only || (positive_only && coin.GetEffectiveValue() > 0)) {36output_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 group39// that would be invalid for the BnB algorithm40valid_outputgroup = !positive_only || output_group.GetSelectionAmount() > 0;41if (valid_outputgroup && fuzzed_data_provider.ConsumeBool()) {42output_groups.push_back(output_group);43output_group = OutputGroup(coin_params);44valid_outputgroup = false;45}46}47if (valid_outputgroup) output_groups.push_back(output_group);48}50static CAmount CreateCoins(FuzzedDataProvider& fuzzed_data_provider, std::vector<COutput>& utxo_pool, CoinSelectionParams& coin_params, int& next_locktime)51{52CAmount total_balance{0};53LIMITED_WHILE (fuzzed_data_provider.ConsumeBool(), 10000) {54const int n_input{fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 10)};55const int n_input_bytes{fuzzed_data_provider.ConsumeIntegralInRange<int>(41, 10000)};56const CAmount amount{fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(1, MAX_MONEY)};57if (total_balance + amount >= MAX_MONEY) {58break;59}60AddCoin(amount, n_input, n_input_bytes, ++next_locktime, utxo_pool, coin_params.m_effective_feerate);61total_balance += amount;62}64return total_balance;65}67static SelectionResult ManualSelection(std::vector<COutput>& utxos, const CAmount& total_amount, const bool& subtract_fee_outputs)68{69SelectionResult result(total_amount, SelectionAlgorithm::MANUAL);70OutputSet utxo_pool;71for (const auto& utxo : utxos) {72utxo_pool.insert(std::make_shared<COutput>(utxo));73}74result.AddInputs(utxo_pool, subtract_fee_outputs);75return result;76}78// Returns true if the result contains an error and the message is not empty79static bool HasErrorMsg(const util::Result<SelectionResult>& res) { return !util::ErrorString(res).empty(); }81FUZZ_TARGET(coin_grinder)82{83FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};84std::vector<COutput> utxo_pool;86const CAmount target{fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(1, MAX_MONEY)};88FastRandomContext fast_random_context{ConsumeUInt256(fuzzed_data_provider)};89CoinSelectionParams coin_params{fast_random_context};90coin_params.m_subtract_fee_outputs = fuzzed_data_provider.ConsumeBool();91coin_params.m_long_term_feerate = CFeeRate{ConsumeMoney(fuzzed_data_provider, /*max=*/COIN)};92coin_params.m_effective_feerate = CFeeRate{ConsumeMoney(fuzzed_data_provider, /*max=*/COIN)};93coin_params.change_output_size = fuzzed_data_provider.ConsumeIntegralInRange<int>(10, 1000);94coin_params.change_spend_size = fuzzed_data_provider.ConsumeIntegralInRange<int>(10, 1000);95coin_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);96coin_params.m_change_fee = coin_params.m_effective_feerate.GetFee(coin_params.change_output_size);97// For other results to be comparable to SRD, we must align the change_target with SRD’s hardcoded behavior98coin_params.m_min_change_target = CHANGE_LOWER + coin_params.m_change_fee;100// Create some coins101CAmount total_balance{0};102CAmount max_spendable{0};103int next_locktime{0};104LIMITED_WHILE (fuzzed_data_provider.ConsumeBool(), 10000) {105const int n_input{fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 10)};106const int n_input_bytes{fuzzed_data_provider.ConsumeIntegralInRange<int>(41, 10000)};107const CAmount amount{fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(1, MAX_MONEY)};108if (total_balance + amount >= MAX_MONEY) {109break;110}111AddCoin(amount, n_input, n_input_bytes, ++next_locktime, utxo_pool, coin_params.m_effective_feerate);112total_balance += amount;113CAmount eff_value = amount - coin_params.m_effective_feerate.GetFee(n_input_bytes);114max_spendable += eff_value;115}117std::vector<OutputGroup> group_pos;118GroupCoins(fuzzed_data_provider, utxo_pool, coin_params, /*positive_only=*/true, group_pos);120// Run coinselection algorithms121auto result_cg = CoinGrinder(group_pos, target, coin_params.m_min_change_target, MAX_STANDARD_TX_WEIGHT);122if (target + coin_params.m_min_change_target > max_spendable || HasErrorMsg(result_cg)) return; // We only need to compare algorithms if CoinGrinder has a solution123assert(result_cg);124if (!result_cg->GetAlgoCompleted()) return; // Bail out if CoinGrinder solution is not optimal126auto result_srd = SelectCoinsSRD(group_pos, target, coin_params.m_change_fee, fast_random_context, MAX_STANDARD_TX_WEIGHT);127if (result_srd && result_srd->GetChange(CHANGE_LOWER, coin_params.m_change_fee) > 0) { // exclude any srd solutions that don’t have change, err on excluding128assert(result_srd->GetWeight() >= result_cg->GetWeight());129}131auto result_knapsack = KnapsackSolver(group_pos, target, coin_params.m_min_change_target, fast_random_context, MAX_STANDARD_TX_WEIGHT);132if (result_knapsack && result_knapsack->GetChange(CHANGE_LOWER, coin_params.m_change_fee) > 0) { // exclude any knapsack solutions that don’t have change, err on excluding133assert(result_knapsack->GetWeight() >= result_cg->GetWeight());134}135}137FUZZ_TARGET(coin_grinder_is_optimal)138{139FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};141FastRandomContext fast_random_context{ConsumeUInt256(fuzzed_data_provider)};142CoinSelectionParams coin_params{fast_random_context};143coin_params.m_subtract_fee_outputs = false;144// Set effective feerate up to MAX_MONEY sats per 1'000'000 vB (2'100'000'000 sat/vB = 21'000 BTC/kvB).145coin_params.m_effective_feerate = CFeeRate{ConsumeMoney(fuzzed_data_provider, MAX_MONEY), 1'000'000};146coin_params.m_min_change_target = ConsumeMoney(fuzzed_data_provider);148// Create some coins149CAmount max_spendable{0};150int next_locktime{0};151static constexpr unsigned max_output_groups{16};152std::vector<OutputGroup> group_pos;153LIMITED_WHILE (fuzzed_data_provider.ConsumeBool(), max_output_groups) {154// With maximum m_effective_feerate and n_input_bytes = 1'000'000, input_fee <= MAX_MONEY.155const int n_input_bytes{fuzzed_data_provider.ConsumeIntegralInRange<int>(1, 1'000'000)};156// Only make UTXOs with positive effective value157const CAmount input_fee = coin_params.m_effective_feerate.GetFee(n_input_bytes);158// Ensure that each UTXO has at least an effective value of 1 sat159const CAmount eff_value{fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(1, MAX_MONEY + group_pos.size() - max_spendable - max_output_groups)};160const CAmount amount{eff_value + input_fee};161std::vector<COutput> temp_utxo_pool;163AddCoin(amount, /*n_input=*/0, n_input_bytes, ++next_locktime, temp_utxo_pool, coin_params.m_effective_feerate);164max_spendable += eff_value;166auto output_group = OutputGroup(coin_params);167output_group.Insert(std::make_shared<COutput>(temp_utxo_pool.at(0)), /*ancestors=*/0, /*cluster_count=*/0);168group_pos.push_back(output_group);169}170size_t num_groups = group_pos.size();171assert(num_groups <= max_output_groups);173// Only choose targets below max_spendable174const CAmount target{fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(1, std::max(CAmount{1}, max_spendable - coin_params.m_min_change_target))};176// Brute force optimal solution177CAmount best_amount{MAX_MONEY};178int best_weight{std::numeric_limits<int>::max()};179for (uint32_t pattern = 1; (pattern >> num_groups) == 0; ++pattern) {180CAmount subset_amount{0};181int subset_weight{0};182for (unsigned i = 0; i < num_groups; ++i) {183if ((pattern >> i) & 1) {184subset_amount += group_pos[i].GetSelectionAmount();185subset_weight += group_pos[i].m_weight;186}187}188if ((subset_amount >= target + coin_params.m_min_change_target) && (subset_weight < best_weight || (subset_weight == best_weight && subset_amount < best_amount))) {189best_weight = subset_weight;190best_amount = subset_amount;191}192}194if (best_weight < std::numeric_limits<int>::max()) {195// Sufficient funds and acceptable weight: CoinGrinder should find at least one solution196int high_max_selection_weight = fuzzed_data_provider.ConsumeIntegralInRange<int>(best_weight, std::numeric_limits<int>::max());198auto result_cg = CoinGrinder(group_pos, target, coin_params.m_min_change_target, high_max_selection_weight);199assert(result_cg);200assert(result_cg->GetWeight() <= high_max_selection_weight);201assert(result_cg->GetSelectedEffectiveValue() >= target + coin_params.m_min_change_target);202assert(best_weight < result_cg->GetWeight() || (best_weight == result_cg->GetWeight() && best_amount <= result_cg->GetSelectedEffectiveValue()));203if (result_cg->GetAlgoCompleted()) {204// If CoinGrinder exhausted the search space, it must return the optimal solution205assert(best_weight == result_cg->GetWeight());206assert(best_amount == result_cg->GetSelectedEffectiveValue());207}208}210// CoinGrinder cannot ever find a better solution than the brute-forced best, or there is none in the first place211int low_max_selection_weight = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, best_weight - 1);212auto result_cg = CoinGrinder(group_pos, target, coin_params.m_min_change_target, low_max_selection_weight);213// Max_weight should have been exceeded, or there were insufficient funds214assert(!result_cg);215}217FUZZ_TARGET(bnb_finds_min_waste)218{219FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};221FastRandomContext fast_random_context{ConsumeUInt256(fuzzed_data_provider)};222CoinSelectionParams coin_params{fast_random_context};223coin_params.m_subtract_fee_outputs = false;224// Set effective feerate up to 10'000'000 sats per kvB (10'000 sat/vB).225coin_params.m_effective_feerate = CFeeRate{ConsumeMoney(fuzzed_data_provider, 10'000'000), 1'000};226coin_params.m_long_term_feerate = CFeeRate{ConsumeMoney(fuzzed_data_provider, 10'000'000), 1'000};227coin_params.m_discard_feerate = CFeeRate{ConsumeMoney(fuzzed_data_provider, 10'000'000), 1'000};228coin_params.m_cost_of_change = ConsumeMoney(fuzzed_data_provider);230coin_params.change_output_size = fuzzed_data_provider.ConsumeIntegralInRange(1, MAX_SCRIPT_SIZE);231coin_params.m_change_fee = coin_params.m_effective_feerate.GetFee(coin_params.change_output_size);232coin_params.change_spend_size = fuzzed_data_provider.ConsumeIntegralInRange<int>(41, 1000);233const auto change_spend_fee{coin_params.m_discard_feerate.GetFee(coin_params.change_spend_size)};234coin_params.m_cost_of_change = coin_params.m_change_fee + change_spend_fee;235CScript change_out_script = CScript() << std::vector<unsigned char>(coin_params.change_output_size, OP_TRUE);236const auto dust{GetDustThreshold(CTxOut{/*nValueIn=*/0, change_out_script}, coin_params.m_discard_feerate)};237coin_params.min_viable_change = std::max(change_spend_fee + 1, dust);239// Create some coins240CAmount max_spendable{0};241int next_locktime{0};242// Too many output groups (>17?) would make it possible to generate UTXO243// pool and target combinations that cannot be completely searched by BnB244// before running into the attempt limit (see BnB "Exhaust..." test). The245// brute force search also gets exponentially more expensive with bigger246// UTXO pools.247// Choose 1–16 of 16 provides ample fuzzing space.248static constexpr unsigned max_output_groups{16};249std::vector<OutputGroup> group_pos;250LIMITED_WHILE (fuzzed_data_provider.ConsumeBool(), max_output_groups) {
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.