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