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.
502// if we add more small coins:503add_coin(available_coins, *wallet, CENT * 6 / 10);504add_coin(available_coins, *wallet, CENT * 7 / 10);506// and try again to make 1.0 * CENT507const auto result18 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 1 * CENT, CENT);508BOOST_CHECK(result18);509BOOST_CHECK_EQUAL(result18->GetSelectedValue(), 1 * CENT); // we should get the exact amount511// run the 'mtgox' test (see https://blockexplorer.com/tx/29a3efd3ef04f9153d47a990bd7b048a4b2d213daaa5fb8ed670fb85f13bdbcf)512// they tried to consolidate 10 50k coins into one 500k coin, and ended up with 50k in change513available_coins = {};514for (int j = 0; j < 20; j++)515add_coin(available_coins, *wallet, 50000 * COIN);517const auto result19 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 500000 * COIN, CENT);518BOOST_CHECK(result19);519BOOST_CHECK_EQUAL(result19->GetSelectedValue(), 500000 * COIN); // we should get the exact amount520BOOST_CHECK_EQUAL(result19->GetInputSet().size(), 10U); // in ten coins522// if there's not enough in the smaller coins to make at least 1 * CENT change (0.5+0.6+0.7 < 1.0+1.0),523// we need to try finding an exact subset anyway525// sometimes it will fail, and so we use the next biggest coin:526available_coins = {};527add_coin(available_coins, *wallet, CENT * 5 / 10);528add_coin(available_coins, *wallet, CENT * 6 / 10);529add_coin(available_coins, *wallet, CENT * 7 / 10);530add_coin(available_coins, *wallet, 1111 * CENT);531const auto result20 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 1 * CENT, CENT);532BOOST_CHECK(result20);533BOOST_CHECK_EQUAL(result20->GetSelectedValue(), 1111 * CENT); // we get the bigger coin534BOOST_CHECK_EQUAL(result20->GetInputSet().size(), 1U);536// but sometimes it's possible, and we use an exact subset (0.4 + 0.6 = 1.0)537available_coins = {};538add_coin(available_coins, *wallet, CENT * 4 / 10);539add_coin(available_coins, *wallet, CENT * 6 / 10);540add_coin(available_coins, *wallet, CENT * 8 / 10);541add_coin(available_coins, *wallet, 1111 * CENT);542const auto result21 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), CENT, CENT);543BOOST_CHECK(result21);544BOOST_CHECK_EQUAL(result21->GetSelectedValue(), CENT); // we should get the exact amount545BOOST_CHECK_EQUAL(result21->GetInputSet().size(), 2U); // in two coins 0.4+0.6547// test avoiding small change548available_coins = {};549add_coin(available_coins, *wallet, CENT * 5 / 100);550add_coin(available_coins, *wallet, CENT * 1);551add_coin(available_coins, *wallet, CENT * 100);553// trying to make 100.01 from these three coins554const auto result22 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), CENT * 10001 / 100, CENT);555BOOST_CHECK(result22);556BOOST_CHECK_EQUAL(result22->GetSelectedValue(), CENT * 10105 / 100); // we should get all coins557BOOST_CHECK_EQUAL(result22->GetInputSet().size(), 3U);559// but if we try to make 99.9, we should take the bigger of the two small coins to avoid small change560const auto result23 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), CENT * 9990 / 100, CENT);561BOOST_CHECK(result23);562BOOST_CHECK_EQUAL(result23->GetSelectedValue(), 101 * CENT);563BOOST_CHECK_EQUAL(result23->GetInputSet().size(), 2U);564}566// test with many inputs567for (CAmount amt=1500; amt < COIN; amt*=10) {568available_coins = {};569// Create 676 inputs (= (old MAX_STANDARD_TX_SIZE == 100000) / 148 bytes per input)570for (uint16_t j = 0; j < 676; j++)571add_coin(available_coins, *wallet, amt);573// We only create the wallet once to save time, but we still run the coin selection RUN_TESTS times.574for (int i = 0; i < RUN_TESTS; i++) {575const auto result24 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 2000, CENT);576BOOST_CHECK(result24);578if (amt - 2000 < CENT) {579// needs more than one input:580uint16_t returnSize = std::ceil((2000.0 + CENT)/amt);581CAmount returnValue = amt * returnSize;582BOOST_CHECK_EQUAL(result24->GetSelectedValue(), returnValue);583BOOST_CHECK_EQUAL(result24->GetInputSet().size(), returnSize);584} else {585// one input is sufficient:586BOOST_CHECK_EQUAL(result24->GetSelectedValue(), amt);587BOOST_CHECK_EQUAL(result24->GetInputSet().size(), 1U);588}589}590}592// test randomness593{594available_coins = {};595for (int i2 = 0; i2 < 100; i2++)596add_coin(available_coins, *wallet, COIN);598// Again, we only create the wallet once to save time, but we still run the coin selection RUN_TESTS times.599for (int i = 0; i < RUN_TESTS; i++) {600// picking 50 from 100 coins doesn't depend on the shuffle,601// but does depend on randomness in the stochastic approximation code602const auto result25 = KnapsackSolver(GroupCoins(available_coins.All()), 50 * COIN, CENT);603BOOST_CHECK(result25);604const auto result26 = KnapsackSolver(GroupCoins(available_coins.All()), 50 * COIN, CENT);605BOOST_CHECK(result26);606BOOST_CHECK(!EqualResult(*result25, *result26));608int fails = 0;609for (int j = 0; j < RANDOM_REPEATS; j++)610{611// Test that the KnapsackSolver selects randomly from equivalent coins (same value and same input size).612// When choosing 1 from 100 identical coins, 1% of the time, this test will choose the same coin twice613// which will cause it to fail.614// To avoid that issue, run the test RANDOM_REPEATS times and only complain if all of them fail615const auto result27 = KnapsackSolver(GroupCoins(available_coins.All()), COIN, CENT);616BOOST_CHECK(result27);617const auto result28 = KnapsackSolver(GroupCoins(available_coins.All()), COIN, CENT);618BOOST_CHECK(result28);619if (EqualResult(*result27, *result28))620fails++;621}622BOOST_CHECK_NE(fails, RANDOM_REPEATS);623}625// add 75 cents in small change. not enough to make 90 cents,626// then try making 90 cents. there are multiple competing "smallest bigger" coins,627// one of which should be picked at random628add_coin(available_coins, *wallet, 5 * CENT);629add_coin(available_coins, *wallet, 10 * CENT);630add_coin(available_coins, *wallet, 15 * CENT);631add_coin(available_coins, *wallet, 20 * CENT);632add_coin(available_coins, *wallet, 25 * CENT);634for (int i = 0; i < RUN_TESTS; i++) {635int fails = 0;636for (int j = 0; j < RANDOM_REPEATS; j++)637{638const auto result29 = KnapsackSolver(GroupCoins(available_coins.All()), 90 * CENT, CENT);639BOOST_CHECK(result29);640const auto result30 = KnapsackSolver(GroupCoins(available_coins.All()), 90 * CENT, CENT);641BOOST_CHECK(result30);642if (EqualResult(*result29, *result30))643fails++;644}645BOOST_CHECK_NE(fails, RANDOM_REPEATS);646}647}648}650BOOST_AUTO_TEST_CASE(ApproximateBestSubset)651{652FastRandomContext rand{};653std::unique_ptr<CWallet> wallet = NewWallet(m_node);655CoinsResult available_coins;657// Test vValue sort order658for (int i = 0; i < 1000; i++)659add_coin(available_coins, *wallet, 1000 * COIN);660add_coin(available_coins, *wallet, 3 * COIN);662const auto result = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_standard), 1003 * COIN, CENT, rand);663BOOST_CHECK(result);664BOOST_CHECK_EQUAL(result->GetSelectedValue(), 1003 * COIN);665BOOST_CHECK_EQUAL(result->GetInputSet().size(), 2U);666}668// Tests that with the ideal conditions, the coin selector will always be able to find a solution that can pay the target value669BOOST_AUTO_TEST_CASE(SelectCoins_test)670{671std::unique_ptr<CWallet> wallet = NewWallet(m_node);672LOCK(wallet->cs_wallet); // Every 'SelectCoins' call requires it674// Random generator stuff675std::default_random_engine generator;676std::exponential_distribution<double> distribution (100);677FastRandomContext rand;679// Run this test 100 times680for (int i = 0; i < 100; ++i)681{682CoinsResult available_coins;683CAmount balance{0};685// Make a wallet with 1000 exponentially distributed random inputs686for (int j = 0; j < 1000; ++j)687{688CAmount val = distribution(generator)*10000000;689add_coin(available_coins, *wallet, val);690balance += val;691}693// Generate a random fee rate in the range of 100 - 400694CFeeRate rate(rand.randrange(300) + 100);696// Generate a random target value between 1000 and wallet balance697CAmount target = rand.randrange(balance - 1000) + 1000;699// Perform selection700CoinSelectionParams cs_params{701rand,702/*change_output_size=*/ 34,703/*change_spend_size=*/ 148,704/*min_change_target=*/ CENT,705/*effective_feerate=*/ CFeeRate(0),706/*long_term_feerate=*/ CFeeRate(0),707/*discard_feerate=*/ CFeeRate(0),708/*tx_noinputs_size=*/ 0,709/*avoid_partial=*/ false,710};711cs_params.m_cost_of_change = 1;712cs_params.min_viable_change = 1;713CCoinControl cc;714const auto result = SelectCoins(*wallet, available_coins, /*pre_set_inputs=*/{}, target, cc, cs_params);715BOOST_CHECK(result);716BOOST_CHECK_GE(result->GetSelectedValue(), target);717}718}720BOOST_AUTO_TEST_CASE(waste_test)721{722const CAmount fee{100};723const CAmount min_viable_change{300};724const CAmount change_cost{125};725const CAmount change_fee{30};726const CAmount fee_diff{40};727const CAmount in_amt{3 * COIN};728const CAmount target{2 * COIN};729const CAmount excess{80};730const CAmount exact_target{in_amt - fee * 2}; // Maximum spendable amount after fees: no change, no excess732// In the following, we test that the waste is calculated correctly in various scenarios.733// Usually, RecalculateWaste would compute change_fee and change_cost on basis of the734// change output type, current feerate, and discard_feerate, but we use fixed values735// across this test to make the test easier to understand.736{737// Waste with change is the change cost and difference between fee and long term fee738SelectionResult selection1{target, SelectionAlgorithm::MANUAL};739add_coin(1 * COIN, 1, selection1, /*fee=*/fee, /*long_term_fee=*/fee - fee_diff);740add_coin(2 * COIN, 2, selection1, fee, fee - fee_diff);741selection1.RecalculateWaste(min_viable_change, change_cost, change_fee);742BOOST_CHECK_EQUAL(fee_diff * 2 + change_cost, selection1.GetWaste());744// Waste will be greater when fee is greater, but long term fee is the same745SelectionResult selection2{target, SelectionAlgorithm::MANUAL};746add_coin(1 * COIN, 1, selection2, fee * 2, fee - fee_diff);747add_coin(2 * COIN, 2, selection2, fee * 2, fee - fee_diff);748selection2.RecalculateWaste(min_viable_change, change_cost, change_fee);749BOOST_CHECK_GT(selection2.GetWaste(), selection1.GetWaste());
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.