Bitcoin Core  21.99.0
P2P Digital Currency
coinselector_tests.cpp
Go to the documentation of this file.
1 // Copyright (c) 2017-2020 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 <amount.h>
6 #include <node/context.h>
8 #include <random.h>
9 #include <test/util/setup_common.h>
10 #include <wallet/coincontrol.h>
11 #include <wallet/coinselection.h>
13 #include <wallet/wallet.h>
14 
15 #include <boost/test/unit_test.hpp>
16 #include <random>
17 
19 
20 // how many times to run all the tests to have a chance to catch errors that only show up with particular random shuffles
21 #define RUN_TESTS 100
22 
23 // some tests fail 1% of the time due to bad luck.
24 // we repeat those tests this many times and only complain if all iterations of the test fail
25 #define RANDOM_REPEATS 5
26 
27 typedef std::set<CInputCoin> CoinSet;
28 
29 static std::vector<COutput> vCoins;
33 static CAmount balance = 0;
34 
38 CoinSelectionParams coin_selection_params(/* use_bnb= */ false, /* change_output_size= */ 0,
39  /* change_spend_size= */ 0, /* effective_feerate= */ CFeeRate(0),
40  /* long_term_feerate= */ CFeeRate(0), /* discard_feerate= */ CFeeRate(0),
41  /* tx_no_inputs_size= */ 0, /* avoid_partial= */ false);
42 
43 static void add_coin(const CAmount& nValue, int nInput, std::vector<CInputCoin>& set)
44 {
46  tx.vout.resize(nInput + 1);
47  tx.vout[nInput].nValue = nValue;
48  set.emplace_back(MakeTransactionRef(tx), nInput);
49 }
50 
51 static void add_coin(const CAmount& nValue, int nInput, CoinSet& set)
52 {
54  tx.vout.resize(nInput + 1);
55  tx.vout[nInput].nValue = nValue;
56  set.emplace(MakeTransactionRef(tx), nInput);
57 }
58 
59 static void add_coin(CWallet& wallet, const CAmount& nValue, int nAge = 6*24, bool fIsFromMe = false, int nInput=0, bool spendable = false)
60 {
61  balance += nValue;
62  static int nextLockTime = 0;
64  tx.nLockTime = nextLockTime++; // so all transactions get different hashes
65  tx.vout.resize(nInput + 1);
66  tx.vout[nInput].nValue = nValue;
67  if (spendable) {
68  CTxDestination dest;
69  std::string error;
70  const bool destination_ok = wallet.GetNewDestination(OutputType::BECH32, "", dest, error);
71  assert(destination_ok);
72  tx.vout[nInput].scriptPubKey = GetScriptForDestination(dest);
73  }
74  if (fIsFromMe) {
75  // IsFromMe() returns (GetDebit() > 0), and GetDebit() is 0 if vin.empty(),
76  // so stop vin being empty, and cache a non-zero Debit to fake out IsFromMe()
77  tx.vin.resize(1);
78  }
79  CWalletTx* wtx = wallet.AddToWallet(MakeTransactionRef(std::move(tx)), /* confirm= */ {});
80  if (fIsFromMe)
81  {
83  wtx->m_is_cache_empty = false;
84  }
85  COutput output(wtx, nInput, nAge, true /* spendable */, true /* solvable */, true /* safe */);
86  vCoins.push_back(output);
87 }
88 static void add_coin(const CAmount& nValue, int nAge = 6*24, bool fIsFromMe = false, int nInput=0, bool spendable = false)
89 {
90  add_coin(testWallet, nValue, nAge, fIsFromMe, nInput, spendable);
91 }
92 
93 static void empty_wallet(void)
94 {
95  vCoins.clear();
96  balance = 0;
97 }
98 
99 static bool equal_sets(CoinSet a, CoinSet b)
100 {
101  std::pair<CoinSet::iterator, CoinSet::iterator> ret = mismatch(a.begin(), a.end(), b.begin());
102  return ret.first == a.end() && ret.second == b.end();
103 }
104 
105 static CAmount make_hard_case(int utxos, std::vector<CInputCoin>& utxo_pool)
106 {
107  utxo_pool.clear();
108  CAmount target = 0;
109  for (int i = 0; i < utxos; ++i) {
110  target += (CAmount)1 << (utxos+i);
111  add_coin((CAmount)1 << (utxos+i), 2*i, utxo_pool);
112  add_coin(((CAmount)1 << (utxos+i)) + ((CAmount)1 << (utxos-1-i)), 2*i + 1, utxo_pool);
113  }
114  return target;
115 }
116 
117 inline std::vector<OutputGroup>& GroupCoins(const std::vector<CInputCoin>& coins)
118 {
119  static std::vector<OutputGroup> static_groups;
120  static_groups.clear();
121  for (auto& coin : coins) {
122  static_groups.emplace_back();
123  static_groups.back().Insert(coin, 0, true, 0, 0, false);
124  }
125  return static_groups;
126 }
127 
128 inline std::vector<OutputGroup>& GroupCoins(const std::vector<COutput>& coins)
129 {
130  static std::vector<OutputGroup> static_groups;
131  static_groups.clear();
132  for (auto& coin : coins) {
133  static_groups.emplace_back();
134  static_groups.back().Insert(coin.GetInputCoin(), coin.nDepth, coin.tx->m_amounts[CWalletTx::DEBIT].m_cached[ISMINE_SPENDABLE] && coin.tx->m_amounts[CWalletTx::DEBIT].m_value[ISMINE_SPENDABLE] == 1 /* HACK: we can't figure out the is_me flag so we use the conditions defined above; perhaps set safe to false for !fIsFromMe in add_coin() */, 0, 0, false);
135  }
136  return static_groups;
137 }
138 
139 // Branch and bound coin selection tests
140 BOOST_AUTO_TEST_CASE(bnb_search_test)
141 {
142 
145 
146  // Setup
147  std::vector<CInputCoin> utxo_pool;
148  CoinSet selection;
149  CoinSet actual_selection;
150  CAmount value_ret = 0;
151  CAmount not_input_fees = 0;
152 
154  // Known Outcome tests //
156 
157  // Empty utxo pool
158  BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 1 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees));
159  selection.clear();
160 
161  // Add utxos
162  add_coin(1 * CENT, 1, utxo_pool);
163  add_coin(2 * CENT, 2, utxo_pool);
164  add_coin(3 * CENT, 3, utxo_pool);
165  add_coin(4 * CENT, 4, utxo_pool);
166 
167  // Select 1 Cent
168  add_coin(1 * CENT, 1, actual_selection);
169  BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), 1 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees));
170  BOOST_CHECK(equal_sets(selection, actual_selection));
171  BOOST_CHECK_EQUAL(value_ret, 1 * CENT);
172  actual_selection.clear();
173  selection.clear();
174 
175  // Select 2 Cent
176  add_coin(2 * CENT, 2, actual_selection);
177  BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), 2 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees));
178  BOOST_CHECK(equal_sets(selection, actual_selection));
179  BOOST_CHECK_EQUAL(value_ret, 2 * CENT);
180  actual_selection.clear();
181  selection.clear();
182 
183  // Select 5 Cent
184  add_coin(4 * CENT, 4, actual_selection);
185  add_coin(1 * CENT, 1, actual_selection);
186  BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), 5 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees));
187  BOOST_CHECK(equal_sets(selection, actual_selection));
188  BOOST_CHECK_EQUAL(value_ret, 5 * CENT);
189  actual_selection.clear();
190  selection.clear();
191 
192  // Select 11 Cent, not possible
193  BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 11 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees));
194  actual_selection.clear();
195  selection.clear();
196 
197  // Cost of change is greater than the difference between target value and utxo sum
198  add_coin(1 * CENT, 1, actual_selection);
199  BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), 0.9 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees));
200  BOOST_CHECK_EQUAL(value_ret, 1 * CENT);
201  BOOST_CHECK(equal_sets(selection, actual_selection));
202  actual_selection.clear();
203  selection.clear();
204 
205  // Cost of change is less than the difference between target value and utxo sum
206  BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 0.9 * CENT, 0, selection, value_ret, not_input_fees));
207  actual_selection.clear();
208  selection.clear();
209 
210  // Select 10 Cent
211  add_coin(5 * CENT, 5, utxo_pool);
212  add_coin(5 * CENT, 5, actual_selection);
213  add_coin(4 * CENT, 4, actual_selection);
214  add_coin(1 * CENT, 1, actual_selection);
215  BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), 10 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees));
216  BOOST_CHECK(equal_sets(selection, actual_selection));
217  BOOST_CHECK_EQUAL(value_ret, 10 * CENT);
218  actual_selection.clear();
219  selection.clear();
220 
221  // Negative effective value
222  // Select 10 Cent but have 1 Cent not be possible because too small
223  add_coin(5 * CENT, 5, actual_selection);
224  add_coin(3 * CENT, 3, actual_selection);
225  add_coin(2 * CENT, 2, actual_selection);
226  BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), 10 * CENT, 5000, selection, value_ret, not_input_fees));
227  BOOST_CHECK_EQUAL(value_ret, 10 * CENT);
228  // FIXME: this test is redundant with the above, because 1 Cent is selected, not "too small"
229  // BOOST_CHECK(equal_sets(selection, actual_selection));
230 
231  // Select 0.25 Cent, not possible
232  BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 0.25 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees));
233  actual_selection.clear();
234  selection.clear();
235 
236  // Iteration exhaustion test
237  CAmount target = make_hard_case(17, utxo_pool);
238  BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), target, 0, selection, value_ret, not_input_fees)); // Should exhaust
239  target = make_hard_case(14, utxo_pool);
240  BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), target, 0, selection, value_ret, not_input_fees)); // Should not exhaust
241 
242  // Test same value early bailout optimization
243  utxo_pool.clear();
244  add_coin(7 * CENT, 7, actual_selection);
245  add_coin(7 * CENT, 7, actual_selection);
246  add_coin(7 * CENT, 7, actual_selection);
247  add_coin(7 * CENT, 7, actual_selection);
248  add_coin(2 * CENT, 7, actual_selection);
249  add_coin(7 * CENT, 7, utxo_pool);
250  add_coin(7 * CENT, 7, utxo_pool);
251  add_coin(7 * CENT, 7, utxo_pool);
252  add_coin(7 * CENT, 7, utxo_pool);
253  add_coin(2 * CENT, 7, utxo_pool);
254  for (int i = 0; i < 50000; ++i) {
255  add_coin(5 * CENT, 7, utxo_pool);
256  }
257  BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), 30 * CENT, 5000, selection, value_ret, not_input_fees));
258  BOOST_CHECK_EQUAL(value_ret, 30 * CENT);
259  BOOST_CHECK(equal_sets(selection, actual_selection));
260 
262  // Behavior tests //
264  // Select 1 Cent with pool of only greater than 5 Cent
265  utxo_pool.clear();
266  for (int i = 5; i <= 20; ++i) {
267  add_coin(i * CENT, i, utxo_pool);
268  }
269  // Run 100 times, to make sure it is never finding a solution
270  for (int i = 0; i < 100; ++i) {
271  BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 1 * CENT, 2 * CENT, selection, value_ret, not_input_fees));
272  }
273 
274  // Make sure that effective value is working in SelectCoinsMinConf when BnB is used
275  CoinSelectionParams coin_selection_params_bnb(/* use_bnb= */ true, /* change_output_size= */ 0,
276  /* change_spend_size= */ 0, /* effective_feerate= */ CFeeRate(3000),
277  /* long_term_feerate= */ CFeeRate(1000), /* discard_feerate= */ CFeeRate(1000),
278  /* tx_no_inputs_size= */ 0, /* avoid_partial= */ false);
279  CoinSet setCoinsRet;
280  CAmount nValueRet;
281  bool bnb_used;
282  empty_wallet();
283  add_coin(1);
284  vCoins.at(0).nInputBytes = 40; // Make sure that it has a negative effective value. The next check should assert if this somehow got through. Otherwise it will fail
285  BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params_bnb, bnb_used));
286 
287  // Test fees subtracted from output:
288  empty_wallet();
289  add_coin(1 * CENT);
290  vCoins.at(0).nInputBytes = 40;
291  BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params_bnb, bnb_used));
292  coin_selection_params_bnb.m_subtract_fee_outputs = true;
293  BOOST_CHECK(testWallet.SelectCoinsMinConf( 1 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params_bnb, bnb_used));
294  BOOST_CHECK_EQUAL(nValueRet, 1 * CENT);
295 
296  // Make sure that can use BnB when there are preset inputs
297  empty_wallet();
298  {
299  std::unique_ptr<CWallet> wallet = std::make_unique<CWallet>(m_node.chain.get(), "", CreateMockWalletDatabase());
300  bool firstRun;
301  wallet->LoadWallet(firstRun);
302  wallet->SetupLegacyScriptPubKeyMan();
303  LOCK(wallet->cs_wallet);
304  add_coin(*wallet, 5 * CENT, 6 * 24, false, 0, true);
305  add_coin(*wallet, 3 * CENT, 6 * 24, false, 0, true);
306  add_coin(*wallet, 2 * CENT, 6 * 24, false, 0, true);
307  CCoinControl coin_control;
308  coin_control.fAllowOtherInputs = true;
309  coin_control.Select(COutPoint(vCoins.at(0).tx->GetHash(), vCoins.at(0).i));
310  coin_selection_params_bnb.m_effective_feerate = CFeeRate(0);
311  BOOST_CHECK(wallet->SelectCoins(vCoins, 10 * CENT, setCoinsRet, nValueRet, coin_control, coin_selection_params_bnb, bnb_used));
312  BOOST_CHECK(bnb_used);
313  BOOST_CHECK(coin_selection_params_bnb.use_bnb);
314  }
315 }
316 
317 BOOST_AUTO_TEST_CASE(knapsack_solver_test)
318 {
319  CoinSet setCoinsRet, setCoinsRet2;
320  CAmount nValueRet;
321  bool bnb_used;
322 
325 
326  // test multiple times to allow for differences in the shuffle order
327  for (int i = 0; i < RUN_TESTS; i++)
328  {
329  empty_wallet();
330 
331  // with an empty wallet we can't even pay one cent
332  BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
333 
334  add_coin(1*CENT, 4); // add a new 1 cent coin
335 
336  // with a new 1 cent coin, we still can't find a mature 1 cent
337  BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
338 
339  // but we can find a new 1 cent
340  BOOST_CHECK( testWallet.SelectCoinsMinConf( 1 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
341  BOOST_CHECK_EQUAL(nValueRet, 1 * CENT);
342 
343  add_coin(2*CENT); // add a mature 2 cent coin
344 
345  // we can't make 3 cents of mature coins
346  BOOST_CHECK(!testWallet.SelectCoinsMinConf( 3 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
347 
348  // we can make 3 cents of new coins
349  BOOST_CHECK( testWallet.SelectCoinsMinConf( 3 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
350  BOOST_CHECK_EQUAL(nValueRet, 3 * CENT);
351 
352  add_coin(5*CENT); // add a mature 5 cent coin,
353  add_coin(10*CENT, 3, true); // a new 10 cent coin sent from one of our own addresses
354  add_coin(20*CENT); // and a mature 20 cent coin
355 
356  // now we have new: 1+10=11 (of which 10 was self-sent), and mature: 2+5+20=27. total = 38
357 
358  // we can't make 38 cents only if we disallow new coins:
359  BOOST_CHECK(!testWallet.SelectCoinsMinConf(38 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
360  // we can't even make 37 cents if we don't allow new coins even if they're from us
361  BOOST_CHECK(!testWallet.SelectCoinsMinConf(38 * CENT, filter_standard_extra, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
362  // but we can make 37 cents if we accept new coins from ourself
363  BOOST_CHECK( testWallet.SelectCoinsMinConf(37 * CENT, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
364  BOOST_CHECK_EQUAL(nValueRet, 37 * CENT);
365  // and we can make 38 cents if we accept all new coins
366  BOOST_CHECK( testWallet.SelectCoinsMinConf(38 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
367  BOOST_CHECK_EQUAL(nValueRet, 38 * CENT);
368 
369  // try making 34 cents from 1,2,5,10,20 - we can't do it exactly
370  BOOST_CHECK( testWallet.SelectCoinsMinConf(34 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
371  BOOST_CHECK_EQUAL(nValueRet, 35 * CENT); // but 35 cents is closest
372  BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U); // the best should be 20+10+5. it's incredibly unlikely the 1 or 2 got included (but possible)
373 
374  // when we try making 7 cents, the smaller coins (1,2,5) are enough. We should see just 2+5
375  BOOST_CHECK( testWallet.SelectCoinsMinConf( 7 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
376  BOOST_CHECK_EQUAL(nValueRet, 7 * CENT);
377  BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
378 
379  // when we try making 8 cents, the smaller coins (1,2,5) are exactly enough.
380  BOOST_CHECK( testWallet.SelectCoinsMinConf( 8 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
381  BOOST_CHECK(nValueRet == 8 * CENT);
382  BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
383 
384  // when we try making 9 cents, no subset of smaller coins is enough, and we get the next bigger coin (10)
385  BOOST_CHECK( testWallet.SelectCoinsMinConf( 9 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
386  BOOST_CHECK_EQUAL(nValueRet, 10 * CENT);
387  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
388 
389  // now clear out the wallet and start again to test choosing between subsets of smaller coins and the next biggest coin
390  empty_wallet();
391 
392  add_coin( 6*CENT);
393  add_coin( 7*CENT);
394  add_coin( 8*CENT);
395  add_coin(20*CENT);
396  add_coin(30*CENT); // now we have 6+7+8+20+30 = 71 cents total
397 
398  // check that we have 71 and not 72
399  BOOST_CHECK( testWallet.SelectCoinsMinConf(71 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
400  BOOST_CHECK(!testWallet.SelectCoinsMinConf(72 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
401 
402  // 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
403  BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
404  BOOST_CHECK_EQUAL(nValueRet, 20 * CENT); // we should get 20 in one coin
405  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
406 
407  add_coin( 5*CENT); // now we have 5+6+7+8+20+30 = 75 cents total
408 
409  // 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
410  BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
411  BOOST_CHECK_EQUAL(nValueRet, 18 * CENT); // we should get 18 in 3 coins
412  BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
413 
414  add_coin( 18*CENT); // now we have 5+6+7+8+18+20+30
415 
416  // 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
417  BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
418  BOOST_CHECK_EQUAL(nValueRet, 18 * CENT); // we should get 18 in 1 coin
419  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); // because in the event of a tie, the biggest coin wins
420 
421  // now try making 11 cents. we should get 5+6
422  BOOST_CHECK( testWallet.SelectCoinsMinConf(11 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
423  BOOST_CHECK_EQUAL(nValueRet, 11 * CENT);
424  BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
425 
426  // check that the smallest bigger coin is used
427  add_coin( 1*COIN);
428  add_coin( 2*COIN);
429  add_coin( 3*COIN);
430  add_coin( 4*COIN); // now we have 5+6+7+8+18+20+30+100+200+300+400 = 1094 cents
431  BOOST_CHECK( testWallet.SelectCoinsMinConf(95 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
432  BOOST_CHECK_EQUAL(nValueRet, 1 * COIN); // we should get 1 BTC in 1 coin
433  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
434 
435  BOOST_CHECK( testWallet.SelectCoinsMinConf(195 * CENT, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
436  BOOST_CHECK_EQUAL(nValueRet, 2 * COIN); // we should get 2 BTC in 1 coin
437  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
438 
439  // empty the wallet and start again, now with fractions of a cent, to test small change avoidance
440 
441  empty_wallet();
442  add_coin(MIN_CHANGE * 1 / 10);
443  add_coin(MIN_CHANGE * 2 / 10);
444  add_coin(MIN_CHANGE * 3 / 10);
445  add_coin(MIN_CHANGE * 4 / 10);
446  add_coin(MIN_CHANGE * 5 / 10);
447 
448  // try making 1 * MIN_CHANGE from the 1.5 * MIN_CHANGE
449  // we'll get change smaller than MIN_CHANGE whatever happens, so can expect MIN_CHANGE exactly
451  BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE);
452 
453  // but if we add a bigger coin, small change is avoided
454  add_coin(1111*MIN_CHANGE);
455 
456  // try making 1 from 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 1111 = 1112.5
458  BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE); // we should get the exact amount
459 
460  // if we add more small coins:
461  add_coin(MIN_CHANGE * 6 / 10);
462  add_coin(MIN_CHANGE * 7 / 10);
463 
464  // and try again to make 1.0 * MIN_CHANGE
466  BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE); // we should get the exact amount
467 
468  // run the 'mtgox' test (see https://blockexplorer.com/tx/29a3efd3ef04f9153d47a990bd7b048a4b2d213daaa5fb8ed670fb85f13bdbcf)
469  // they tried to consolidate 10 50k coins into one 500k coin, and ended up with 50k in change
470  empty_wallet();
471  for (int j = 0; j < 20; j++)
472  add_coin(50000 * COIN);
473 
474  BOOST_CHECK( testWallet.SelectCoinsMinConf(500000 * COIN, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
475  BOOST_CHECK_EQUAL(nValueRet, 500000 * COIN); // we should get the exact amount
476  BOOST_CHECK_EQUAL(setCoinsRet.size(), 10U); // in ten coins
477 
478  // if there's not enough in the smaller coins to make at least 1 * MIN_CHANGE change (0.5+0.6+0.7 < 1.0+1.0),
479  // we need to try finding an exact subset anyway
480 
481  // sometimes it will fail, and so we use the next biggest coin:
482  empty_wallet();
483  add_coin(MIN_CHANGE * 5 / 10);
484  add_coin(MIN_CHANGE * 6 / 10);
485  add_coin(MIN_CHANGE * 7 / 10);
486  add_coin(1111 * MIN_CHANGE);
488  BOOST_CHECK_EQUAL(nValueRet, 1111 * MIN_CHANGE); // we get the bigger coin
489  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
490 
491  // but sometimes it's possible, and we use an exact subset (0.4 + 0.6 = 1.0)
492  empty_wallet();
493  add_coin(MIN_CHANGE * 4 / 10);
494  add_coin(MIN_CHANGE * 6 / 10);
495  add_coin(MIN_CHANGE * 8 / 10);
496  add_coin(1111 * MIN_CHANGE);
498  BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE); // we should get the exact amount
499  BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); // in two coins 0.4+0.6
500 
501  // test avoiding small change
502  empty_wallet();
503  add_coin(MIN_CHANGE * 5 / 100);
504  add_coin(MIN_CHANGE * 1);
505  add_coin(MIN_CHANGE * 100);
506 
507  // trying to make 100.01 from these three coins
508  BOOST_CHECK(testWallet.SelectCoinsMinConf(MIN_CHANGE * 10001 / 100, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
509  BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE * 10105 / 100); // we should get all coins
510  BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
511 
512  // but if we try to make 99.9, we should take the bigger of the two small coins to avoid small change
513  BOOST_CHECK(testWallet.SelectCoinsMinConf(MIN_CHANGE * 9990 / 100, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
514  BOOST_CHECK_EQUAL(nValueRet, 101 * MIN_CHANGE);
515  BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
516  }
517 
518  // test with many inputs
519  for (CAmount amt=1500; amt < COIN; amt*=10) {
520  empty_wallet();
521  // Create 676 inputs (= (old MAX_STANDARD_TX_SIZE == 100000) / 148 bytes per input)
522  for (uint16_t j = 0; j < 676; j++)
523  add_coin(amt);
524 
525  // We only create the wallet once to save time, but we still run the coin selection RUN_TESTS times.
526  for (int i = 0; i < RUN_TESTS; i++) {
527  BOOST_CHECK(testWallet.SelectCoinsMinConf(2000, filter_confirmed, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
528 
529  if (amt - 2000 < MIN_CHANGE) {
530  // needs more than one input:
531  uint16_t returnSize = std::ceil((2000.0 + MIN_CHANGE)/amt);
532  CAmount returnValue = amt * returnSize;
533  BOOST_CHECK_EQUAL(nValueRet, returnValue);
534  BOOST_CHECK_EQUAL(setCoinsRet.size(), returnSize);
535  } else {
536  // one input is sufficient:
537  BOOST_CHECK_EQUAL(nValueRet, amt);
538  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
539  }
540  }
541  }
542 
543  // test randomness
544  {
545  empty_wallet();
546  for (int i2 = 0; i2 < 100; i2++)
547  add_coin(COIN);
548 
549  // Again, we only create the wallet once to save time, but we still run the coin selection RUN_TESTS times.
550  for (int i = 0; i < RUN_TESTS; i++) {
551  // picking 50 from 100 coins doesn't depend on the shuffle,
552  // but does depend on randomness in the stochastic approximation code
553  BOOST_CHECK(testWallet.SelectCoinsMinConf(50 * COIN, filter_standard, vCoins, setCoinsRet , nValueRet, coin_selection_params, bnb_used));
554  BOOST_CHECK(testWallet.SelectCoinsMinConf(50 * COIN, filter_standard, vCoins, setCoinsRet2, nValueRet, coin_selection_params, bnb_used));
555  BOOST_CHECK(!equal_sets(setCoinsRet, setCoinsRet2));
556 
557  int fails = 0;
558  for (int j = 0; j < RANDOM_REPEATS; j++)
559  {
560  // selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of the time
561  // run the test RANDOM_REPEATS times and only complain if all of them fail
564  if (equal_sets(setCoinsRet, setCoinsRet2))
565  fails++;
566  }
567  BOOST_CHECK_NE(fails, RANDOM_REPEATS);
568  }
569 
570  // add 75 cents in small change. not enough to make 90 cents,
571  // then try making 90 cents. there are multiple competing "smallest bigger" coins,
572  // one of which should be picked at random
573  add_coin(5 * CENT);
574  add_coin(10 * CENT);
575  add_coin(15 * CENT);
576  add_coin(20 * CENT);
577  add_coin(25 * CENT);
578 
579  for (int i = 0; i < RUN_TESTS; i++) {
580  int fails = 0;
581  for (int j = 0; j < RANDOM_REPEATS; j++)
582  {
583  // selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of the time
584  // run the test RANDOM_REPEATS times and only complain if all of them fail
585  BOOST_CHECK(testWallet.SelectCoinsMinConf(90*CENT, filter_standard, vCoins, setCoinsRet , nValueRet, coin_selection_params, bnb_used));
586  BOOST_CHECK(testWallet.SelectCoinsMinConf(90*CENT, filter_standard, vCoins, setCoinsRet2, nValueRet, coin_selection_params, bnb_used));
587  if (equal_sets(setCoinsRet, setCoinsRet2))
588  fails++;
589  }
590  BOOST_CHECK_NE(fails, RANDOM_REPEATS);
591  }
592  }
593 
594  empty_wallet();
595 }
596 
598 {
599  CoinSet setCoinsRet;
600  CAmount nValueRet;
601  bool bnb_used;
602 
605 
606  empty_wallet();
607 
608  // Test vValue sort order
609  for (int i = 0; i < 1000; i++)
610  add_coin(1000 * COIN);
611  add_coin(3 * COIN);
612 
613  BOOST_CHECK(testWallet.SelectCoinsMinConf(1003 * COIN, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
614  BOOST_CHECK_EQUAL(nValueRet, 1003 * COIN);
615  BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
616 
617  empty_wallet();
618 }
619 
620 // Tests that with the ideal conditions, the coin selector will always be able to find a solution that can pay the target value
621 BOOST_AUTO_TEST_CASE(SelectCoins_test)
622 {
624 
625  // Random generator stuff
626  std::default_random_engine generator;
627  std::exponential_distribution<double> distribution (100);
628  FastRandomContext rand;
629 
630  // Run this test 100 times
631  for (int i = 0; i < 100; ++i)
632  {
633  empty_wallet();
634 
635  // Make a wallet with 1000 exponentially distributed random inputs
636  for (int j = 0; j < 1000; ++j)
637  {
638  add_coin((CAmount)(distribution(generator)*10000000));
639  }
640 
641  // Generate a random fee rate in the range of 100 - 400
642  CFeeRate rate(rand.randrange(300) + 100);
643 
644  // Generate a random target value between 1000 and wallet balance
645  CAmount target = rand.randrange(balance - 1000) + 1000;
646 
647  // Perform selection
648  CoinSelectionParams coin_selection_params_knapsack(/* use_bnb= */ false, /* change_output_size= */ 34,
649  /* change_spend_size= */ 148, /* effective_feerate= */ CFeeRate(0),
650  /* long_term_feerate= */ CFeeRate(0), /* discard_feerate= */ CFeeRate(0),
651  /* tx_no_inputs_size= */ 0, /* avoid_partial= */ false);
652  CoinSelectionParams coin_selection_params_bnb(/* use_bnb= */ true, /* change_output_size= */ 34,
653  /* change_spend_size= */ 148, /* effective_feerate= */ CFeeRate(0),
654  /* long_term_feerate= */ CFeeRate(0), /* discard_feerate= */ CFeeRate(0),
655  /* tx_no_inputs_size= */ 0, /* avoid_partial= */ false);
656  CoinSet out_set;
657  CAmount out_value = 0;
658  bool bnb_used = false;
659  BOOST_CHECK(testWallet.SelectCoinsMinConf(target, filter_standard, vCoins, out_set, out_value, coin_selection_params_bnb, bnb_used) ||
660  testWallet.SelectCoinsMinConf(target, filter_standard, vCoins, out_set, out_value, coin_selection_params_knapsack, bnb_used));
661  BOOST_CHECK_GE(out_value, target);
662  }
663 }
664 
CCoinControl::Select
void Select(const COutPoint &output)
Definition: coincontrol.h:72
CCoinControl::fAllowOtherInputs
bool fAllowOtherInputs
If false, allows unselected inputs, but requires all selected inputs be used.
Definition: coincontrol.h:33
CMutableTransaction::vin
std::vector< CTxIn > vin
Definition: transaction.h:346
CoinSet
std::set< CInputCoin > CoinSet
Definition: coinselector_tests.cpp:27
GroupCoins
std::vector< OutputGroup > & GroupCoins(const std::vector< CInputCoin > &coins)
Definition: coinselector_tests.cpp:117
MIN_CHANGE
static constexpr CAmount MIN_CHANGE
target minimum change amount
Definition: coinselection.h:14
CreateDummyWalletDatabase
std::unique_ptr< WalletDatabase > CreateDummyWalletDatabase()
Return object for accessing dummy database with no read/write capabilities.
Definition: walletdb.cpp:1088
wallet.h
CoinSelectionParams::use_bnb
bool use_bnb
Definition: wallet.h:609
transaction.h
GetScriptForDestination
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:307
vCoins
static std::vector< COutput > vCoins
Definition: coinselector_tests.cpp:29
interfaces::MakeChain
std::unique_ptr< Chain > MakeChain(NodeContext &node)
Return implementation of Chain interface.
Definition: interfaces.cpp:719
RANDOM_REPEATS
#define RANDOM_REPEATS
Definition: coinselector_tests.cpp:25
CCoinControl
Coin Control Features.
Definition: coincontrol.h:23
MakeTransactionRef
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:387
wallet
Definition: interfaces.cpp:47
CWalletTx::m_is_cache_empty
bool m_is_cache_empty
This flag is true if all m_amounts caches are empty.
Definition: wallet.h:342
CoinEligibilityFilter
Definition: coinselection.h:59
BOOST_FIXTURE_TEST_SUITE
#define BOOST_FIXTURE_TEST_SUITE(a, b)
Definition: object.cpp:14
SelectCoinsBnB
bool SelectCoinsBnB(std::vector< OutputGroup > &utxo_pool, const CAmount &target_value, const CAmount &cost_of_change, std::set< CInputCoin > &out_set, CAmount &value_ret, CAmount not_input_fees)
Definition: coinselection.cpp:66
context.h
empty_wallet
static void empty_wallet(void)
Definition: coinselector_tests.cpp:93
NodeContext::chain
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:47
CFeeRate
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:29
ApproximateBestSubset
static void ApproximateBestSubset(const std::vector< OutputGroup > &groups, const CAmount &nTotalLower, const CAmount &nTargetValue, std::vector< char > &vfBest, CAmount &nBest, int iterations=1000)
Definition: coinselection.cpp:174
balance
static CAmount balance
Definition: coinselector_tests.cpp:33
make_hard_case
static CAmount make_hard_case(int utxos, std::vector< CInputCoin > &utxo_pool)
Definition: coinselector_tests.cpp:105
testNode
static NodeContext testNode
Definition: coinselector_tests.cpp:30
random.h
CMutableTransaction::nLockTime
uint32_t nLockTime
Definition: transaction.h:349
coinselection.h
equal_sets
static bool equal_sets(CoinSet a, CoinSet b)
Definition: coinselector_tests.cpp:99
filter_standard_extra
CoinEligibilityFilter filter_standard_extra(6, 6, 0)
BOOST_AUTO_TEST_CASE
BOOST_AUTO_TEST_CASE(bnb_search_test)
Definition: coinselector_tests.cpp:140
testChain
static auto testChain
Definition: coinselector_tests.cpp:31
CachableAmount::Set
void Set(isminefilter filter, CAmount value)
Definition: ismine.h:63
CoinSelectionParams
Definition: wallet.h:607
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
testWallet
static CWallet testWallet(testChain.get(), "", CreateDummyWalletDatabase())
m_node
NodeContext & m_node
Definition: interfaces.cpp:712
add_coin
static void add_coin(const CAmount &nValue, int nInput, std::vector< CInputCoin > &set)
Definition: coinselector_tests.cpp:43
WalletTestingSetup
Testing setup and teardown for wallet.
Definition: wallet_test_fixture.h:20
wallet_test_fixture.h
CWallet::SetupLegacyScriptPubKeyMan
void SetupLegacyScriptPubKeyMan()
Make a LegacyScriptPubKeyMan and set it for all types, internal, and external.
Definition: wallet.cpp:4467
CoinSelectionParams::m_subtract_fee_outputs
bool m_subtract_fee_outputs
Indicate that we are subtracting the fee from outputs.
Definition: wallet.h:617
ISMINE_SPENDABLE
@ ISMINE_SPENDABLE
Definition: ismine.h:42
OutputType::BECH32
@ BECH32
CMutableTransaction::vout
std::vector< CTxOut > vout
Definition: transaction.h:347
RUN_TESTS
#define RUN_TESTS
Definition: coinselector_tests.cpp:21
CWallet::SelectCoinsMinConf
bool SelectCoinsMinConf(const CAmount &nTargetValue, const CoinEligibilityFilter &eligibility_filter, std::vector< COutput > coins, std::set< CInputCoin > &setCoinsRet, CAmount &nValueRet, const CoinSelectionParams &coin_selection_params, bool &bnb_used) const
Shuffle and select coins until nTargetValue is reached while avoiding small change; This method is st...
Definition: wallet.cpp:2395
LOCK
#define LOCK(cs)
Definition: sync.h:232
CreateMockWalletDatabase
std::unique_ptr< WalletDatabase > CreateMockWalletDatabase()
Return object for accessing temporary in-memory database.
Definition: walletdb.cpp:1094
CWallet
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:638
CWalletTx
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:273
FastRandomContext::randrange
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:190
CoinSelectionParams::m_effective_feerate
CFeeRate m_effective_feerate
Definition: wallet.h:612
CTxDestination
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:212
CWallet::cs_wallet
RecursiveMutex cs_wallet
Definition: wallet.h:746
COIN
static const CAmount COIN
Definition: amount.h:14
COutPoint
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
coin_selection_params
CoinSelectionParams coin_selection_params(false, 0, 0, CFeeRate(0), CFeeRate(0), CFeeRate(0), 0, false)
CWalletTx::DEBIT
@ DEBIT
Definition: wallet.h:333
CoinSet
std::set< CInputCoin > CoinSet
Definition: coin_selection.cpp:67
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:50
CWalletTx::m_amounts
CachableAmount m_amounts[AMOUNTTYPE_ENUM_ELEMENTS]
Definition: wallet.h:335
filter_standard
CoinEligibilityFilter filter_standard(1, 6, 0)
CMutableTransaction
A mutable version of CTransaction.
Definition: transaction.h:344
NodeContext
NodeContext struct containing references to chain state and connection state.
Definition: context.h:38
coincontrol.h
filter_confirmed
CoinEligibilityFilter filter_confirmed(1, 1, 0)
COutput
Definition: wallet.h:563
amount.h
assert
assert(std::addressof(::ChainstateActive().CoinsTip())==std::addressof(coins_cache))
FastRandomContext
Fast randomness source.
Definition: random.h:119
BOOST_CHECK
#define BOOST_CHECK(expr)
Definition: object.cpp:17
BOOST_AUTO_TEST_SUITE_END
#define BOOST_AUTO_TEST_SUITE_END()
Definition: object.cpp:16
BOOST_CHECK_EQUAL
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18