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