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