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