Bitcoin ABC  0.22.13
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();
95  balance = Amount::zero();
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(), WalletLocation(),
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(), WalletLocation(),
354 
355  CoinSet setCoinsRet, setCoinsRet2;
356  Amount nValueRet;
357  bool bnb_used;
358 
359  LOCK(testWallet.cs_wallet);
360  testWallet.SetupLegacyScriptPubKeyMan();
361 
362  // test multiple times to allow for differences in the shuffle order
363  for (int i = 0; i < RUN_TESTS; i++) {
364  empty_wallet();
365 
366  // with an empty wallet we can't even pay one cent
367  BOOST_CHECK(!testWallet.SelectCoinsMinConf(
368  1 * CENT, filter_standard, GroupCoins(vCoins), setCoinsRet,
369  nValueRet, coin_selection_params, bnb_used));
370 
371  // add a new 1 cent coin
372  add_coin(testWallet, 1 * CENT, 4);
373 
374  // with a new 1 cent coin, we still can't find a mature 1 cent
375  BOOST_CHECK(!testWallet.SelectCoinsMinConf(
376  1 * CENT, filter_standard, GroupCoins(vCoins), setCoinsRet,
377  nValueRet, coin_selection_params, bnb_used));
378 
379  // but we can find a new 1 cent
380  BOOST_CHECK(testWallet.SelectCoinsMinConf(
381  1 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
382  nValueRet, coin_selection_params, bnb_used));
383  BOOST_CHECK_EQUAL(nValueRet, 1 * CENT);
384  // add a mature 2 cent coin
385  add_coin(testWallet, 2 * CENT);
386 
387  // we can't make 3 cents of mature coins
388  BOOST_CHECK(!testWallet.SelectCoinsMinConf(
389  3 * CENT, filter_standard, GroupCoins(vCoins), setCoinsRet,
390  nValueRet, coin_selection_params, bnb_used));
391 
392  // we can make 3 cents of new coins
393  BOOST_CHECK(testWallet.SelectCoinsMinConf(
394  3 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
395  nValueRet, coin_selection_params, bnb_used));
396  BOOST_CHECK_EQUAL(nValueRet, 3 * CENT);
397 
398  // add a mature 5 cent coin,
399  add_coin(testWallet, 5 * CENT);
400  // a new 10 cent coin sent from one of our own addresses
401  add_coin(testWallet, 10 * CENT, 3, true);
402  // and a mature 20 cent coin
403  add_coin(testWallet, 20 * CENT);
404 
405  // now we have new: 1+10=11 (of which 10 was self-sent), and mature:
406  // 2+5+20=27. total = 38
407 
408  // we can't make 38 cents only if we disallow new coins:
409  BOOST_CHECK(!testWallet.SelectCoinsMinConf(
410  38 * CENT, filter_standard, GroupCoins(vCoins), setCoinsRet,
411  nValueRet, coin_selection_params, bnb_used));
412  // we can't even make 37 cents if we don't allow new coins even if
413  // they're from us
414  BOOST_CHECK(!testWallet.SelectCoinsMinConf(
415  38 * CENT, filter_standard_extra, GroupCoins(vCoins), setCoinsRet,
416  nValueRet, coin_selection_params, bnb_used));
417  // but we can make 37 cents if we accept new coins from ourself
418  BOOST_CHECK(testWallet.SelectCoinsMinConf(
419  37 * CENT, filter_standard, GroupCoins(vCoins), setCoinsRet,
420  nValueRet, coin_selection_params, bnb_used));
421  BOOST_CHECK_EQUAL(nValueRet, 37 * CENT);
422  // and we can make 38 cents if we accept all new coins
423  BOOST_CHECK(testWallet.SelectCoinsMinConf(
424  38 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
425  nValueRet, coin_selection_params, bnb_used));
426  BOOST_CHECK_EQUAL(nValueRet, 38 * CENT);
427 
428  // try making 34 cents from 1,2,5,10,20 - we can't do it exactly
429  BOOST_CHECK(testWallet.SelectCoinsMinConf(
430  34 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
431  nValueRet, coin_selection_params, bnb_used));
432  // but 35 cents is closest
433  BOOST_CHECK_EQUAL(nValueRet, 35 * CENT);
434  // the best should be 20+10+5. it's incredibly unlikely the 1 or 2 got
435  // included (but possible)
436  BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
437 
438  // when we try making 7 cents, the smaller coins (1,2,5) are enough. We
439  // should see just 2+5
440  BOOST_CHECK(testWallet.SelectCoinsMinConf(
441  7 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
442  nValueRet, coin_selection_params, bnb_used));
443  BOOST_CHECK_EQUAL(nValueRet, 7 * CENT);
444  BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
445 
446  // when we try making 8 cents, the smaller coins (1,2,5) are exactly
447  // enough.
448  BOOST_CHECK(testWallet.SelectCoinsMinConf(
449  8 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
450  nValueRet, coin_selection_params, bnb_used));
451  BOOST_CHECK(nValueRet == 8 * CENT);
452  BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
453 
454  // when we try making 9 cents, no subset of smaller coins is enough, and
455  // we get the next bigger coin (10)
456  BOOST_CHECK(testWallet.SelectCoinsMinConf(
457  9 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
458  nValueRet, coin_selection_params, bnb_used));
459  BOOST_CHECK_EQUAL(nValueRet, 10 * CENT);
460  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
461 
462  // now clear out the wallet and start again to test choosing between
463  // subsets of smaller coins and the next biggest coin
464  empty_wallet();
465 
466  add_coin(testWallet, 6 * CENT);
467  add_coin(testWallet, 7 * CENT);
468  add_coin(testWallet, 8 * CENT);
469  add_coin(testWallet, 20 * CENT);
470  // now we have 6+7+8+20+30 = 71 cents total
471  add_coin(testWallet, 30 * CENT);
472 
473  // check that we have 71 and not 72
474  BOOST_CHECK(testWallet.SelectCoinsMinConf(
475  71 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
476  nValueRet, coin_selection_params, bnb_used));
477  BOOST_CHECK(!testWallet.SelectCoinsMinConf(
478  72 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
479  nValueRet, coin_selection_params, bnb_used));
480 
481  // now try making 16 cents. the best smaller coins can do is 6+7+8 =
482  // 21; not as good at the next biggest coin, 20
483  BOOST_CHECK(testWallet.SelectCoinsMinConf(
484  16 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
485  nValueRet, coin_selection_params, bnb_used));
486  // we should get 20 in one coin
487  BOOST_CHECK_EQUAL(nValueRet, 20 * CENT);
488  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
489 
490  // now we have 5+6+7+8+20+30 = 75 cents total
491  add_coin(testWallet, 5 * CENT);
492 
493  // now if we try making 16 cents again, the smaller coins can make 5+6+7
494  // = 18 cents, better than the next biggest coin, 20
495  BOOST_CHECK(testWallet.SelectCoinsMinConf(
496  16 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
497  nValueRet, coin_selection_params, bnb_used));
498  // we should get 18 in 3 coins
499  BOOST_CHECK_EQUAL(nValueRet, 18 * CENT);
500  BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
501 
502  // now we have 5+6+7+8+18+20+30
503  add_coin(testWallet, 18 * CENT);
504 
505  // and now if we try making 16 cents again, the smaller coins can make
506  // 5+6+7 = 18 cents, the same as the next biggest coin, 18
507  BOOST_CHECK(testWallet.SelectCoinsMinConf(
508  16 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
509  nValueRet, coin_selection_params, bnb_used));
510  // we should get 18 in 1 coin
511  BOOST_CHECK_EQUAL(nValueRet, 18 * CENT);
512  // because in the event of a tie, the biggest coin wins
513  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
514 
515  // now try making 11 cents. we should get 5+6
516  BOOST_CHECK(testWallet.SelectCoinsMinConf(
517  11 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
518  nValueRet, coin_selection_params, bnb_used));
519  BOOST_CHECK_EQUAL(nValueRet, 11 * CENT);
520  BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
521 
522  // check that the smallest bigger coin is used
523  add_coin(testWallet, 1 * COIN);
524  add_coin(testWallet, 2 * COIN);
525  add_coin(testWallet, 3 * COIN);
526  // now we have 5+6+7+8+18+20+30+100+200+300+400 = 1094 cents
527  add_coin(testWallet, 4 * COIN);
528  BOOST_CHECK(testWallet.SelectCoinsMinConf(
529  95 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
530  nValueRet, coin_selection_params, bnb_used));
531  // we should get 1 BCH in 1 coin
532  BOOST_CHECK_EQUAL(nValueRet, 1 * COIN);
533  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
534 
535  BOOST_CHECK(testWallet.SelectCoinsMinConf(
536  195 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
537  nValueRet, coin_selection_params, bnb_used));
538  // we should get 2 BCH in 1 coin
539  BOOST_CHECK_EQUAL(nValueRet, 2 * COIN);
540  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
541 
542  // empty the wallet and start again, now with fractions of a cent, to
543  // test small change avoidance
544 
545  empty_wallet();
546  add_coin(testWallet, 1 * MIN_CHANGE / 10);
547  add_coin(testWallet, 2 * MIN_CHANGE / 10);
548  add_coin(testWallet, 3 * MIN_CHANGE / 10);
549  add_coin(testWallet, 4 * MIN_CHANGE / 10);
550  add_coin(testWallet, 5 * MIN_CHANGE / 10);
551 
552  // try making 1 * MIN_CHANGE from the 1.5 * MIN_CHANGE
553  // we'll get change smaller than MIN_CHANGE whatever happens, so can
554  // expect MIN_CHANGE exactly
555  BOOST_CHECK(testWallet.SelectCoinsMinConf(
556  MIN_CHANGE, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
557  nValueRet, coin_selection_params, bnb_used));
558  BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE);
559 
560  // but if we add a bigger coin, small change is avoided
561  add_coin(testWallet, 1111 * MIN_CHANGE);
562 
563  // try making 1 from 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 1111 = 1112.5
564  BOOST_CHECK(testWallet.SelectCoinsMinConf(
565  1 * MIN_CHANGE, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
566  nValueRet, coin_selection_params, bnb_used));
567  // we should get the exact amount
568  BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE);
569 
570  // if we add more small coins:
571  add_coin(testWallet, 6 * MIN_CHANGE / 10);
572  add_coin(testWallet, 7 * MIN_CHANGE / 10);
573 
574  // and try again to make 1.0 * MIN_CHANGE
575  BOOST_CHECK(testWallet.SelectCoinsMinConf(
576  1 * MIN_CHANGE, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
577  nValueRet, coin_selection_params, bnb_used));
578  // we should get the exact amount
579  BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE);
580 
581  // run the 'mtgox' test (see
582  // http://blockexplorer.com/tx/29a3efd3ef04f9153d47a990bd7b048a4b2d213daaa5fb8ed670fb85f13bdbcf)
583  // they tried to consolidate 10 50k coins into one 500k coin, and ended
584  // up with 50k in change
585  empty_wallet();
586  for (int j = 0; j < 20; j++) {
587  add_coin(testWallet, 50000 * COIN);
588  }
589 
590  BOOST_CHECK(testWallet.SelectCoinsMinConf(
591  500000 * COIN, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
592  nValueRet, coin_selection_params, bnb_used));
593  // we should get the exact amount
594  BOOST_CHECK_EQUAL(nValueRet, 500000 * COIN);
595  // in ten coins
596  BOOST_CHECK_EQUAL(setCoinsRet.size(), 10U);
597 
598  // if there's not enough in the smaller coins to make at least 1 *
599  // MIN_CHANGE change (0.5+0.6+0.7 < 1.0+1.0), we need to try finding an
600  // exact subset anyway
601 
602  // sometimes it will fail, and so we use the next biggest coin:
603  empty_wallet();
604  add_coin(testWallet, 5 * MIN_CHANGE / 10);
605  add_coin(testWallet, 6 * MIN_CHANGE / 10);
606  add_coin(testWallet, 7 * MIN_CHANGE / 10);
607  add_coin(testWallet, 1111 * MIN_CHANGE);
608  BOOST_CHECK(testWallet.SelectCoinsMinConf(
609  1 * MIN_CHANGE, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
610  nValueRet, coin_selection_params, bnb_used));
611  // we get the bigger coin
612  BOOST_CHECK_EQUAL(nValueRet, 1111 * MIN_CHANGE);
613  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
614 
615  // but sometimes it's possible, and we use an exact subset (0.4 + 0.6 =
616  // 1.0)
617  empty_wallet();
618  add_coin(testWallet, 4 * MIN_CHANGE / 10);
619  add_coin(testWallet, 6 * MIN_CHANGE / 10);
620  add_coin(testWallet, 8 * MIN_CHANGE / 10);
621  add_coin(testWallet, 1111 * MIN_CHANGE);
622  BOOST_CHECK(testWallet.SelectCoinsMinConf(
623  MIN_CHANGE, filter_confirmed, GroupCoins(vCoins), setCoinsRet,
624  nValueRet, coin_selection_params, bnb_used));
625  // we should get the exact amount
626  BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE);
627  // in two coins 0.4+0.6
628  BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
629 
630  // test avoiding small change
631  empty_wallet();
632  add_coin(testWallet, 5 * MIN_CHANGE / 100);
633  add_coin(testWallet, 1 * MIN_CHANGE);
634  add_coin(testWallet, 100 * MIN_CHANGE);
635 
636  // trying to make 100.01 from these three coins
637  BOOST_CHECK(testWallet.SelectCoinsMinConf(
638  10001 * MIN_CHANGE / 100, filter_confirmed, GroupCoins(vCoins),
639  setCoinsRet, nValueRet, coin_selection_params, bnb_used));
640  // we should get all coins
641  BOOST_CHECK_EQUAL(nValueRet, 10105 * MIN_CHANGE / 100);
642  BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
643 
644  // but if we try to make 99.9, we should take the bigger of the two
645  // small coins to avoid small change
646  BOOST_CHECK(testWallet.SelectCoinsMinConf(
647  9990 * MIN_CHANGE / 100, filter_confirmed, GroupCoins(vCoins),
648  setCoinsRet, nValueRet, coin_selection_params, bnb_used));
649  BOOST_CHECK_EQUAL(nValueRet, 101 * MIN_CHANGE);
650  BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
651  }
652 
653  // test with many inputs
654  for (Amount amt = 1500 * SATOSHI; amt < COIN; amt = 10 * amt) {
655  empty_wallet();
656  // Create 676 inputs (= (old MAX_STANDARD_TX_SIZE == 100000) / 148
657  // bytes per input)
658  for (uint16_t j = 0; j < 676; j++) {
659  add_coin(testWallet, amt);
660  }
661 
662  // We only create the wallet once to save time, but we still run the
663  // coin selection RUN_TESTS times.
664  for (int i = 0; i < RUN_TESTS; i++) {
665  BOOST_CHECK(testWallet.SelectCoinsMinConf(
666  2000 * SATOSHI, filter_confirmed, GroupCoins(vCoins),
667  setCoinsRet, nValueRet, coin_selection_params, bnb_used));
668 
669  if (amt - 2000 * SATOSHI < MIN_CHANGE) {
670  // needs more than one input:
671  uint16_t returnSize = std::ceil(
672  (2000.0 + (MIN_CHANGE / SATOSHI)) / (amt / SATOSHI));
673  Amount returnValue = returnSize * amt;
674  BOOST_CHECK_EQUAL(nValueRet, returnValue);
675  BOOST_CHECK_EQUAL(setCoinsRet.size(), returnSize);
676  } else {
677  // one input is sufficient:
678  BOOST_CHECK_EQUAL(nValueRet, amt);
679  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
680  }
681  }
682  }
683 
684  // test randomness
685  {
686  empty_wallet();
687  for (int i2 = 0; i2 < 100; i2++) {
688  add_coin(testWallet, COIN);
689  }
690 
691  // Again, we only create the wallet once to save time, but we still run
692  // the coin selection RUN_TESTS times.
693  for (int i = 0; i < RUN_TESTS; i++) {
694  // picking 50 from 100 coins doesn't depend on the shuffle, but does
695  // depend on randomness in the stochastic approximation code
696  BOOST_CHECK(testWallet.SelectCoinsMinConf(
697  50 * COIN, filter_standard, GroupCoins(vCoins), setCoinsRet,
698  nValueRet, coin_selection_params, bnb_used));
699  BOOST_CHECK(testWallet.SelectCoinsMinConf(
700  50 * COIN, filter_standard, GroupCoins(vCoins), setCoinsRet2,
701  nValueRet, coin_selection_params, bnb_used));
702  BOOST_CHECK(!equal_sets(setCoinsRet, setCoinsRet2));
703 
704  int fails = 0;
705  for (int j = 0; j < RANDOM_REPEATS; j++) {
706  // selecting 1 from 100 identical coins depends on the shuffle;
707  // this test will fail 1% of the time run the test
708  // RANDOM_REPEATS times and only complain if all of them fail
709  BOOST_CHECK(testWallet.SelectCoinsMinConf(
710  COIN, filter_standard, GroupCoins(vCoins), setCoinsRet,
711  nValueRet, coin_selection_params, bnb_used));
712  BOOST_CHECK(testWallet.SelectCoinsMinConf(
713  COIN, filter_standard, GroupCoins(vCoins), setCoinsRet2,
714  nValueRet, coin_selection_params, bnb_used));
715  if (equal_sets(setCoinsRet, setCoinsRet2)) {
716  fails++;
717  }
718  }
719  BOOST_CHECK_NE(fails, RANDOM_REPEATS);
720  }
721 
722  // add 75 cents in small change. not enough to make 90 cents, then
723  // try making 90 cents. there are multiple competing "smallest
724  // bigger" coins, one of which should be picked at random
725  add_coin(testWallet, 5 * CENT);
726  add_coin(testWallet, 10 * CENT);
727  add_coin(testWallet, 15 * CENT);
728  add_coin(testWallet, 20 * CENT);
729  add_coin(testWallet, 25 * CENT);
730 
731  for (int i = 0; i < RUN_TESTS; i++) {
732  int fails = 0;
733  for (int j = 0; j < RANDOM_REPEATS; j++) {
734  // selecting 1 from 100 identical coins depends on the shuffle;
735  // this test will fail 1% of the time run the test
736  // RANDOM_REPEATS times and only complain if all of them fail
737  BOOST_CHECK(testWallet.SelectCoinsMinConf(
738  90 * CENT, filter_standard, GroupCoins(vCoins), setCoinsRet,
739  nValueRet, coin_selection_params, bnb_used));
740  BOOST_CHECK(testWallet.SelectCoinsMinConf(
741  90 * CENT, filter_standard, GroupCoins(vCoins),
742  setCoinsRet2, nValueRet, coin_selection_params, bnb_used));
743  if (equal_sets(setCoinsRet, setCoinsRet2)) {
744  fails++;
745  }
746  }
747  BOOST_CHECK_NE(fails, RANDOM_REPEATS);
748  }
749  }
750 
751  empty_wallet();
752 }
753 
755  CoinSet setCoinsRet;
756  Amount nValueRet;
757  bool bnb_used;
758 
759  LOCK(m_wallet.cs_wallet);
760  m_wallet.SetupLegacyScriptPubKeyMan();
761 
762  empty_wallet();
763 
764  // Test vValue sort order
765  for (int i = 0; i < 1000; i++) {
766  add_coin(m_wallet, 1000 * COIN);
767  }
768  add_coin(m_wallet, 3 * COIN);
769 
770  BOOST_CHECK(m_wallet.SelectCoinsMinConf(
771  1003 * COIN, filter_standard, GroupCoins(vCoins), setCoinsRet,
772  nValueRet, coin_selection_params, bnb_used));
773  BOOST_CHECK_EQUAL(nValueRet, 1003 * COIN);
774  BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
775 
776  empty_wallet();
777 }
778 
779 // Tests that with the ideal conditions, the coin selector will always be able
780 // to find a solution that can pay the target value
781 BOOST_AUTO_TEST_CASE(SelectCoins_test) {
782  auto testChain = interfaces::MakeChain(testNode, Params());
783  CWallet testWallet(testChain.get(), WalletLocation(),
785  testWallet.SetupLegacyScriptPubKeyMan();
786 
787  // Random generator stuff
788  std::default_random_engine generator;
789  std::exponential_distribution<double> distribution(100);
790  FastRandomContext rand;
791 
792  // Run this test 100 times
793  for (int i = 0; i < 100; ++i) {
794  empty_wallet();
795 
796  // Make a wallet with 1000 exponentially distributed random inputs
797  for (int j = 0; j < 1000; ++j) {
798  add_coin(testWallet,
799  int64_t(10000000 * distribution(generator)) * SATOSHI);
800  }
801 
802  // Generate a random fee rate in the range of 100 - 400
803  CFeeRate rate(int64_t(rand.randrange(300) + 100) * SATOSHI);
804 
805  // Generate a random target value between 1000 and wallet balance
806  Amount target =
807  int64_t(rand.randrange(balance / SATOSHI - 1000) + 1000) * SATOSHI;
808 
809  // Perform selection
810  CoinSelectionParams coin_selection_params_knapsack(
811  false, 34, 148, CFeeRate(Amount::zero()), 0);
812  CoinSelectionParams coin_selection_params_bnb(
813  true, 34, 148, CFeeRate(Amount::zero()), 0);
814  CoinSet out_set;
815  Amount out_value = Amount::zero();
816  bool bnb_used = false;
817  BOOST_CHECK(testWallet.SelectCoinsMinConf(
818  target, filter_standard, GroupCoins(vCoins), out_set,
819  out_value, coin_selection_params_bnb, bnb_used) ||
820  testWallet.SelectCoinsMinConf(
821  target, filter_standard, GroupCoins(vCoins), out_set,
822  out_value, coin_selection_params_knapsack, bnb_used));
823  BOOST_CHECK_GE(out_value, target);
824  }
825 }
826 
static std::unique_ptr< BerkeleyDatabase > CreateDummy()
Return object for accessing dummy database with no read/write capabilities.
Definition: bdb.h:135
void SetupLegacyScriptPubKeyMan()
Make a LegacyScriptPubKeyMan and set it for all types, internal, and external.
Definition: wallet.cpp:4848
static std::unique_ptr< BerkeleyDatabase > CreateMock()
Return object for accessing temporary in-memory database.
Definition: bdb.h:142
std::shared_ptr< CWallet > m_wallet
Definition: wallet.cpp:464
bool m_is_cache_empty
This flag is true if all m_amounts caches are empty.
Definition: wallet.h:358
static constexpr Amount zero()
Definition: amount.h:35
static bool equal_sets(CoinSet a, CoinSet b)
static void add_coin(const Amount nValue, int nInput, std::vector< CInputCoin > &set)
CoinSelectionParams coin_selection_params(false, 0, 0, CFeeRate(Amount::zero()), 0)
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:337
Definition: amount.h:17
CoinEligibilityFilter filter_standard(1, 6, 0)
static constexpr Amount SATOSHI
Definition: amount.h:151
static NodeContext testNode
std::vector< CTxOut > vout
Definition: transaction.h:298
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)
BOOST_AUTO_TEST_CASE(bnb_search_test)
#define RANDOM_REPEATS
Coin Control Features.
Definition: coincontrol.h:19
void Set(isminefilter filter, Amount value)
Definition: ismine.h:39
std::set< CInputCoin > CoinSet
std::vector< CTxIn > vin
Definition: transaction.h:297
static void empty_wallet()
NodeContext struct containing references to chain state and connection state.
Definition: context.h:35
static constexpr Amount COIN
Definition: amount.h:153
#define LOCK(cs)
Definition: sync.h:230
Fast randomness source.
Definition: random.h:113
void Select(const COutPoint &output)
Definition: coincontrol.h:56
bool fAllowOtherInputs
If false, allows unselected inputs, but requires all selected inputs be used.
Definition: coincontrol.h:28
bool m_subtract_fee_outputs
Indicate that we are subtracting the fee from outputs.
Definition: wallet.h:661
#define RUN_TESTS
std::vector< OutputGroup > & GroupCoins(const std::vector< CInputCoin > &coins)
CoinEligibilityFilter filter_confirmed(1, 1, 0)
CWalletTx * AddToWallet(CTransactionRef tx, const CWalletTx::Confirmation &confirm, const UpdateWalletTxFn &update_wtx=nullptr, bool fFlushOnClose=true)
Definition: wallet.cpp:857
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:246
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:22
static void ApproximateBestSubset(const std::vector< OutputGroup > &groups, const Amount &nTotalLower, const Amount &nTargetValue, std::vector< char > &vfBest, Amount &nBest, int iterations=1000)
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:280
static Amount balance
CachableAmount m_amounts[AMOUNTTYPE_ENUM_ELEMENTS]
Definition: wallet.h:351
#define BOOST_FIXTURE_TEST_SUITE(a, b)
Definition: object.cpp:14
Testing setup and teardown for wallet.
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
const CChainParams & Params()
Return the currently selected parameters.
CoinEligibilityFilter filter_standard_extra(6, 6, 0)
A mutable version of CTransaction.
Definition: transaction.h:295
#define BOOST_AUTO_TEST_SUITE_END()
Definition: object.cpp:16
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:679
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
static std::vector< COutput > vCoins
The WalletLocation class provides wallet information.
Definition: walletutil.h:80
static constexpr Amount MIN_CHANGE
target minimum change amount
Definition: coinselection.h:13
CFeeRate effective_fee
Definition: wallet.h:658
bool error(const char *fmt, const Args &... args)
Definition: system.h:47
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:188
boost::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:87
static Amount make_hard_case(int utxos, std::vector< CInputCoin > &utxo_pool)
bool GetNewDestination(const OutputType type, const std::string label, CTxDestination &dest, std::string &error)
Definition: wallet.cpp:3626
#define BOOST_CHECK(expr)
Definition: object.cpp:17
std::unique_ptr< Chain > MakeChain(NodeContext &node, const CChainParams &params)
Return implementation of Chain interface.
Definition: chain.cpp:448