Bitcoin Core 29.99.0
P2P Digital Currency
coinselector_tests.cpp
Go to the documentation of this file.
1// Copyright (c) 2017-2022 The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <consensus/amount.h>
6#include <node/context.h>
7#include <policy/policy.h>
9#include <random.h>
11#include <util/translation.h>
12#include <wallet/coincontrol.h>
14#include <wallet/spend.h>
15#include <wallet/test/util.h>
17#include <wallet/wallet.h>
18
19#include <algorithm>
20#include <boost/test/unit_test.hpp>
21#include <random>
22
23namespace wallet {
24BOOST_FIXTURE_TEST_SUITE(coinselector_tests, WalletTestingSetup)
25
26// how many times to run all the tests to have a chance to catch errors that only show up with particular random shuffles
27#define RUN_TESTS 100
28
29// some tests fail 1% of the time due to bad luck.
30// we repeat those tests this many times and only complain if all iterations of the test fail
31#define RANDOM_REPEATS 5
32
33typedef std::set<std::shared_ptr<COutput>> CoinSet;
34
38static int nextLockTime = 0;
39
40static void add_coin(const CAmount& nValue, int nInput, SelectionResult& result)
41{
43 tx.vout.resize(nInput + 1);
44 tx.vout[nInput].nValue = nValue;
45 tx.nLockTime = nextLockTime++; // so all transactions get different hashes
46 COutput output(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, /*input_bytes=*/ -1, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, /*fees=*/ 0);
48 group.Insert(std::make_shared<COutput>(output), /*ancestors=*/ 0, /*descendants=*/ 0);
49 result.AddInput(group);
50}
51
52static void add_coin(const CAmount& nValue, int nInput, SelectionResult& result, CAmount fee, CAmount long_term_fee)
53{
55 tx.vout.resize(nInput + 1);
56 tx.vout[nInput].nValue = nValue;
57 tx.nLockTime = nextLockTime++; // so all transactions get different hashes
58 std::shared_ptr<COutput> coin = std::make_shared<COutput>(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, /*input_bytes=*/ 148, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, fee);
60 group.Insert(coin, /*ancestors=*/ 0, /*descendants=*/ 0);
61 coin->long_term_fee = long_term_fee; // group.Insert() will modify long_term_fee, so we need to set it afterwards
62 result.AddInput(group);
63}
64
65static void add_coin(CoinsResult& available_coins, CWallet& wallet, const CAmount& nValue, CFeeRate feerate = CFeeRate(0), int nAge = 6*24, bool fIsFromMe = false, int nInput =0, bool spendable = false, int custom_size = 0)
66{
68 tx.nLockTime = nextLockTime++; // so all transactions get different hashes
69 tx.vout.resize(nInput + 1);
70 tx.vout[nInput].nValue = nValue;
71 if (spendable) {
72 tx.vout[nInput].scriptPubKey = GetScriptForDestination(*Assert(wallet.GetNewDestination(OutputType::BECH32, "")));
73 }
74 uint256 txid = tx.GetHash();
75
76 LOCK(wallet.cs_wallet);
77 auto ret = wallet.mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(txid), std::forward_as_tuple(MakeTransactionRef(std::move(tx)), TxStateInactive{}));
78 assert(ret.second);
79 CWalletTx& wtx = (*ret.first).second;
80 const auto& txout = wtx.tx->vout.at(nInput);
81 available_coins.Add(OutputType::BECH32, {COutPoint(wtx.GetHash(), nInput), txout, nAge, custom_size == 0 ? CalculateMaximumSignedInputSize(txout, &wallet, /*coin_control=*/nullptr) : custom_size, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, wtx.GetTxTime(), fIsFromMe, feerate});
82}
83
84// Helpers
85std::optional<SelectionResult> KnapsackSolver(std::vector<OutputGroup>& groups, const CAmount& nTargetValue,
86 CAmount change_target, FastRandomContext& rng)
87{
88 auto res{KnapsackSolver(groups, nTargetValue, change_target, rng, MAX_STANDARD_TX_WEIGHT)};
89 return res ? std::optional<SelectionResult>(*res) : std::nullopt;
90}
91
92std::optional<SelectionResult> SelectCoinsBnB(std::vector<OutputGroup>& utxo_pool, const CAmount& selection_target, const CAmount& cost_of_change)
93{
94 auto res{SelectCoinsBnB(utxo_pool, selection_target, cost_of_change, MAX_STANDARD_TX_WEIGHT)};
95 return res ? std::optional<SelectionResult>(*res) : std::nullopt;
96}
97
100static bool EquivalentResult(const SelectionResult& a, const SelectionResult& b)
101{
102 std::vector<CAmount> a_amts;
103 std::vector<CAmount> b_amts;
104 for (const auto& coin : a.GetInputSet()) {
105 a_amts.push_back(coin->txout.nValue);
106 }
107 for (const auto& coin : b.GetInputSet()) {
108 b_amts.push_back(coin->txout.nValue);
109 }
110 std::sort(a_amts.begin(), a_amts.end());
111 std::sort(b_amts.begin(), b_amts.end());
112
113 std::pair<std::vector<CAmount>::iterator, std::vector<CAmount>::iterator> ret = std::mismatch(a_amts.begin(), a_amts.end(), b_amts.begin());
114 return ret.first == a_amts.end() && ret.second == b_amts.end();
115}
116
118static bool EqualResult(const SelectionResult& a, const SelectionResult& b)
119{
120 std::pair<CoinSet::iterator, CoinSet::iterator> ret = std::mismatch(a.GetInputSet().begin(), a.GetInputSet().end(), b.GetInputSet().begin(),
121 [](const std::shared_ptr<COutput>& a, const std::shared_ptr<COutput>& b) {
122 return a->outpoint == b->outpoint;
123 });
124 return ret.first == a.GetInputSet().end() && ret.second == b.GetInputSet().end();
125}
126
127inline std::vector<OutputGroup>& GroupCoins(const std::vector<COutput>& available_coins, bool subtract_fee_outputs = false)
128{
129 static std::vector<OutputGroup> static_groups;
130 static_groups.clear();
131 for (auto& coin : available_coins) {
132 static_groups.emplace_back();
133 OutputGroup& group = static_groups.back();
134 group.Insert(std::make_shared<COutput>(coin), /*ancestors=*/ 0, /*descendants=*/ 0);
135 group.m_subtract_fee_outputs = subtract_fee_outputs;
136 }
137 return static_groups;
138}
139
140inline std::vector<OutputGroup>& KnapsackGroupOutputs(const CoinsResult& available_coins, CWallet& wallet, const CoinEligibilityFilter& filter)
141{
142 FastRandomContext rand{};
143 CoinSelectionParams coin_selection_params{
144 rand,
145 /*change_output_size=*/ 0,
146 /*change_spend_size=*/ 0,
147 /*min_change_target=*/ CENT,
148 /*effective_feerate=*/ CFeeRate(0),
149 /*long_term_feerate=*/ CFeeRate(0),
150 /*discard_feerate=*/ CFeeRate(0),
151 /*tx_noinputs_size=*/ 0,
152 /*avoid_partial=*/ false,
153 };
154 static OutputGroupTypeMap static_groups;
155 static_groups = GroupOutputs(wallet, available_coins, coin_selection_params, {{filter}})[filter];
156 return static_groups.all_groups.mixed_group;
157}
158
159static std::unique_ptr<CWallet> NewWallet(const node::NodeContext& m_node, const std::string& wallet_name = "")
160{
161 std::unique_ptr<CWallet> wallet = std::make_unique<CWallet>(m_node.chain.get(), wallet_name, CreateMockableWalletDatabase());
162 BOOST_CHECK(wallet->LoadWallet() == DBErrors::LOAD_OK);
163 LOCK(wallet->cs_wallet);
164 wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
165 wallet->SetupDescriptorScriptPubKeyMans();
166 return wallet;
167}
168
169// Branch and bound coin selection tests
170BOOST_AUTO_TEST_CASE(bnb_search_test)
171{
172 FastRandomContext rand{};
173 // Setup
174 std::vector<COutput> utxo_pool;
176
178 // Behavior tests //
180
181 // Make sure that effective value is working in AttemptSelection when BnB is used
182 CoinSelectionParams coin_selection_params_bnb{
183 rand,
184 /*change_output_size=*/ 31,
185 /*change_spend_size=*/ 68,
186 /*min_change_target=*/ 0,
187 /*effective_feerate=*/ CFeeRate(3000),
188 /*long_term_feerate=*/ CFeeRate(1000),
189 /*discard_feerate=*/ CFeeRate(1000),
190 /*tx_noinputs_size=*/ 0,
191 /*avoid_partial=*/ false,
192 };
193 coin_selection_params_bnb.m_change_fee = coin_selection_params_bnb.m_effective_feerate.GetFee(coin_selection_params_bnb.change_output_size);
194 coin_selection_params_bnb.m_cost_of_change = coin_selection_params_bnb.m_effective_feerate.GetFee(coin_selection_params_bnb.change_spend_size) + coin_selection_params_bnb.m_change_fee;
195 coin_selection_params_bnb.min_viable_change = coin_selection_params_bnb.m_effective_feerate.GetFee(coin_selection_params_bnb.change_spend_size);
196
197 {
198 std::unique_ptr<CWallet> wallet = NewWallet(m_node);
199
200 CoinsResult available_coins;
201
202 add_coin(available_coins, *wallet, 1, coin_selection_params_bnb.m_effective_feerate);
203 available_coins.All().at(0).input_bytes = 40; // Make sure that it has a negative effective value. The next check should assert if this somehow got through. Otherwise it will fail
204 BOOST_CHECK(!SelectCoinsBnB(GroupCoins(available_coins.All()), 1 * CENT, coin_selection_params_bnb.m_cost_of_change));
205
206 // Test fees subtracted from output:
207 available_coins.Clear();
208 add_coin(available_coins, *wallet, 1 * CENT, coin_selection_params_bnb.m_effective_feerate);
209 available_coins.All().at(0).input_bytes = 40;
210 const auto result9 = SelectCoinsBnB(GroupCoins(available_coins.All()), 1 * CENT, coin_selection_params_bnb.m_cost_of_change);
211 BOOST_CHECK(result9);
212 BOOST_CHECK_EQUAL(result9->GetSelectedValue(), 1 * CENT);
213 }
214
215 {
216 std::unique_ptr<CWallet> wallet = NewWallet(m_node);
217
218 CoinsResult available_coins;
219
220 coin_selection_params_bnb.m_effective_feerate = CFeeRate(0);
221 add_coin(available_coins, *wallet, 5 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
222 add_coin(available_coins, *wallet, 3 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
223 add_coin(available_coins, *wallet, 2 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
224 CCoinControl coin_control;
225 coin_control.m_allow_other_inputs = true;
226 COutput select_coin = available_coins.All().at(0);
227 coin_control.Select(select_coin.outpoint);
228 PreSelectedInputs selected_input;
229 selected_input.Insert(select_coin, coin_selection_params_bnb.m_subtract_fee_outputs);
230 available_coins.Erase({available_coins.coins[OutputType::BECH32].begin()->outpoint});
231
232 LOCK(wallet->cs_wallet);
233 const auto result10 = SelectCoins(*wallet, available_coins, selected_input, 10 * CENT, coin_control, coin_selection_params_bnb);
234 BOOST_CHECK(result10);
235 }
236 {
237 std::unique_ptr<CWallet> wallet = NewWallet(m_node);
238 LOCK(wallet->cs_wallet); // Every 'SelectCoins' call requires it
239
240 CoinsResult available_coins;
241
242 // pre selected coin should be selected even if disadvantageous
243 coin_selection_params_bnb.m_effective_feerate = CFeeRate(5000);
244 coin_selection_params_bnb.m_long_term_feerate = CFeeRate(3000);
245
246 // Add selectable outputs, increasing their raw amounts by their input fee to make the effective value equal to the raw amount
247 CAmount input_fee = coin_selection_params_bnb.m_effective_feerate.GetFee(/*num_bytes=*/68); // bech32 input size (default test output type)
248 add_coin(available_coins, *wallet, 10 * CENT + input_fee, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
249 add_coin(available_coins, *wallet, 9 * CENT + input_fee, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
250 add_coin(available_coins, *wallet, 1 * CENT + input_fee, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
251
252 expected_result.Clear();
253 add_coin(9 * CENT + input_fee, 2, expected_result);
254 add_coin(1 * CENT + input_fee, 2, expected_result);
255 CCoinControl coin_control;
256 coin_control.m_allow_other_inputs = true;
257 COutput select_coin = available_coins.All().at(1); // pre select 9 coin
258 coin_control.Select(select_coin.outpoint);
259 PreSelectedInputs selected_input;
260 selected_input.Insert(select_coin, coin_selection_params_bnb.m_subtract_fee_outputs);
261 available_coins.Erase({(++available_coins.coins[OutputType::BECH32].begin())->outpoint});
262 const auto result13 = SelectCoins(*wallet, available_coins, selected_input, 10 * CENT, coin_control, coin_selection_params_bnb);
263 BOOST_CHECK(EquivalentResult(expected_result, *result13));
264 }
265
266 {
267 // Test bnb max weight exceeded
268 // Inputs set [10, 9, 8, 5, 3, 1], Selection Target = 16 and coin 5 exceeding the max weight.
269
270 std::unique_ptr<CWallet> wallet = NewWallet(m_node);
271
272 CoinsResult available_coins;
273 add_coin(available_coins, *wallet, 10 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
274 add_coin(available_coins, *wallet, 9 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
275 add_coin(available_coins, *wallet, 8 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
276 add_coin(available_coins, *wallet, 5 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true, /*custom_size=*/MAX_STANDARD_TX_WEIGHT);
277 add_coin(available_coins, *wallet, 3 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
278 add_coin(available_coins, *wallet, 1 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
279
280 CAmount selection_target = 16 * CENT;
281 const auto& no_res = SelectCoinsBnB(GroupCoins(available_coins.All(), /*subtract_fee_outputs*/true),
282 selection_target, /*cost_of_change=*/0, MAX_STANDARD_TX_WEIGHT);
283 BOOST_REQUIRE(!no_res);
284 BOOST_CHECK(util::ErrorString(no_res).original.find("The inputs size exceeds the maximum weight") != std::string::npos);
285
286 // Now add same coin value with a good size and check that it gets selected
287 add_coin(available_coins, *wallet, 5 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true);
288 const auto& res = SelectCoinsBnB(GroupCoins(available_coins.All(), /*subtract_fee_outputs*/true), selection_target, /*cost_of_change=*/0);
289
290 expected_result.Clear();
291 add_coin(8 * CENT, 2, expected_result);
292 add_coin(5 * CENT, 2, expected_result);
293 add_coin(3 * CENT, 2, expected_result);
294 BOOST_CHECK(EquivalentResult(expected_result, *res));
295 }
296}
297
298BOOST_AUTO_TEST_CASE(bnb_sffo_restriction)
299{
300 // Verify the coin selection process does not produce a BnB solution when SFFO is enabled.
301 // This is currently problematic because it could require a change output. And BnB is specialized on changeless solutions.
302 std::unique_ptr<CWallet> wallet = NewWallet(m_node);
303 WITH_LOCK(wallet->cs_wallet, wallet->SetLastBlockProcessed(300, uint256{})); // set a high block so internal UTXOs are selectable
304
305 FastRandomContext rand{};
306 CoinSelectionParams params{
307 rand,
308 /*change_output_size=*/ 31, // unused value, p2wpkh output size (wallet default change type)
309 /*change_spend_size=*/ 68, // unused value, p2wpkh input size (high-r signature)
310 /*min_change_target=*/ 0, // dummy, set later
311 /*effective_feerate=*/ CFeeRate(3000),
312 /*long_term_feerate=*/ CFeeRate(1000),
313 /*discard_feerate=*/ CFeeRate(1000),
314 /*tx_noinputs_size=*/ 0,
315 /*avoid_partial=*/ false,
316 };
317 params.m_subtract_fee_outputs = true;
318 params.m_change_fee = params.m_effective_feerate.GetFee(params.change_output_size);
319 params.m_cost_of_change = params.m_discard_feerate.GetFee(params.change_spend_size) + params.m_change_fee;
320 params.m_min_change_target = params.m_cost_of_change + 1;
321 // Add spendable coin at the BnB selection upper bound
322 CoinsResult available_coins;
323 add_coin(available_coins, *wallet, COIN + params.m_cost_of_change, /*feerate=*/params.m_effective_feerate, /*nAge=*/6, /*fIsFromMe=*/true, /*nInput=*/0, /*spendable=*/true);
324 add_coin(available_coins, *wallet, 0.5 * COIN + params.m_cost_of_change, /*feerate=*/params.m_effective_feerate, /*nAge=*/6, /*fIsFromMe=*/true, /*nInput=*/0, /*spendable=*/true);
325 add_coin(available_coins, *wallet, 0.5 * COIN, /*feerate=*/params.m_effective_feerate, /*nAge=*/6, /*fIsFromMe=*/true, /*nInput=*/0, /*spendable=*/true);
326 // Knapsack will only find a changeless solution on an exact match to the satoshi, SRD doesn’t look for changeless
327 // If BnB were run, it would produce a single input solution with the best waste score
328 auto result = WITH_LOCK(wallet->cs_wallet, return SelectCoins(*wallet, available_coins, /*pre_set_inputs=*/{}, COIN, /*coin_control=*/{}, params));
329 BOOST_CHECK(result.has_value());
330 BOOST_CHECK_NE(result->GetAlgo(), SelectionAlgorithm::BNB);
331 BOOST_CHECK(result->GetInputSet().size() == 2);
332 // We have only considered BnB, SRD, and Knapsack. Test needs to be reevaluated if new algo is added
333 BOOST_CHECK(result->GetAlgo() == SelectionAlgorithm::SRD || result->GetAlgo() == SelectionAlgorithm::KNAPSACK);
334}
335
336BOOST_AUTO_TEST_CASE(knapsack_solver_test)
337{
338 FastRandomContext rand{};
339 const auto temp1{[&rand](std::vector<OutputGroup>& g, const CAmount& v, CAmount c) { return KnapsackSolver(g, v, c, rand); }};
340 const auto KnapsackSolver{temp1};
341 std::unique_ptr<CWallet> wallet = NewWallet(m_node);
342
343 CoinsResult available_coins;
344
345 // test multiple times to allow for differences in the shuffle order
346 for (int i = 0; i < RUN_TESTS; i++)
347 {
348 available_coins.Clear();
349
350 // with an empty wallet we can't even pay one cent
352
353 add_coin(available_coins, *wallet, 1*CENT, CFeeRate(0), 4); // add a new 1 cent coin
354
355 // with a new 1 cent coin, we still can't find a mature 1 cent
357
358 // but we can find a new 1 cent
359 const auto result1 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 1 * CENT, CENT);
360 BOOST_CHECK(result1);
361 BOOST_CHECK_EQUAL(result1->GetSelectedValue(), 1 * CENT);
362
363 add_coin(available_coins, *wallet, 2*CENT); // add a mature 2 cent coin
364
365 // we can't make 3 cents of mature coins
367
368 // we can make 3 cents of new coins
369 const auto result2 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 3 * CENT, CENT);
370 BOOST_CHECK(result2);
371 BOOST_CHECK_EQUAL(result2->GetSelectedValue(), 3 * CENT);
372
373 add_coin(available_coins, *wallet, 5*CENT); // add a mature 5 cent coin,
374 add_coin(available_coins, *wallet, 10*CENT, CFeeRate(0), 3, true); // a new 10 cent coin sent from one of our own addresses
375 add_coin(available_coins, *wallet, 20*CENT); // and a mature 20 cent coin
376
377 // now we have new: 1+10=11 (of which 10 was self-sent), and mature: 2+5+20=27. total = 38
378
379 // we can't make 38 cents only if we disallow new coins:
381 // we can't even make 37 cents if we don't allow new coins even if they're from us
383 // but we can make 37 cents if we accept new coins from ourself
384 const auto result3 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_standard), 37 * CENT, CENT);
385 BOOST_CHECK(result3);
386 BOOST_CHECK_EQUAL(result3->GetSelectedValue(), 37 * CENT);
387 // and we can make 38 cents if we accept all new coins
388 const auto result4 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 38 * CENT, CENT);
389 BOOST_CHECK(result4);
390 BOOST_CHECK_EQUAL(result4->GetSelectedValue(), 38 * CENT);
391
392 // try making 34 cents from 1,2,5,10,20 - we can't do it exactly
393 const auto result5 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 34 * CENT, CENT);
394 BOOST_CHECK(result5);
395 BOOST_CHECK_EQUAL(result5->GetSelectedValue(), 35 * CENT); // but 35 cents is closest
396 BOOST_CHECK_EQUAL(result5->GetInputSet().size(), 3U); // the best should be 20+10+5. it's incredibly unlikely the 1 or 2 got included (but possible)
397
398 // when we try making 7 cents, the smaller coins (1,2,5) are enough. We should see just 2+5
399 const auto result6 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 7 * CENT, CENT);
400 BOOST_CHECK(result6);
401 BOOST_CHECK_EQUAL(result6->GetSelectedValue(), 7 * CENT);
402 BOOST_CHECK_EQUAL(result6->GetInputSet().size(), 2U);
403
404 // when we try making 8 cents, the smaller coins (1,2,5) are exactly enough.
405 const auto result7 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 8 * CENT, CENT);
406 BOOST_CHECK(result7);
407 BOOST_CHECK(result7->GetSelectedValue() == 8 * CENT);
408 BOOST_CHECK_EQUAL(result7->GetInputSet().size(), 3U);
409
410 // when we try making 9 cents, no subset of smaller coins is enough, and we get the next bigger coin (10)
411 const auto result8 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 9 * CENT, CENT);
412 BOOST_CHECK(result8);
413 BOOST_CHECK_EQUAL(result8->GetSelectedValue(), 10 * CENT);
414 BOOST_CHECK_EQUAL(result8->GetInputSet().size(), 1U);
415
416 // now clear out the wallet and start again to test choosing between subsets of smaller coins and the next biggest coin
417 available_coins.Clear();
418
419 add_coin(available_coins, *wallet, 6*CENT);
420 add_coin(available_coins, *wallet, 7*CENT);
421 add_coin(available_coins, *wallet, 8*CENT);
422 add_coin(available_coins, *wallet, 20*CENT);
423 add_coin(available_coins, *wallet, 30*CENT); // now we have 6+7+8+20+30 = 71 cents total
424
425 // check that we have 71 and not 72
426 const auto result9 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 71 * CENT, CENT);
427 BOOST_CHECK(result9);
429
430 // now try making 16 cents. the best smaller coins can do is 6+7+8 = 21; not as good at the next biggest coin, 20
431 const auto result10 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 16 * CENT, CENT);
432 BOOST_CHECK(result10);
433 BOOST_CHECK_EQUAL(result10->GetSelectedValue(), 20 * CENT); // we should get 20 in one coin
434 BOOST_CHECK_EQUAL(result10->GetInputSet().size(), 1U);
435
436 add_coin(available_coins, *wallet, 5*CENT); // now we have 5+6+7+8+20+30 = 75 cents total
437
438 // now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, better than the next biggest coin, 20
439 const auto result11 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 16 * CENT, CENT);
440 BOOST_CHECK(result11);
441 BOOST_CHECK_EQUAL(result11->GetSelectedValue(), 18 * CENT); // we should get 18 in 3 coins
442 BOOST_CHECK_EQUAL(result11->GetInputSet().size(), 3U);
443
444 add_coin(available_coins, *wallet, 18*CENT); // now we have 5+6+7+8+18+20+30
445
446 // and now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, the same as the next biggest coin, 18
447 const auto result12 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 16 * CENT, CENT);
448 BOOST_CHECK(result12);
449 BOOST_CHECK_EQUAL(result12->GetSelectedValue(), 18 * CENT); // we should get 18 in 1 coin
450 BOOST_CHECK_EQUAL(result12->GetInputSet().size(), 1U); // because in the event of a tie, the biggest coin wins
451
452 // now try making 11 cents. we should get 5+6
453 const auto result13 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 11 * CENT, CENT);
454 BOOST_CHECK(result13);
455 BOOST_CHECK_EQUAL(result13->GetSelectedValue(), 11 * CENT);
456 BOOST_CHECK_EQUAL(result13->GetInputSet().size(), 2U);
457
458 // check that the smallest bigger coin is used
459 add_coin(available_coins, *wallet, 1*COIN);
460 add_coin(available_coins, *wallet, 2*COIN);
461 add_coin(available_coins, *wallet, 3*COIN);
462 add_coin(available_coins, *wallet, 4*COIN); // now we have 5+6+7+8+18+20+30+100+200+300+400 = 1094 cents
463 const auto result14 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 95 * CENT, CENT);
464 BOOST_CHECK(result14);
465 BOOST_CHECK_EQUAL(result14->GetSelectedValue(), 1 * COIN); // we should get 1 BTC in 1 coin
466 BOOST_CHECK_EQUAL(result14->GetInputSet().size(), 1U);
467
468 const auto result15 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 195 * CENT, CENT);
469 BOOST_CHECK(result15);
470 BOOST_CHECK_EQUAL(result15->GetSelectedValue(), 2 * COIN); // we should get 2 BTC in 1 coin
471 BOOST_CHECK_EQUAL(result15->GetInputSet().size(), 1U);
472
473 // empty the wallet and start again, now with fractions of a cent, to test small change avoidance
474
475 available_coins.Clear();
476 add_coin(available_coins, *wallet, CENT * 1 / 10);
477 add_coin(available_coins, *wallet, CENT * 2 / 10);
478 add_coin(available_coins, *wallet, CENT * 3 / 10);
479 add_coin(available_coins, *wallet, CENT * 4 / 10);
480 add_coin(available_coins, *wallet, CENT * 5 / 10);
481
482 // try making 1 * CENT from the 1.5 * CENT
483 // we'll get change smaller than CENT whatever happens, so can expect CENT exactly
484 const auto result16 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), CENT, CENT);
485 BOOST_CHECK(result16);
486 BOOST_CHECK_EQUAL(result16->GetSelectedValue(), CENT);
487
488 // but if we add a bigger coin, small change is avoided
489 add_coin(available_coins, *wallet, 1111*CENT);
490
491 // try making 1 from 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 1111 = 1112.5
492 const auto result17 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 1 * CENT, CENT);
493 BOOST_CHECK(result17);
494 BOOST_CHECK_EQUAL(result17->GetSelectedValue(), 1 * CENT); // we should get the exact amount
495
496 // if we add more small coins:
497 add_coin(available_coins, *wallet, CENT * 6 / 10);
498 add_coin(available_coins, *wallet, CENT * 7 / 10);
499
500 // and try again to make 1.0 * CENT
501 const auto result18 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 1 * CENT, CENT);
502 BOOST_CHECK(result18);
503 BOOST_CHECK_EQUAL(result18->GetSelectedValue(), 1 * CENT); // we should get the exact amount
504
505 // run the 'mtgox' test (see https://blockexplorer.com/tx/29a3efd3ef04f9153d47a990bd7b048a4b2d213daaa5fb8ed670fb85f13bdbcf)
506 // they tried to consolidate 10 50k coins into one 500k coin, and ended up with 50k in change
507 available_coins.Clear();
508 for (int j = 0; j < 20; j++)
509 add_coin(available_coins, *wallet, 50000 * COIN);
510
511 const auto result19 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 500000 * COIN, CENT);
512 BOOST_CHECK(result19);
513 BOOST_CHECK_EQUAL(result19->GetSelectedValue(), 500000 * COIN); // we should get the exact amount
514 BOOST_CHECK_EQUAL(result19->GetInputSet().size(), 10U); // in ten coins
515
516 // 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),
517 // we need to try finding an exact subset anyway
518
519 // sometimes it will fail, and so we use the next biggest coin:
520 available_coins.Clear();
521 add_coin(available_coins, *wallet, CENT * 5 / 10);
522 add_coin(available_coins, *wallet, CENT * 6 / 10);
523 add_coin(available_coins, *wallet, CENT * 7 / 10);
524 add_coin(available_coins, *wallet, 1111 * CENT);
525 const auto result20 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 1 * CENT, CENT);
526 BOOST_CHECK(result20);
527 BOOST_CHECK_EQUAL(result20->GetSelectedValue(), 1111 * CENT); // we get the bigger coin
528 BOOST_CHECK_EQUAL(result20->GetInputSet().size(), 1U);
529
530 // but sometimes it's possible, and we use an exact subset (0.4 + 0.6 = 1.0)
531 available_coins.Clear();
532 add_coin(available_coins, *wallet, CENT * 4 / 10);
533 add_coin(available_coins, *wallet, CENT * 6 / 10);
534 add_coin(available_coins, *wallet, CENT * 8 / 10);
535 add_coin(available_coins, *wallet, 1111 * CENT);
536 const auto result21 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), CENT, CENT);
537 BOOST_CHECK(result21);
538 BOOST_CHECK_EQUAL(result21->GetSelectedValue(), CENT); // we should get the exact amount
539 BOOST_CHECK_EQUAL(result21->GetInputSet().size(), 2U); // in two coins 0.4+0.6
540
541 // test avoiding small change
542 available_coins.Clear();
543 add_coin(available_coins, *wallet, CENT * 5 / 100);
544 add_coin(available_coins, *wallet, CENT * 1);
545 add_coin(available_coins, *wallet, CENT * 100);
546
547 // trying to make 100.01 from these three coins
548 const auto result22 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), CENT * 10001 / 100, CENT);
549 BOOST_CHECK(result22);
550 BOOST_CHECK_EQUAL(result22->GetSelectedValue(), CENT * 10105 / 100); // we should get all coins
551 BOOST_CHECK_EQUAL(result22->GetInputSet().size(), 3U);
552
553 // but if we try to make 99.9, we should take the bigger of the two small coins to avoid small change
554 const auto result23 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), CENT * 9990 / 100, CENT);
555 BOOST_CHECK(result23);
556 BOOST_CHECK_EQUAL(result23->GetSelectedValue(), 101 * CENT);
557 BOOST_CHECK_EQUAL(result23->GetInputSet().size(), 2U);
558 }
559
560 // test with many inputs
561 for (CAmount amt=1500; amt < COIN; amt*=10) {
562 available_coins.Clear();
563 // Create 676 inputs (= (old MAX_STANDARD_TX_SIZE == 100000) / 148 bytes per input)
564 for (uint16_t j = 0; j < 676; j++)
565 add_coin(available_coins, *wallet, amt);
566
567 // We only create the wallet once to save time, but we still run the coin selection RUN_TESTS times.
568 for (int i = 0; i < RUN_TESTS; i++) {
569 const auto result24 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 2000, CENT);
570 BOOST_CHECK(result24);
571
572 if (amt - 2000 < CENT) {
573 // needs more than one input:
574 uint16_t returnSize = std::ceil((2000.0 + CENT)/amt);
575 CAmount returnValue = amt * returnSize;
576 BOOST_CHECK_EQUAL(result24->GetSelectedValue(), returnValue);
577 BOOST_CHECK_EQUAL(result24->GetInputSet().size(), returnSize);
578 } else {
579 // one input is sufficient:
580 BOOST_CHECK_EQUAL(result24->GetSelectedValue(), amt);
581 BOOST_CHECK_EQUAL(result24->GetInputSet().size(), 1U);
582 }
583 }
584 }
585
586 // test randomness
587 {
588 available_coins.Clear();
589 for (int i2 = 0; i2 < 100; i2++)
590 add_coin(available_coins, *wallet, COIN);
591
592 // Again, we only create the wallet once to save time, but we still run the coin selection RUN_TESTS times.
593 for (int i = 0; i < RUN_TESTS; i++) {
594 // picking 50 from 100 coins doesn't depend on the shuffle,
595 // but does depend on randomness in the stochastic approximation code
596 const auto result25 = KnapsackSolver(GroupCoins(available_coins.All()), 50 * COIN, CENT);
597 BOOST_CHECK(result25);
598 const auto result26 = KnapsackSolver(GroupCoins(available_coins.All()), 50 * COIN, CENT);
599 BOOST_CHECK(result26);
600 BOOST_CHECK(!EqualResult(*result25, *result26));
601
602 int fails = 0;
603 for (int j = 0; j < RANDOM_REPEATS; j++)
604 {
605 // Test that the KnapsackSolver selects randomly from equivalent coins (same value and same input size).
606 // When choosing 1 from 100 identical coins, 1% of the time, this test will choose the same coin twice
607 // which will cause it to fail.
608 // To avoid that issue, run the test RANDOM_REPEATS times and only complain if all of them fail
609 const auto result27 = KnapsackSolver(GroupCoins(available_coins.All()), COIN, CENT);
610 BOOST_CHECK(result27);
611 const auto result28 = KnapsackSolver(GroupCoins(available_coins.All()), COIN, CENT);
612 BOOST_CHECK(result28);
613 if (EqualResult(*result27, *result28))
614 fails++;
615 }
616 BOOST_CHECK_NE(fails, RANDOM_REPEATS);
617 }
618
619 // add 75 cents in small change. not enough to make 90 cents,
620 // then try making 90 cents. there are multiple competing "smallest bigger" coins,
621 // one of which should be picked at random
622 add_coin(available_coins, *wallet, 5 * CENT);
623 add_coin(available_coins, *wallet, 10 * CENT);
624 add_coin(available_coins, *wallet, 15 * CENT);
625 add_coin(available_coins, *wallet, 20 * CENT);
626 add_coin(available_coins, *wallet, 25 * CENT);
627
628 for (int i = 0; i < RUN_TESTS; i++) {
629 int fails = 0;
630 for (int j = 0; j < RANDOM_REPEATS; j++)
631 {
632 const auto result29 = KnapsackSolver(GroupCoins(available_coins.All()), 90 * CENT, CENT);
633 BOOST_CHECK(result29);
634 const auto result30 = KnapsackSolver(GroupCoins(available_coins.All()), 90 * CENT, CENT);
635 BOOST_CHECK(result30);
636 if (EqualResult(*result29, *result30))
637 fails++;
638 }
639 BOOST_CHECK_NE(fails, RANDOM_REPEATS);
640 }
641 }
642}
643
645{
646 FastRandomContext rand{};
647 std::unique_ptr<CWallet> wallet = NewWallet(m_node);
648
649 CoinsResult available_coins;
650
651 // Test vValue sort order
652 for (int i = 0; i < 1000; i++)
653 add_coin(available_coins, *wallet, 1000 * COIN);
654 add_coin(available_coins, *wallet, 3 * COIN);
655
656 const auto result = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_standard), 1003 * COIN, CENT, rand);
657 BOOST_CHECK(result);
658 BOOST_CHECK_EQUAL(result->GetSelectedValue(), 1003 * COIN);
659 BOOST_CHECK_EQUAL(result->GetInputSet().size(), 2U);
660}
661
662// Tests that with the ideal conditions, the coin selector will always be able to find a solution that can pay the target value
663BOOST_AUTO_TEST_CASE(SelectCoins_test)
664{
665 std::unique_ptr<CWallet> wallet = NewWallet(m_node);
666 LOCK(wallet->cs_wallet); // Every 'SelectCoins' call requires it
667
668 // Random generator stuff
669 std::default_random_engine generator;
670 std::exponential_distribution<double> distribution (100);
672
673 // Run this test 100 times
674 for (int i = 0; i < 100; ++i)
675 {
676 CoinsResult available_coins;
677 CAmount balance{0};
678
679 // Make a wallet with 1000 exponentially distributed random inputs
680 for (int j = 0; j < 1000; ++j)
681 {
682 CAmount val = distribution(generator)*10000000;
683 add_coin(available_coins, *wallet, val);
684 balance += val;
685 }
686
687 // Generate a random fee rate in the range of 100 - 400
688 CFeeRate rate(rand.randrange(300) + 100);
689
690 // Generate a random target value between 1000 and wallet balance
691 CAmount target = rand.randrange(balance - 1000) + 1000;
692
693 // Perform selection
694 CoinSelectionParams cs_params{
695 rand,
696 /*change_output_size=*/ 34,
697 /*change_spend_size=*/ 148,
698 /*min_change_target=*/ CENT,
699 /*effective_feerate=*/ CFeeRate(0),
700 /*long_term_feerate=*/ CFeeRate(0),
701 /*discard_feerate=*/ CFeeRate(0),
702 /*tx_noinputs_size=*/ 0,
703 /*avoid_partial=*/ false,
704 };
705 cs_params.m_cost_of_change = 1;
706 cs_params.min_viable_change = 1;
707 CCoinControl cc;
708 const auto result = SelectCoins(*wallet, available_coins, /*pre_set_inputs=*/{}, target, cc, cs_params);
709 BOOST_CHECK(result);
710 BOOST_CHECK_GE(result->GetSelectedValue(), target);
711 }
712}
713
715{
716 const CAmount fee{100};
717 const CAmount min_viable_change{300};
718 const CAmount change_cost{125};
719 const CAmount change_fee{30};
720 const CAmount fee_diff{40};
721 const CAmount in_amt{3 * COIN};
722 const CAmount target{2 * COIN};
723 const CAmount excess{80};
724 const CAmount exact_target{in_amt - fee * 2}; // Maximum spendable amount after fees: no change, no excess
725
726 // In the following, we test that the waste is calculated correctly in various scenarios.
727 // Usually, RecalculateWaste would compute change_fee and change_cost on basis of the
728 // change output type, current feerate, and discard_feerate, but we use fixed values
729 // across this test to make the test easier to understand.
730 {
731 // Waste with change is the change cost and difference between fee and long term fee
733 add_coin(1 * COIN, 1, selection1, /*fee=*/fee, /*long_term_fee=*/fee - fee_diff);
734 add_coin(2 * COIN, 2, selection1, fee, fee - fee_diff);
735 selection1.RecalculateWaste(min_viable_change, change_cost, change_fee);
736 BOOST_CHECK_EQUAL(fee_diff * 2 + change_cost, selection1.GetWaste());
737
738 // Waste will be greater when fee is greater, but long term fee is the same
740 add_coin(1 * COIN, 1, selection2, fee * 2, fee - fee_diff);
741 add_coin(2 * COIN, 2, selection2, fee * 2, fee - fee_diff);
742 selection2.RecalculateWaste(min_viable_change, change_cost, change_fee);
743 BOOST_CHECK_GT(selection2.GetWaste(), selection1.GetWaste());
744
745 // Waste with change is the change cost and difference between fee and long term fee
746 // With long term fee greater than fee, waste should be less than when long term fee is less than fee
748 add_coin(1 * COIN, 1, selection3, fee, fee + fee_diff);
749 add_coin(2 * COIN, 2, selection3, fee, fee + fee_diff);
750 selection3.RecalculateWaste(min_viable_change, change_cost, change_fee);
751 BOOST_CHECK_EQUAL(fee_diff * -2 + change_cost, selection3.GetWaste());
752 BOOST_CHECK_LT(selection3.GetWaste(), selection1.GetWaste());
753 }
754
755 {
756 // Waste without change is the excess and difference between fee and long term fee
757 SelectionResult selection_nochange1{exact_target - excess, SelectionAlgorithm::MANUAL};
758 add_coin(1 * COIN, 1, selection_nochange1, fee, fee - fee_diff);
759 add_coin(2 * COIN, 2, selection_nochange1, fee, fee - fee_diff);
760 selection_nochange1.RecalculateWaste(min_viable_change, change_cost, change_fee);
761 BOOST_CHECK_EQUAL(fee_diff * 2 + excess, selection_nochange1.GetWaste());
762
763 // Waste without change is the excess and difference between fee and long term fee
764 // With long term fee greater than fee, waste should be less than when long term fee is less than fee
765 SelectionResult selection_nochange2{exact_target - excess, SelectionAlgorithm::MANUAL};
766 add_coin(1 * COIN, 1, selection_nochange2, fee, fee + fee_diff);
767 add_coin(2 * COIN, 2, selection_nochange2, fee, fee + fee_diff);
768 selection_nochange2.RecalculateWaste(min_viable_change, change_cost, change_fee);
769 BOOST_CHECK_EQUAL(fee_diff * -2 + excess, selection_nochange2.GetWaste());
770 BOOST_CHECK_LT(selection_nochange2.GetWaste(), selection_nochange1.GetWaste());
771 }
772
773 {
774 // Waste with change and fee == long term fee is just cost of change
776 add_coin(1 * COIN, 1, selection, fee, fee);
777 add_coin(2 * COIN, 2, selection, fee, fee);
778 selection.RecalculateWaste(min_viable_change, change_cost, change_fee);
779 BOOST_CHECK_EQUAL(change_cost, selection.GetWaste());
780 }
781
782 {
783 // Waste without change and fee == long term fee is just the excess
784 SelectionResult selection{exact_target - excess, SelectionAlgorithm::MANUAL};
785 add_coin(1 * COIN, 1, selection, fee, fee);
786 add_coin(2 * COIN, 2, selection, fee, fee);
787 selection.RecalculateWaste(min_viable_change, change_cost, change_fee);
788 BOOST_CHECK_EQUAL(excess, selection.GetWaste());
789 }
790
791 {
792 // Waste is 0 when fee == long_term_fee, no change, and no excess
793 SelectionResult selection{exact_target, SelectionAlgorithm::MANUAL};
794 add_coin(1 * COIN, 1, selection, fee, fee);
795 add_coin(2 * COIN, 2, selection, fee, fee);
796 selection.RecalculateWaste(min_viable_change, change_cost , change_fee);
797 BOOST_CHECK_EQUAL(0, selection.GetWaste());
798 }
799
800 {
801 // Waste is 0 when (fee - long_term_fee) == (-cost_of_change), and no excess
803 add_coin(1 * COIN, 1, selection, fee, fee + fee_diff);
804 add_coin(2 * COIN, 2, selection, fee, fee + fee_diff);
805 selection.RecalculateWaste(min_viable_change, /*change_cost=*/fee_diff * 2, change_fee);
806 BOOST_CHECK_EQUAL(0, selection.GetWaste());
807 }
808
809 {
810 // Waste is 0 when (fee - long_term_fee) == (-excess), no change cost
811 const CAmount new_target{exact_target - /*excess=*/fee_diff * 2};
812 SelectionResult selection{new_target, SelectionAlgorithm::MANUAL};
813 add_coin(1 * COIN, 1, selection, fee, fee + fee_diff);
814 add_coin(2 * COIN, 2, selection, fee, fee + fee_diff);
815 selection.RecalculateWaste(min_viable_change, change_cost, change_fee);
816 BOOST_CHECK_EQUAL(0, selection.GetWaste());
817 }
818
819 {
820 // Negative waste when the long term fee is greater than the current fee and the selected value == target
821 SelectionResult selection{exact_target, SelectionAlgorithm::MANUAL};
822 const CAmount target_waste1{-2 * fee_diff}; // = (2 * fee) - (2 * (fee + fee_diff))
823 add_coin(1 * COIN, 1, selection, fee, fee + fee_diff);
824 add_coin(2 * COIN, 2, selection, fee, fee + fee_diff);
825 selection.RecalculateWaste(min_viable_change, change_cost, change_fee);
826 BOOST_CHECK_EQUAL(target_waste1, selection.GetWaste());
827 }
828
829 {
830 // Negative waste when the long term fee is greater than the current fee and change_cost < - (inputs * (fee - long_term_fee))
832 const CAmount large_fee_diff{90};
833 const CAmount target_waste2{-2 * large_fee_diff + change_cost};
834 // = (2 * fee) - (2 * (fee + large_fee_diff)) + change_cost
835 // = (2 * 100) - (2 * (100 + 90)) + 125
836 // = 200 - 380 + 125 = -55
837 assert(target_waste2 == -55);
838 add_coin(1 * COIN, 1, selection, fee, fee + large_fee_diff);
839 add_coin(2 * COIN, 2, selection, fee, fee + large_fee_diff);
840 selection.RecalculateWaste(min_viable_change, change_cost, change_fee);
841 BOOST_CHECK_EQUAL(target_waste2, selection.GetWaste());
842 }
843}
844
845
847{
848 const CAmount fee{100};
849 const CAmount min_viable_change{200};
850 const CAmount change_cost{125};
851 const CAmount change_fee{35};
852 const CAmount fee_diff{40};
853 const CAmount target{2 * COIN};
854
855 {
857 add_coin(1 * COIN, 1, selection, /*fee=*/fee, /*long_term_fee=*/fee + fee_diff);
858 add_coin(2 * COIN, 2, selection, fee, fee + fee_diff);
859 const std::vector<std::shared_ptr<COutput>> inputs = selection.GetShuffledInputVector();
860
861 for (size_t i = 0; i < inputs.size(); ++i) {
862 inputs[i]->ApplyBumpFee(20*(i+1));
863 }
864
865 selection.RecalculateWaste(min_viable_change, change_cost, change_fee);
866 CAmount expected_waste = fee_diff * -2 + change_cost + /*bump_fees=*/60;
867 BOOST_CHECK_EQUAL(expected_waste, selection.GetWaste());
868
869 selection.SetBumpFeeDiscount(30);
870 selection.RecalculateWaste(min_viable_change, change_cost, change_fee);
871 expected_waste = fee_diff * -2 + change_cost + /*bump_fees=*/60 - /*group_discount=*/30;
872 BOOST_CHECK_EQUAL(expected_waste, selection.GetWaste());
873 }
874
875 {
876 // Test with changeless transaction
877 //
878 // Bump fees and excess both contribute fully to the waste score,
879 // therefore, a bump fee group discount will not change the waste
880 // score as long as we do not create change in both instances.
881 CAmount changeless_target = 3 * COIN - 2 * fee - 100;
882 SelectionResult selection{changeless_target, SelectionAlgorithm::MANUAL};
883 add_coin(1 * COIN, 1, selection, /*fee=*/fee, /*long_term_fee=*/fee + fee_diff);
884 add_coin(2 * COIN, 2, selection, fee, fee + fee_diff);
885 const std::vector<std::shared_ptr<COutput>> inputs = selection.GetShuffledInputVector();
886
887 for (size_t i = 0; i < inputs.size(); ++i) {
888 inputs[i]->ApplyBumpFee(20*(i+1));
889 }
890
891 selection.RecalculateWaste(min_viable_change, change_cost, change_fee);
892 CAmount expected_waste = fee_diff * -2 + /*bump_fees=*/60 + /*excess = 100 - bump_fees*/40;
893 BOOST_CHECK_EQUAL(expected_waste, selection.GetWaste());
894
895 selection.SetBumpFeeDiscount(30);
896 selection.RecalculateWaste(min_viable_change, change_cost, change_fee);
897 expected_waste = fee_diff * -2 + /*bump_fees=*/60 - /*group_discount=*/30 + /*excess = 100 - bump_fees + group_discount*/70;
898 BOOST_CHECK_EQUAL(expected_waste, selection.GetWaste());
899 }
900}
901
902BOOST_AUTO_TEST_CASE(effective_value_test)
903{
904 const int input_bytes = 148;
905 const CFeeRate feerate(1000);
906 const CAmount nValue = 10000;
907 const int nInput = 0;
908
910 tx.vout.resize(1);
911 tx.vout[nInput].nValue = nValue;
912
913 // standard case, pass feerate in constructor
914 COutput output1(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, input_bytes, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, feerate);
915 const CAmount expected_ev1 = 9852; // 10000 - 148
916 BOOST_CHECK_EQUAL(output1.GetEffectiveValue(), expected_ev1);
917
918 // input bytes unknown (input_bytes = -1), pass feerate in constructor
919 COutput output2(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, /*input_bytes=*/ -1, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, feerate);
920 BOOST_CHECK_EQUAL(output2.GetEffectiveValue(), nValue); // The effective value should be equal to the absolute value if input_bytes is -1
921
922 // negative effective value, pass feerate in constructor
923 COutput output3(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, input_bytes, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, CFeeRate(100000));
924 const CAmount expected_ev3 = -4800; // 10000 - 14800
925 BOOST_CHECK_EQUAL(output3.GetEffectiveValue(), expected_ev3);
926
927 // standard case, pass fees in constructor
928 const CAmount fees = 148;
929 COutput output4(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, input_bytes, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, fees);
930 BOOST_CHECK_EQUAL(output4.GetEffectiveValue(), expected_ev1);
931
932 // input bytes unknown (input_bytes = -1), pass fees in constructor
933 COutput output5(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, /*input_bytes=*/ -1, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, /*fees=*/ 0);
934 BOOST_CHECK_EQUAL(output5.GetEffectiveValue(), nValue); // The effective value should be equal to the absolute value if input_bytes is -1
935}
936
938 const CoinSelectionParams& cs_params,
940 int max_selection_weight,
941 std::function<CoinsResult(CWallet&)> coin_setup)
942{
943 std::unique_ptr<CWallet> wallet = NewWallet(m_node);
944 CoinEligibilityFilter filter(0, 0, 0); // accept all coins without ancestors
945 Groups group = GroupOutputs(*wallet, coin_setup(*wallet), cs_params, {{filter}})[filter].all_groups;
946 return CoinGrinder(group.positive_group, target, cs_params.m_min_change_target, max_selection_weight);
947}
948
949BOOST_AUTO_TEST_CASE(coin_grinder_tests)
950{
951 // Test Coin Grinder:
952 // 1) Insufficient funds, select all provided coins and fail.
953 // 2) Exceeded max weight, coin selection always surpasses the max allowed weight.
954 // 3) Select coins without surpassing the max weight (some coins surpasses the max allowed weight, some others not)
955 // 4) Test that two less valuable UTXOs with a combined lower weight are preferred over a more valuable heavier UTXO
956 // 5) Test finding a solution in a UTXO pool with mixed weights
957 // 6) Test that the lightest solution among many clones is found
958 // 7) Test that lots of tiny UTXOs can be skipped if they are too heavy while there are enough funds in lookahead
959
961 CoinSelectionParams dummy_params{ // Only used to provide the 'avoid_partial' flag.
962 rand,
963 /*change_output_size=*/34,
964 /*change_spend_size=*/68,
965 /*min_change_target=*/CENT,
966 /*effective_feerate=*/CFeeRate(5000),
967 /*long_term_feerate=*/CFeeRate(2000),
968 /*discard_feerate=*/CFeeRate(1000),
969 /*tx_noinputs_size=*/10 + 34, // static header size + output size
970 /*avoid_partial=*/false,
971 };
972
973 {
974 // #########################################################
975 // 1) Insufficient funds, select all provided coins and fail
976 // #########################################################
977 CAmount target = 49.5L * COIN;
978 int max_selection_weight = 10'000; // high enough to not fail for this reason.
979 const auto& res = CoinGrinder(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
980 CoinsResult available_coins;
981 for (int j = 0; j < 10; ++j) {
982 add_coin(available_coins, wallet, CAmount(1 * COIN));
983 add_coin(available_coins, wallet, CAmount(2 * COIN));
984 }
985 return available_coins;
986 });
987 BOOST_CHECK(!res);
988 BOOST_CHECK(util::ErrorString(res).empty()); // empty means "insufficient funds"
989 }
990
991 {
992 // ###########################
993 // 2) Test max weight exceeded
994 // ###########################
995 CAmount target = 29.5L * COIN;
996 int max_selection_weight = 3000;
997 const auto& res = CoinGrinder(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
998 CoinsResult available_coins;
999 for (int j = 0; j < 10; ++j) {
1000 add_coin(available_coins, wallet, CAmount(1 * COIN), CFeeRate(5000), 144, false, 0, true);
1001 add_coin(available_coins, wallet, CAmount(2 * COIN), CFeeRate(5000), 144, false, 0, true);
1002 }
1003 return available_coins;
1004 });
1005 BOOST_CHECK(!res);
1006 BOOST_CHECK(util::ErrorString(res).original.find("The inputs size exceeds the maximum weight") != std::string::npos);
1007 }
1008
1009 {
1010 // ###############################################################################################################
1011 // 3) Test that the lowest-weight solution is found when some combinations would exceed the allowed weight
1012 // ################################################################################################################
1013 CAmount target = 25.33L * COIN;
1014 int max_selection_weight = 10'000; // WU
1015 const auto& res = CoinGrinder(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
1016 CoinsResult available_coins;
1017 for (int j = 0; j < 60; ++j) { // 60 UTXO --> 19,8 BTC total --> 60 × 272 WU = 16320 WU
1018 add_coin(available_coins, wallet, CAmount(0.33 * COIN), CFeeRate(5000), 144, false, 0, true);
1019 }
1020 for (int i = 0; i < 10; i++) { // 10 UTXO --> 20 BTC total --> 10 × 272 WU = 2720 WU
1021 add_coin(available_coins, wallet, CAmount(2 * COIN), CFeeRate(5000), 144, false, 0, true);
1022 }
1023 return available_coins;
1024 });
1025 SelectionResult expected_result(CAmount(0), SelectionAlgorithm::CG);
1026 for (int i = 0; i < 10; ++i) {
1027 add_coin(2 * COIN, i, expected_result);
1028 }
1029 for (int j = 0; j < 17; ++j) {
1030 add_coin(0.33 * COIN, j + 10, expected_result);
1031 }
1032 BOOST_CHECK(EquivalentResult(expected_result, *res));
1033 // Demonstrate how following improvements reduce iteration count and catch any regressions in the future.
1034 size_t expected_attempts = 37;
1035 BOOST_CHECK_MESSAGE(res->GetSelectionsEvaluated() == expected_attempts, strprintf("Expected %i attempts, but got %i", expected_attempts, res->GetSelectionsEvaluated()));
1036 }
1037
1038 {
1039 // #################################################################################################################
1040 // 4) Test that two less valuable UTXOs with a combined lower weight are preferred over a more valuable heavier UTXO
1041 // #################################################################################################################
1042 CAmount target = 1.9L * COIN;
1043 int max_selection_weight = 400'000; // WU
1044 const auto& res = CoinGrinder(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
1045 CoinsResult available_coins;
1046 add_coin(available_coins, wallet, CAmount(2 * COIN), CFeeRate(5000), 144, false, 0, true, 148);
1047 add_coin(available_coins, wallet, CAmount(1 * COIN), CFeeRate(5000), 144, false, 0, true, 68);
1048 add_coin(available_coins, wallet, CAmount(1 * COIN), CFeeRate(5000), 144, false, 0, true, 68);
1049 return available_coins;
1050 });
1051 SelectionResult expected_result(CAmount(0), SelectionAlgorithm::CG);
1052 add_coin(1 * COIN, 1, expected_result);
1053 add_coin(1 * COIN, 2, expected_result);
1054 BOOST_CHECK(EquivalentResult(expected_result, *res));
1055 // Demonstrate how following improvements reduce iteration count and catch any regressions in the future.
1056 size_t expected_attempts = 3;
1057 BOOST_CHECK_MESSAGE(res->GetSelectionsEvaluated() == expected_attempts, strprintf("Expected %i attempts, but got %i", expected_attempts, res->GetSelectionsEvaluated()));
1058 }
1059
1060 {
1061 // ###############################################################################################################
1062 // 5) Test finding a solution in a UTXO pool with mixed weights
1063 // ################################################################################################################
1064 CAmount target = 30L * COIN;
1065 int max_selection_weight = 400'000; // WU
1066 const auto& res = CoinGrinder(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
1067 CoinsResult available_coins;
1068 for (int j = 0; j < 5; ++j) {
1069 // Add heavy coins {3, 6, 9, 12, 15}
1070 add_coin(available_coins, wallet, CAmount((3 + 3 * j) * COIN), CFeeRate(5000), 144, false, 0, true, 350);
1071 // Add medium coins {2, 5, 8, 11, 14}
1072 add_coin(available_coins, wallet, CAmount((2 + 3 * j) * COIN), CFeeRate(5000), 144, false, 0, true, 250);
1073 // Add light coins {1, 4, 7, 10, 13}
1074 add_coin(available_coins, wallet, CAmount((1 + 3 * j) * COIN), CFeeRate(5000), 144, false, 0, true, 150);
1075 }
1076 return available_coins;
1077 });
1078 BOOST_CHECK(res);
1079 SelectionResult expected_result(CAmount(0), SelectionAlgorithm::CG);
1080 add_coin(14 * COIN, 1, expected_result);
1081 add_coin(13 * COIN, 2, expected_result);
1082 add_coin(4 * COIN, 3, expected_result);
1083 BOOST_CHECK(EquivalentResult(expected_result, *res));
1084 // Demonstrate how following improvements reduce iteration count and catch any regressions in the future.
1085 size_t expected_attempts = 92;
1086 BOOST_CHECK_MESSAGE(res->GetSelectionsEvaluated() == expected_attempts, strprintf("Expected %i attempts, but got %i", expected_attempts, res->GetSelectionsEvaluated()));
1087 }
1088
1089 {
1090 // #################################################################################################################
1091 // 6) Test that the lightest solution among many clones is found
1092 // #################################################################################################################
1093 CAmount target = 9.9L * COIN;
1094 int max_selection_weight = 400'000; // WU
1095 const auto& res = CoinGrinder(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
1096 CoinsResult available_coins;
1097 // Expected Result: 4 + 3 + 2 + 1 = 10 BTC at 400 vB
1098 add_coin(available_coins, wallet, CAmount(4 * COIN), CFeeRate(5000), 144, false, 0, true, 100);
1099 add_coin(available_coins, wallet, CAmount(3 * COIN), CFeeRate(5000), 144, false, 0, true, 100);
1100 add_coin(available_coins, wallet, CAmount(2 * COIN), CFeeRate(5000), 144, false, 0, true, 100);
1101 add_coin(available_coins, wallet, CAmount(1 * COIN), CFeeRate(5000), 144, false, 0, true, 100);
1102 // Distracting clones:
1103 for (int j = 0; j < 100; ++j) {
1104 add_coin(available_coins, wallet, CAmount(8 * COIN), CFeeRate(5000), 144, false, 0, true, 1000);
1105 }
1106 for (int j = 0; j < 100; ++j) {
1107 add_coin(available_coins, wallet, CAmount(7 * COIN), CFeeRate(5000), 144, false, 0, true, 800);
1108 }
1109 for (int j = 0; j < 100; ++j) {
1110 add_coin(available_coins, wallet, CAmount(6 * COIN), CFeeRate(5000), 144, false, 0, true, 600);
1111 }
1112 for (int j = 0; j < 100; ++j) {
1113 add_coin(available_coins, wallet, CAmount(5 * COIN), CFeeRate(5000), 144, false, 0, true, 400);
1114 }
1115 return available_coins;
1116 });
1117 SelectionResult expected_result(CAmount(0), SelectionAlgorithm::CG);
1118 add_coin(4 * COIN, 0, expected_result);
1119 add_coin(3 * COIN, 0, expected_result);
1120 add_coin(2 * COIN, 0, expected_result);
1121 add_coin(1 * COIN, 0, expected_result);
1122 BOOST_CHECK(EquivalentResult(expected_result, *res));
1123 // Demonstrate how following improvements reduce iteration count and catch any regressions in the future.
1124 size_t expected_attempts = 38;
1125 BOOST_CHECK_MESSAGE(res->GetSelectionsEvaluated() == expected_attempts, strprintf("Expected %i attempts, but got %i", expected_attempts, res->GetSelectionsEvaluated()));
1126 }
1127
1128 {
1129 // #################################################################################################################
1130 // 7) Test that lots of tiny UTXOs can be skipped if they are too heavy while there are enough funds in lookahead
1131 // #################################################################################################################
1132 CAmount target = 1.9L * COIN;
1133 int max_selection_weight = 40000; // WU
1134 const auto& res = CoinGrinder(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
1135 CoinsResult available_coins;
1136 add_coin(available_coins, wallet, CAmount(1.8 * COIN), CFeeRate(5000), 144, false, 0, true, 2500);
1137 add_coin(available_coins, wallet, CAmount(1 * COIN), CFeeRate(5000), 144, false, 0, true, 1000);
1138 add_coin(available_coins, wallet, CAmount(1 * COIN), CFeeRate(5000), 144, false, 0, true, 1000);
1139 for (int j = 0; j < 100; ++j) {
1140 // make a 100 unique coins only differing by one sat
1141 add_coin(available_coins, wallet, CAmount(0.01 * COIN + j), CFeeRate(5000), 144, false, 0, true, 110);
1142 }
1143 return available_coins;
1144 });
1145 SelectionResult expected_result(CAmount(0), SelectionAlgorithm::CG);
1146 add_coin(1 * COIN, 1, expected_result);
1147 add_coin(1 * COIN, 2, expected_result);
1148 BOOST_CHECK(EquivalentResult(expected_result, *res));
1149 // Demonstrate how following improvements reduce iteration count and catch any regressions in the future.
1150 size_t expected_attempts = 7;
1151 BOOST_CHECK_MESSAGE(res->GetSelectionsEvaluated() == expected_attempts, strprintf("Expected %i attempts, but got %i", expected_attempts, res->GetSelectionsEvaluated()));
1152 }
1153}
1154
1156 const CoinSelectionParams& cs_params,
1158 int max_selection_weight,
1159 std::function<CoinsResult(CWallet&)> coin_setup)
1160{
1161 std::unique_ptr<CWallet> wallet = NewWallet(m_node);
1162 CoinEligibilityFilter filter(0, 0, 0); // accept all coins without ancestors
1163 Groups group = GroupOutputs(*wallet, coin_setup(*wallet), cs_params, {{filter}})[filter].all_groups;
1164 return SelectCoinsSRD(group.positive_group, target, cs_params.m_change_fee, cs_params.rng_fast, max_selection_weight);
1165}
1166
1168{
1169 // Test SRD:
1170 // 1) Insufficient funds, select all provided coins and fail.
1171 // 2) Exceeded max weight, coin selection always surpasses the max allowed weight.
1172 // 3) Select coins without surpassing the max weight (some coins surpasses the max allowed weight, some others not)
1173
1174 FastRandomContext rand;
1175 CoinSelectionParams dummy_params{ // Only used to provide the 'avoid_partial' flag.
1176 rand,
1177 /*change_output_size=*/34,
1178 /*change_spend_size=*/68,
1179 /*min_change_target=*/CENT,
1180 /*effective_feerate=*/CFeeRate(0),
1181 /*long_term_feerate=*/CFeeRate(0),
1182 /*discard_feerate=*/CFeeRate(0),
1183 /*tx_noinputs_size=*/10 + 34, // static header size + output size
1184 /*avoid_partial=*/false,
1185 };
1186
1187 {
1188 // #########################################################
1189 // 1) Insufficient funds, select all provided coins and fail
1190 // #########################################################
1191 CAmount target = 49.5L * COIN;
1192 int max_selection_weight = 10000; // high enough to not fail for this reason.
1193 const auto& res = SelectCoinsSRD(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
1194 CoinsResult available_coins;
1195 for (int j = 0; j < 10; ++j) {
1196 add_coin(available_coins, wallet, CAmount(1 * COIN));
1197 add_coin(available_coins, wallet, CAmount(2 * COIN));
1198 }
1199 return available_coins;
1200 });
1201 BOOST_CHECK(!res);
1202 BOOST_CHECK(util::ErrorString(res).empty()); // empty means "insufficient funds"
1203 }
1204
1205 {
1206 // ###########################
1207 // 2) Test max weight exceeded
1208 // ###########################
1209 CAmount target = 49.5L * COIN;
1210 int max_selection_weight = 3000;
1211 const auto& res = SelectCoinsSRD(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
1212 CoinsResult available_coins;
1213 for (int j = 0; j < 10; ++j) {
1214 /* 10 × 1 BTC + 10 × 2 BTC = 30 BTC. 20 × 272 WU = 5440 WU */
1215 add_coin(available_coins, wallet, CAmount(1 * COIN), CFeeRate(0), 144, false, 0, true);
1216 add_coin(available_coins, wallet, CAmount(2 * COIN), CFeeRate(0), 144, false, 0, true);
1217 }
1218 return available_coins;
1219 });
1220 BOOST_CHECK(!res);
1221 BOOST_CHECK(util::ErrorString(res).original.find("The inputs size exceeds the maximum weight") != std::string::npos);
1222 }
1223
1224 {
1225 // ################################################################################################################
1226 // 3) Test selection when some coins surpass the max allowed weight while others not. --> must find a good solution
1227 // ################################################################################################################
1228 CAmount target = 25.33L * COIN;
1229 int max_selection_weight = 10000; // WU
1230 const auto& res = SelectCoinsSRD(target, dummy_params, m_node, max_selection_weight, [&](CWallet& wallet) {
1231 CoinsResult available_coins;
1232 for (int j = 0; j < 60; ++j) { // 60 UTXO --> 19,8 BTC total --> 60 × 272 WU = 16320 WU
1233 add_coin(available_coins, wallet, CAmount(0.33 * COIN), CFeeRate(0), 144, false, 0, true);
1234 }
1235 for (int i = 0; i < 10; i++) { // 10 UTXO --> 20 BTC total --> 10 × 272 WU = 2720 WU
1236 add_coin(available_coins, wallet, CAmount(2 * COIN), CFeeRate(0), 144, false, 0, true);
1237 }
1238 return available_coins;
1239 });
1240 BOOST_CHECK(res);
1241 }
1242}
1243
1244static util::Result<SelectionResult> select_coins(const CAmount& target, const CoinSelectionParams& cs_params, const CCoinControl& cc, std::function<CoinsResult(CWallet&)> coin_setup, const node::NodeContext& m_node)
1245{
1246 std::unique_ptr<CWallet> wallet = NewWallet(m_node);
1247 auto available_coins = coin_setup(*wallet);
1248
1249 LOCK(wallet->cs_wallet);
1250 auto result = SelectCoins(*wallet, available_coins, /*pre_set_inputs=*/ {}, target, cc, cs_params);
1251 if (result) {
1252 const auto signedTxSize = 10 + 34 + 68 * result->GetInputSet().size(); // static header size + output size + inputs size (P2WPKH)
1253 BOOST_CHECK_LE(signedTxSize * WITNESS_SCALE_FACTOR, MAX_STANDARD_TX_WEIGHT);
1254
1255 BOOST_CHECK_GE(result->GetSelectedValue(), target);
1256 }
1257 return result;
1258}
1259
1260static bool has_coin(const CoinSet& set, CAmount amount)
1261{
1262 return std::any_of(set.begin(), set.end(), [&](const auto& coin) { return coin->GetEffectiveValue() == amount; });
1263}
1264
1265BOOST_AUTO_TEST_CASE(check_max_selection_weight)
1266{
1267 const CAmount target = 49.5L * COIN;
1268 CCoinControl cc;
1269
1270 FastRandomContext rand;
1271 CoinSelectionParams cs_params{
1272 rand,
1273 /*change_output_size=*/34,
1274 /*change_spend_size=*/68,
1275 /*min_change_target=*/CENT,
1276 /*effective_feerate=*/CFeeRate(0),
1277 /*long_term_feerate=*/CFeeRate(0),
1278 /*discard_feerate=*/CFeeRate(0),
1279 /*tx_noinputs_size=*/10 + 34, // static header size + output size
1280 /*avoid_partial=*/false,
1281 };
1282
1283 int max_weight = MAX_STANDARD_TX_WEIGHT - WITNESS_SCALE_FACTOR * (cs_params.tx_noinputs_size + cs_params.change_output_size);
1284 {
1285 // Scenario 1:
1286 // The actor starts with 1x 50.0 BTC and 1515x 0.033 BTC (~100.0 BTC total) unspent outputs
1287 // Then tries to spend 49.5 BTC
1288 // The 50.0 BTC output should be selected, because the transaction would otherwise be too large
1289
1290 // Perform selection
1291
1292 const auto result = select_coins(
1293 target, cs_params, cc, [&](CWallet& wallet) {
1294 CoinsResult available_coins;
1295 for (int j = 0; j < 1515; ++j) {
1296 add_coin(available_coins, wallet, CAmount(0.033 * COIN), CFeeRate(0), 144, false, 0, true);
1297 }
1298
1299 add_coin(available_coins, wallet, CAmount(50 * COIN), CFeeRate(0), 144, false, 0, true);
1300 return available_coins;
1301 },
1302 m_node);
1303
1304 BOOST_CHECK(result);
1305 // Verify that the 50 BTC UTXO was selected, and result is below max_weight
1306 BOOST_CHECK(has_coin(result->GetInputSet(), CAmount(50 * COIN)));
1307 BOOST_CHECK_LE(result->GetWeight(), max_weight);
1308 }
1309
1310 {
1311 // Scenario 2:
1312
1313 // The actor starts with 400x 0.0625 BTC and 2000x 0.025 BTC (75.0 BTC total) unspent outputs
1314 // Then tries to spend 49.5 BTC
1315 // A combination of coins should be selected, such that the created transaction is not too large
1316
1317 // Perform selection
1318 const auto result = select_coins(
1319 target, cs_params, cc, [&](CWallet& wallet) {
1320 CoinsResult available_coins;
1321 for (int j = 0; j < 400; ++j) {
1322 add_coin(available_coins, wallet, CAmount(0.0625 * COIN), CFeeRate(0), 144, false, 0, true);
1323 }
1324 for (int j = 0; j < 2000; ++j) {
1325 add_coin(available_coins, wallet, CAmount(0.025 * COIN), CFeeRate(0), 144, false, 0, true);
1326 }
1327 return available_coins;
1328 },
1329 m_node);
1330
1331 BOOST_CHECK(has_coin(result->GetInputSet(), CAmount(0.0625 * COIN)));
1332 BOOST_CHECK(has_coin(result->GetInputSet(), CAmount(0.025 * COIN)));
1333 BOOST_CHECK_LE(result->GetWeight(), max_weight);
1334 }
1335
1336 {
1337 // Scenario 3:
1338
1339 // The actor starts with 1515x 0.033 BTC (49.995 BTC total) unspent outputs
1340 // No results should be returned, because the transaction would be too large
1341
1342 // Perform selection
1343 const auto result = select_coins(
1344 target, cs_params, cc, [&](CWallet& wallet) {
1345 CoinsResult available_coins;
1346 for (int j = 0; j < 1515; ++j) {
1347 add_coin(available_coins, wallet, CAmount(0.033 * COIN), CFeeRate(0), 144, false, 0, true);
1348 }
1349 return available_coins;
1350 },
1351 m_node);
1352
1353 // No results
1354 // 1515 inputs * 68 bytes = 103,020 bytes
1355 // 103,020 bytes * 4 = 412,080 weight, which is above the MAX_STANDARD_TX_WEIGHT of 400,000
1356 BOOST_CHECK(!result);
1357 }
1358}
1359
1360BOOST_AUTO_TEST_CASE(SelectCoins_effective_value_test)
1361{
1362 // Test that the effective value is used to check whether preset inputs provide sufficient funds when subtract_fee_outputs is not used.
1363 // This test creates a coin whose value is higher than the target but whose effective value is lower than the target.
1364 // The coin is selected using coin control, with m_allow_other_inputs = false. SelectCoins should fail due to insufficient funds.
1365
1366 std::unique_ptr<CWallet> wallet = NewWallet(m_node);
1367
1368 CoinsResult available_coins;
1369 {
1370 std::unique_ptr<CWallet> dummyWallet = NewWallet(m_node, /*wallet_name=*/"dummy");
1371 add_coin(available_coins, *dummyWallet, 100000); // 0.001 BTC
1372 }
1373
1374 CAmount target{99900}; // 0.000999 BTC
1375
1376 FastRandomContext rand;
1377 CoinSelectionParams cs_params{
1378 rand,
1379 /*change_output_size=*/34,
1380 /*change_spend_size=*/148,
1381 /*min_change_target=*/1000,
1382 /*effective_feerate=*/CFeeRate(3000),
1383 /*long_term_feerate=*/CFeeRate(1000),
1384 /*discard_feerate=*/CFeeRate(1000),
1385 /*tx_noinputs_size=*/0,
1386 /*avoid_partial=*/false,
1387 };
1388 CCoinControl cc;
1389 cc.m_allow_other_inputs = false;
1390 COutput output = available_coins.All().at(0);
1391 cc.SetInputWeight(output.outpoint, 148);
1392 cc.Select(output.outpoint).SetTxOut(output.txout);
1393
1394 LOCK(wallet->cs_wallet);
1395 const auto preset_inputs = *Assert(FetchSelectedInputs(*wallet, cc, cs_params));
1396 available_coins.Erase({available_coins.coins[OutputType::BECH32].begin()->outpoint});
1397
1398 const auto result = SelectCoins(*wallet, available_coins, preset_inputs, target, cc, cs_params);
1399 BOOST_CHECK(!result);
1400}
1401
1403{
1404 // Test case to verify CoinsResult object sanity.
1405 CoinsResult available_coins;
1406 {
1407 std::unique_ptr<CWallet> dummyWallet = NewWallet(m_node, /*wallet_name=*/"dummy");
1408
1409 // Add some coins to 'available_coins'
1410 for (int i=0; i<10; i++) {
1411 add_coin(available_coins, *dummyWallet, 1 * COIN);
1412 }
1413 }
1414
1415 {
1416 // First test case, check that 'CoinsResult::Erase' function works as expected.
1417 // By trying to erase two elements from the 'available_coins' object.
1418 std::unordered_set<COutPoint, SaltedOutpointHasher> outs_to_remove;
1419 const auto& coins = available_coins.All();
1420 for (int i = 0; i < 2; i++) {
1421 outs_to_remove.emplace(coins[i].outpoint);
1422 }
1423 available_coins.Erase(outs_to_remove);
1424
1425 // Check that the elements were actually removed.
1426 const auto& updated_coins = available_coins.All();
1427 for (const auto& out: outs_to_remove) {
1428 auto it = std::find_if(updated_coins.begin(), updated_coins.end(), [&out](const COutput &coin) {
1429 return coin.outpoint == out;
1430 });
1431 BOOST_CHECK(it == updated_coins.end());
1432 }
1433 // And verify that no extra element were removed
1434 BOOST_CHECK_EQUAL(available_coins.Size(), 8);
1435 }
1436}
1437
1439} // namespace wallet
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
int ret
node::NodeContext m_node
Definition: bitcoin-gui.cpp:42
#define Assert(val)
Identity function.
Definition: check.h:106
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:33
CAmount GetFee(uint32_t num_bytes) const
Return the fee in satoshis for the given vsize in vbytes.
Definition: feerate.cpp:23
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
Fast randomness source.
Definition: random.h:377
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
Definition: random.h:254
256-bit opaque blob.
Definition: uint256.h:196
Coin Control Features.
Definition: coincontrol.h:81
PreselectedInput & Select(const COutPoint &outpoint)
Lock-in the given output for spending.
Definition: coincontrol.cpp:40
bool m_allow_other_inputs
If true, the selection process can add extra unselected inputs from the wallet while requires all sel...
Definition: coincontrol.h:91
void SetInputWeight(const COutPoint &outpoint, int64_t weight)
Set an input's weight.
Definition: coincontrol.cpp:67
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:300
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:177
const Txid & GetHash() const LIFETIMEBOUND
Definition: transaction.h:351
CTransactionRef tx
Definition: transaction.h:258
int64_t GetTxTime() const
Definition: transaction.cpp:26
void SetTxOut(const CTxOut &txout)
Set the previous output for this input.
Definition: coincontrol.cpp:90
#define RANDOM_REPEATS
#define RUN_TESTS
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
BOOST_FIXTURE_TEST_SUITE(cuckoocache_tests, BasicTestingSetup)
Test Suite for CuckooCache.
BOOST_AUTO_TEST_SUITE_END()
uint64_t fee
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:93
static const CoinEligibilityFilter filter_standard(1, 6, 0)
FilteredOutputGroups GroupOutputs(const CWallet &wallet, const CoinsResult &coins, const CoinSelectionParams &coin_sel_params, const std::vector< SelectionFilter > &filters, std::vector< OutputGroup > &ret_discarded_groups)
Definition: spend.cpp:531
BOOST_FIXTURE_TEST_CASE(wallet_coinsresult_test, BasicTestingSetup)
util::Result< SelectionResult > SelectCoinsBnB(std::vector< OutputGroup > &utxo_pool, const CAmount &selection_target, const CAmount &cost_of_change, int max_selection_weight)
static std::unique_ptr< CWallet > NewWallet(const node::NodeContext &m_node, const std::string &wallet_name="")
util::Result< SelectionResult > CoinGrinder(std::vector< OutputGroup > &utxo_pool, const CAmount &selection_target, CAmount change_target, int max_selection_weight)
util::Result< PreSelectedInputs > FetchSelectedInputs(const CWallet &wallet, const CCoinControl &coin_control, const CoinSelectionParams &coin_selection_params)
Fetch and validate coin control selected inputs.
Definition: spend.cpp:267
std::vector< OutputGroup > & GroupCoins(const std::vector< COutput > &available_coins, bool subtract_fee_outputs=false)
std::vector< OutputGroup > & KnapsackGroupOutputs(const CoinsResult &available_coins, CWallet &wallet, const CoinEligibilityFilter &filter)
util::Result< SelectionResult > KnapsackSolver(std::vector< OutputGroup > &groups, const CAmount &nTargetValue, CAmount change_target, FastRandomContext &rng, int max_selection_weight)
util::Result< SelectionResult > SelectCoins(const CWallet &wallet, CoinsResult &available_coins, const PreSelectedInputs &pre_set_inputs, const CAmount &nTargetValue, const CCoinControl &coin_control, const CoinSelectionParams &coin_selection_params)
Select all coins from coin_control, and if coin_control 'm_allow_other_inputs=true',...
Definition: spend.cpp:773
static const CoinEligibilityFilter filter_standard_extra(6, 6, 0)
static bool has_coin(const CoinSet &set, CAmount amount)
std::set< std::shared_ptr< COutput > > CoinSet
static bool EqualResult(const SelectionResult &a, const SelectionResult &b)
Check if this selection is equal to another one.
std::unique_ptr< WalletDatabase > CreateMockableWalletDatabase(MockableData records)
Definition: util.cpp:187
BOOST_AUTO_TEST_CASE(bnb_test)
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:74
static int nextLockTime
static const CoinEligibilityFilter filter_confirmed(1, 1, 0)
int CalculateMaximumSignedInputSize(const CTxOut &txout, const COutPoint outpoint, const SigningProvider *provider, bool can_grind_r, const CCoinControl *coin_control)
Definition: spend.cpp:90
static void add_coin(const CAmount &nValue, int nInput, SelectionResult &result)
static bool EquivalentResult(const SelectionResult &a, const SelectionResult &b)
Check if SelectionResult a is equivalent to SelectionResult b.
static void ApproximateBestSubset(FastRandomContext &insecure_rand, const std::vector< OutputGroup > &groups, const CAmount &nTotalLower, const CAmount &nTargetValue, std::vector< char > &vfBest, CAmount &nBest, int max_selection_weight, int iterations=1000)
Find a subset of the OutputGroups that is at least as large as, but as close as possible to,...
util::Result< SelectionResult > SelectCoinsSRD(const std::vector< OutputGroup > &utxo_pool, CAmount target_value, CAmount change_fee, FastRandomContext &rng, int max_selection_weight)
Select coins by Single Random Draw.
static util::Result< SelectionResult > select_coins(const CAmount &target, const CoinSelectionParams &cs_params, const CCoinControl &cc, std::function< CoinsResult(CWallet &)> coin_setup, const node::NodeContext &m_node)
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
#define BOOST_CHECK(expr)
Definition: object.cpp:17
static constexpr int32_t MAX_STANDARD_TX_WEIGHT
The maximum weight for transactions we're willing to relay/mine.
Definition: policy.h:34
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:424
static constexpr CAmount CENT
Definition: setup_common.h:47
Basic testing setup.
Definition: setup_common.h:64
A mutable version of CTransaction.
Definition: transaction.h:378
std::vector< CTxOut > vout
Definition: transaction.h:380
Txid GetHash() const
Compute the hash of this CMutableTransaction.
Definition: transaction.cpp:69
NodeContext struct containing references to chain state and connection state.
Definition: context.h:56
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:76
A UTXO under consideration for use in funding a new transaction.
Definition: coinselection.h:28
COutPoint outpoint
The outpoint identifying this UTXO.
Definition: coinselection.h:38
CTxOut txout
The output itself.
Definition: coinselection.h:41
CAmount GetEffectiveValue() const
Parameters for filtering which OutputGroups we may use in coin selection.
Parameters for one iteration of Coin Selection.
FastRandomContext & rng_fast
Randomness to use in the context of coin selection.
CAmount m_min_change_target
Mininmum change to target in Knapsack solver and CoinGrinder: select coins to cover the payment and a...
CAmount m_change_fee
Cost of creating the change output.
int change_output_size
Size of a change output in bytes, determined by the output type.
int tx_noinputs_size
Size of the transaction before coin selection, consisting of the header and recipient output(s),...
COutputs available for spending, stored by OutputType.
Definition: spend.h:40
void Add(OutputType type, const COutput &out)
Definition: spend.cpp:238
std::vector< COutput > All() const
Concatenate and return all COutputs as one vector.
Definition: spend.cpp:201
size_t Size() const
The following methods are provided so that CoinsResult can mimic a vector, i.e., methods can work wit...
Definition: spend.cpp:192
std::map< OutputType, std::vector< COutput > > coins
Definition: spend.h:41
void Erase(const std::unordered_set< COutPoint, SaltedOutpointHasher > &coins_to_remove)
Definition: spend.cpp:215
std::vector< OutputGroup > mixed_group
A group of UTXOs paid to the same output script.
Stores several 'Groups' whose were mapped by output type.
void Insert(const COutput &output, bool subtract_fee_outputs)
Definition: spend.h:164
const std::set< std::shared_ptr< COutput > > & GetInputSet() const
Get m_selected_inputs.
void AddInput(const OutputGroup &group)
State of transaction not confirmed or conflicting with a known block and not in the mempool.
Definition: transaction.h:58
#define LOCK(cs)
Definition: sync.h:257
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:301
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
assert(!tx.IsCoinBase())