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