Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

wallet_tests.cpp
Go to the documentation of this file.
1 // Copyright (c) 2012-2015 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 
7 #include <iostream>
8 #include <memory>
9 #include <set>
10 #include <stdint.h>
11 #include <utility>
12 #include <vector>
13 
14 #include <consensus/validation.h>
15 #include <rpc/server.h>
16 #include <test/test_dash.h>
17 #include <validation.h>
18 #include <wallet/coincontrol.h>
20 
21 #include <boost/test/unit_test.hpp>
22 #include <univalue.h>
23 
24 extern UniValue importmulti(const JSONRPCRequest& request);
25 extern UniValue dumpwallet(const JSONRPCRequest& request);
26 extern UniValue importwallet(const JSONRPCRequest& request);
27 extern UniValue getnewaddress(const JSONRPCRequest& request);
28 
29 // how many times to run all the tests to have a chance to catch errors that only show up with particular random shuffles
30 #define RUN_TESTS 100
31 
32 // some tests fail 1% of the time due to bad luck.
33 // we repeat those tests this many times and only complain if all iterations of the test fail
34 #define RANDOM_REPEATS 5
35 
36 std::vector<std::unique_ptr<CWalletTx>> wtxn;
37 
38 typedef std::set<CInputCoin> CoinSet;
39 
41 
42 static const CWallet testWallet("dummy", WalletDatabase::CreateDummy());
43 static std::vector<COutput> vCoins;
44 
45 static void add_coin(const CAmount& nValue, int nAge = 6*24, bool fIsFromMe = false, int nInput=0)
46 {
47  static int nextLockTime = 0;
49  tx.nLockTime = nextLockTime++; // so all transactions get different hashes
50  tx.vout.resize(nInput+1);
51  tx.vout[nInput].nValue = nValue;
52  if (fIsFromMe) {
53  // IsFromMe() returns (GetDebit() > 0), and GetDebit() is 0 if vin.empty(),
54  // so stop vin being empty, and cache a non-zero Debit to fake out IsFromMe()
55  tx.vin.resize(1);
56  }
57  std::unique_ptr<CWalletTx> wtx(new CWalletTx(&testWallet, MakeTransactionRef(std::move(tx))));
58  if (fIsFromMe)
59  {
60  wtx->fDebitCached = true;
61  wtx->nDebitCached = 1;
62  }
63  COutput output(wtx.get(), nInput, nAge, true /* spendable */, true /* solvable */, true /* safe */);
64  vCoins.push_back(output);
65  wtxn.emplace_back(std::move(wtx));
66 }
67 
68 static void empty_wallet(void)
69 {
70  vCoins.clear();
71  wtxn.clear();
72 }
73 
74 static bool equal_sets(CoinSet a, CoinSet b)
75 {
76  std::pair<CoinSet::iterator, CoinSet::iterator> ret = mismatch(a.begin(), a.end(), b.begin());
77  return ret.first == a.end() && ret.second == b.end();
78 }
79 
80 BOOST_AUTO_TEST_CASE(coin_selection_tests)
81 {
82  CoinSet setCoinsRet, setCoinsRet2;
83  CAmount nValueRet;
84 
86 
87  // test multiple times to allow for differences in the shuffle order
88  for (int i = 0; i < RUN_TESTS; i++)
89  {
90  empty_wallet();
91 
92  // with an empty wallet we can't even pay one cent
93  BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet));
94 
95  add_coin(1*CENT, 4); // add a new 1 cent coin
96 
97  // with a new 1 cent coin, we still can't find a mature 1 cent
98  BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet));
99 
100  // but we can find a new 1 cent
101  BOOST_CHECK( testWallet.SelectCoinsMinConf( 1 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
102  BOOST_CHECK_EQUAL(nValueRet, 1 * CENT);
103 
104  add_coin(2*CENT); // add a mature 2 cent coin
105 
106  // we can't make 3 cents of mature coins
107  BOOST_CHECK(!testWallet.SelectCoinsMinConf( 3 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet));
108 
109  // we can make 3 cents of new coins
110  BOOST_CHECK( testWallet.SelectCoinsMinConf( 3 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
111  BOOST_CHECK_EQUAL(nValueRet, 3 * CENT);
112 
113  add_coin(5*CENT); // add a mature 5 cent coin,
114  add_coin(10*CENT, 3, true); // a new 10 cent coin sent from one of our own addresses
115  add_coin(20*CENT); // and a mature 20 cent coin
116 
117  // now we have new: 1+10=11 (of which 10 was self-sent), and mature: 2+5+20=27. total = 38
118 
119  // we can't make 38 cents only if we disallow new coins:
120  BOOST_CHECK(!testWallet.SelectCoinsMinConf(38 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet));
121  // we can't even make 37 cents if we don't allow new coins even if they're from us
122  BOOST_CHECK(!testWallet.SelectCoinsMinConf(38 * CENT, 6, 6, 0, vCoins, setCoinsRet, nValueRet));
123  // but we can make 37 cents if we accept new coins from ourself
124  BOOST_CHECK( testWallet.SelectCoinsMinConf(37 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet));
125  BOOST_CHECK_EQUAL(nValueRet, 37 * CENT);
126  // and we can make 38 cents if we accept all new coins
127  BOOST_CHECK( testWallet.SelectCoinsMinConf(38 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
128  BOOST_CHECK_EQUAL(nValueRet, 38 * CENT);
129 
130  // try making 34 cents from 1,2,5,10,20 - we can't do it exactly
131  BOOST_CHECK( testWallet.SelectCoinsMinConf(34 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
132  BOOST_CHECK_EQUAL(nValueRet, 35 * CENT); // but 35 cents is closest
133  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)
134 
135  // when we try making 7 cents, the smaller coins (1,2,5) are enough. We should see just 2+5
136  BOOST_CHECK( testWallet.SelectCoinsMinConf( 7 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
137  BOOST_CHECK_EQUAL(nValueRet, 7 * CENT);
138  BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
139 
140  // when we try making 8 cents, the smaller coins (1,2,5) are exactly enough.
141  BOOST_CHECK( testWallet.SelectCoinsMinConf( 8 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
142  BOOST_CHECK(nValueRet == 8 * CENT);
143  BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
144 
145  // when we try making 9 cents, no subset of smaller coins is enough, and we get the next bigger coin (10)
146  BOOST_CHECK( testWallet.SelectCoinsMinConf( 9 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
147  BOOST_CHECK_EQUAL(nValueRet, 10 * CENT);
148  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
149 
150  // now clear out the wallet and start again to test choosing between subsets of smaller coins and the next biggest coin
151  empty_wallet();
152 
153  add_coin( 6*CENT);
154  add_coin( 7*CENT);
155  add_coin( 8*CENT);
156  add_coin(20*CENT);
157  add_coin(30*CENT); // now we have 6+7+8+20+30 = 71 cents total
158 
159  // check that we have 71 and not 72
160  BOOST_CHECK( testWallet.SelectCoinsMinConf(71 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
161  BOOST_CHECK(!testWallet.SelectCoinsMinConf(72 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
162 
163  // 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
164  BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
165  BOOST_CHECK_EQUAL(nValueRet, 20 * CENT); // we should get 20 in one coin
166  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
167 
168  add_coin( 5*CENT); // now we have 5+6+7+8+20+30 = 75 cents total
169 
170  // 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
171  BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
172  BOOST_CHECK_EQUAL(nValueRet, 18 * CENT); // we should get 18 in 3 coins
173  BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
174 
175  add_coin( 18*CENT); // now we have 5+6+7+8+18+20+30
176 
177  // 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
178  BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
179  BOOST_CHECK_EQUAL(nValueRet, 18 * CENT); // we should get 18 in 1 coin
180  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); // because in the event of a tie, the biggest coin wins
181 
182  // now try making 11 cents. we should get 5+6
183  BOOST_CHECK( testWallet.SelectCoinsMinConf(11 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
184  BOOST_CHECK_EQUAL(nValueRet, 11 * CENT);
185  BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
186 
187  // check that the smallest bigger coin is used
188  add_coin( 1*COIN);
189  add_coin( 2*COIN);
190  add_coin( 3*COIN);
191  add_coin( 4*COIN); // now we have 5+6+7+8+18+20+30+100+200+300+400 = 1094 cents
192  BOOST_CHECK( testWallet.SelectCoinsMinConf(95 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
193  BOOST_CHECK_EQUAL(nValueRet, 1 * COIN); // we should get 1 BTC in 1 coin
194  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
195 
196  BOOST_CHECK( testWallet.SelectCoinsMinConf(195 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
197  BOOST_CHECK_EQUAL(nValueRet, 2 * COIN); // we should get 2 BTC in 1 coin
198  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
199 
200  // empty the wallet and start again, now with fractions of a cent, to test small change avoidance
201 
202  empty_wallet();
203  add_coin(MIN_CHANGE * 1 / 10);
204  add_coin(MIN_CHANGE * 2 / 10);
205  add_coin(MIN_CHANGE * 3 / 10);
206  add_coin(MIN_CHANGE * 4 / 10);
207  add_coin(MIN_CHANGE * 5 / 10);
208 
209  // try making 1 * MIN_CHANGE from the 1.5 * MIN_CHANGE
210  // we'll get change smaller than MIN_CHANGE whatever happens, so can expect MIN_CHANGE exactly
211  BOOST_CHECK( testWallet.SelectCoinsMinConf(MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
212  BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE);
213 
214  // but if we add a bigger coin, small change is avoided
215  add_coin(1111*MIN_CHANGE);
216 
217  // try making 1 from 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 1111 = 1112.5
218  BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
219  BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE); // we should get the exact amount
220 
221  // if we add more small coins:
222  add_coin(MIN_CHANGE * 6 / 10);
223  add_coin(MIN_CHANGE * 7 / 10);
224 
225  // and try again to make 1.0 * MIN_CHANGE
226  BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
227  BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE); // we should get the exact amount
228 
229  // run the 'mtgox' test (see http://blockexplorer.com/tx/29a3efd3ef04f9153d47a990bd7b048a4b2d213daaa5fb8ed670fb85f13bdbcf)
230  // they tried to consolidate 10 50k coins into one 500k coin, and ended up with 50k in change
231  empty_wallet();
232  for (int j = 0; j < 20; j++)
233  add_coin(50000 * COIN);
234 
235  BOOST_CHECK( testWallet.SelectCoinsMinConf(500000 * COIN, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
236  BOOST_CHECK_EQUAL(nValueRet, 500000 * COIN); // we should get the exact amount
237  BOOST_CHECK_EQUAL(setCoinsRet.size(), 10U); // in ten coins
238 
239  // 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),
240  // we need to try finding an exact subset anyway
241 
242  // sometimes it will fail, and so we use the next biggest coin:
243  empty_wallet();
244  add_coin(MIN_CHANGE * 5 / 10);
245  add_coin(MIN_CHANGE * 6 / 10);
246  add_coin(MIN_CHANGE * 7 / 10);
247  add_coin(1111 * MIN_CHANGE);
248  BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
249  BOOST_CHECK_EQUAL(nValueRet, 1111 * MIN_CHANGE); // we get the bigger coin
250  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
251 
252  // but sometimes it's possible, and we use an exact subset (0.4 + 0.6 = 1.0)
253  empty_wallet();
254  add_coin(MIN_CHANGE * 4 / 10);
255  add_coin(MIN_CHANGE * 6 / 10);
256  add_coin(MIN_CHANGE * 8 / 10);
257  add_coin(1111 * MIN_CHANGE);
258  BOOST_CHECK( testWallet.SelectCoinsMinConf(MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
259  BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE); // we should get the exact amount
260  BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); // in two coins 0.4+0.6
261 
262  // test avoiding small change
263  empty_wallet();
264  add_coin(MIN_CHANGE * 5 / 100);
265  add_coin(MIN_CHANGE * 1);
266  add_coin(MIN_CHANGE * 100);
267 
268  // trying to make 100.01 from these three coins
269  BOOST_CHECK(testWallet.SelectCoinsMinConf(MIN_CHANGE * 10001 / 100, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
270  BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE * 10105 / 100); // we should get all coins
271  BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
272 
273  // but if we try to make 99.9, we should take the bigger of the two small coins to avoid small change
274  BOOST_CHECK(testWallet.SelectCoinsMinConf(MIN_CHANGE * 9990 / 100, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
275  BOOST_CHECK_EQUAL(nValueRet, 101 * MIN_CHANGE);
276  BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
277 
278  // test with many inputs
279  for (CAmount amt=1500; amt < COIN; amt*=10) {
280  empty_wallet();
281  // Create 676 inputs (= MAX_STANDARD_TX_SIZE / 148 bytes per input)
282  for (uint16_t j = 0; j < 676; j++)
283  add_coin(amt);
284  BOOST_CHECK(testWallet.SelectCoinsMinConf(2000, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
285  if (amt - 2000 < MIN_CHANGE) {
286  // needs more than one input:
287  uint16_t returnSize = std::ceil((2000.0 + MIN_CHANGE)/amt);
288  CAmount returnValue = amt * returnSize;
289  BOOST_CHECK_EQUAL(nValueRet, returnValue);
290  BOOST_CHECK_EQUAL(setCoinsRet.size(), returnSize);
291  } else {
292  // one input is sufficient:
293  BOOST_CHECK_EQUAL(nValueRet, amt);
294  BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
295  }
296  }
297 
298  // test randomness
299  {
300  empty_wallet();
301  for (int i2 = 0; i2 < 100; i2++)
302  add_coin(COIN);
303 
304  // picking 50 from 100 coins doesn't depend on the shuffle,
305  // but does depend on randomness in the stochastic approximation code
306  BOOST_CHECK(testWallet.SelectCoinsMinConf(50 * COIN, 1, 6, 0, vCoins, setCoinsRet , nValueRet));
307  BOOST_CHECK(testWallet.SelectCoinsMinConf(50 * COIN, 1, 6, 0, vCoins, setCoinsRet2, nValueRet));
308  BOOST_CHECK(!equal_sets(setCoinsRet, setCoinsRet2));
309 
310  int fails = 0;
311  for (int j = 0; j < RANDOM_REPEATS; j++)
312  {
313  // selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of the time
314  // run the test RANDOM_REPEATS times and only complain if all of them fail
315  BOOST_CHECK(testWallet.SelectCoinsMinConf(COIN, 1, 6, 0, vCoins, setCoinsRet , nValueRet));
316  BOOST_CHECK(testWallet.SelectCoinsMinConf(COIN, 1, 6, 0, vCoins, setCoinsRet2, nValueRet));
317  if (equal_sets(setCoinsRet, setCoinsRet2))
318  fails++;
319  }
320  BOOST_CHECK_NE(fails, RANDOM_REPEATS);
321 
322  // add 75 cents in small change. not enough to make 90 cents,
323  // then try making 90 cents. there are multiple competing "smallest bigger" coins,
324  // one of which should be picked at random
325  add_coin(5 * CENT);
326  add_coin(10 * CENT);
327  add_coin(15 * CENT);
328  add_coin(20 * CENT);
329  add_coin(25 * CENT);
330 
331  fails = 0;
332  for (int j = 0; j < RANDOM_REPEATS; j++)
333  {
334  // selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of the time
335  // run the test RANDOM_REPEATS times and only complain if all of them fail
336  BOOST_CHECK(testWallet.SelectCoinsMinConf(90*CENT, 1, 6, 0, vCoins, setCoinsRet , nValueRet));
337  BOOST_CHECK(testWallet.SelectCoinsMinConf(90*CENT, 1, 6, 0, vCoins, setCoinsRet2, nValueRet));
338  if (equal_sets(setCoinsRet, setCoinsRet2))
339  fails++;
340  }
341  BOOST_CHECK_NE(fails, RANDOM_REPEATS);
342  }
343  }
344  empty_wallet();
345 }
346 
348 {
349  CoinSet setCoinsRet;
350  CAmount nValueRet;
351 
353 
354  empty_wallet();
355 
356  // Test vValue sort order
357  for (int i = 0; i < 1000; i++)
358  add_coin(1000 * COIN);
359  add_coin(3 * COIN);
360 
361  BOOST_CHECK(testWallet.SelectCoinsMinConf(1003 * COIN, 1, 6, 0, vCoins, setCoinsRet, nValueRet));
362  BOOST_CHECK_EQUAL(nValueRet, 1003 * COIN);
363  BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
364 
365  empty_wallet();
366 }
367 
368 static void AddKey(CWallet& wallet, const CKey& key)
369 {
370  LOCK(wallet.cs_wallet);
371  wallet.AddKeyPubKey(key, key.GetPubKey());
372 }
373 
374 BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup)
375 {
376  // Cap last block file size, and mine new block in a new block file.
377  CBlockIndex* const nullBlock = nullptr;
378  CBlockIndex* oldTip = chainActive.Tip();
380  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
381  CBlockIndex* newTip = chainActive.Tip();
382 
383  LOCK(cs_main);
384 
385  // Verify ScanForWalletTransactions picks up transactions in both the old
386  // and new block files.
387  {
388  CWallet wallet("dummy", WalletDatabase::CreateDummy());
389  AddKey(wallet, coinbaseKey);
390  WalletRescanReserver reserver(&wallet);
391  reserver.reserve();
392  BOOST_CHECK_EQUAL(nullBlock, wallet.ScanForWalletTransactions(oldTip, nullptr, reserver));
393  BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 1000 * COIN);
394  }
395 
396  // Prune the older block file.
398  UnlinkPrunedFiles({oldTip->GetBlockPos().nFile});
399 
400  // Verify ScanForWalletTransactions only picks transactions in the new block
401  // file.
402  {
403  CWallet wallet("dummy", WalletDatabase::CreateDummy());
404  AddKey(wallet, coinbaseKey);
405  WalletRescanReserver reserver(&wallet);
406  reserver.reserve();
407  BOOST_CHECK_EQUAL(oldTip, wallet.ScanForWalletTransactions(oldTip, nullptr, reserver));
408  BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 500 * COIN);
409  }
410 
411  // Verify importmulti RPC returns failure for a key whose creation time is
412  // before the missing block, and success for a key whose creation time is
413  // after.
414  {
415  CWallet wallet("dummy", WalletDatabase::CreateDummy());
416  AddWallet(&wallet);
417  UniValue keys;
418  keys.setArray();
419  UniValue key;
420  key.setObject();
421  key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey())));
422  key.pushKV("timestamp", 0);
423  key.pushKV("internal", UniValue(true));
424  keys.push_back(key);
425  key.clear();
426  key.setObject();
427  CKey futureKey;
428  futureKey.MakeNewKey(true);
429  key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(futureKey.GetPubKey())));
430  key.pushKV("timestamp", newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1);
431  key.pushKV("internal", UniValue(true));
432  keys.push_back(key);
433  JSONRPCRequest request;
434  request.params.setArray();
435  request.params.push_back(keys);
436 
437  UniValue response = importmulti(request);
438  BOOST_CHECK_EQUAL(response.write(),
439  strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":\"Rescan failed for key with creation "
440  "timestamp %d. There was an error reading a block from time %d, which is after or within %d "
441  "seconds of key creation, and could contain transactions pertaining to the key. As a result, "
442  "transactions and coins using this key may not appear in the wallet. This error could be caused "
443  "by pruning or data corruption (see dashd log for details) and could be dealt with by "
444  "downloading and rescanning the relevant blocks (see -reindex and -rescan "
445  "options).\"}},{\"success\":true}]",
446  0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW));
447  RemoveWallet(&wallet);
448  }
449 }
450 
451 // Verify importwallet RPC starts rescan at earliest block with timestamp
452 // greater or equal than key birthday. Previously there was a bug where
453 // importwallet RPC would start the scan at the latest block with timestamp less
454 // than or equal to key birthday.
455 BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup)
456 {
457  // Create two blocks with same timestamp to verify that importwallet rescan
458  // will pick up both blocks, not just the first.
459  const int64_t BLOCK_TIME = chainActive.Tip()->GetBlockTimeMax() + 5;
460  SetMockTime(BLOCK_TIME);
461  coinbaseTxns.emplace_back(*CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
462  coinbaseTxns.emplace_back(*CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
463 
464  // Set key birthday to block time increased by the timestamp window, so
465  // rescan will start at the block time.
466  const int64_t KEY_TIME = BLOCK_TIME + 7200;
467  SetMockTime(KEY_TIME);
468  coinbaseTxns.emplace_back(*CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
469 
470  LOCK(cs_main);
471 
472  // Import key into wallet and call dumpwallet to create backup file.
473  {
474  CWallet wallet("dummy", WalletDatabase::CreateDummy());
475  LOCK(wallet.cs_wallet);
476  wallet.mapKeyMetadata[coinbaseKey.GetPubKey().GetID()].nCreateTime = KEY_TIME;
477  wallet.AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
478 
479  JSONRPCRequest request;
480  request.params.setArray();
481  request.params.push_back((pathTemp / "wallet.backup").string());
482  AddWallet(&wallet);
483  ::dumpwallet(request);
484  RemoveWallet(&wallet);
485  }
486 
487  // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME
488  // were scanned, and no prior blocks were scanned.
489  {
490  CWallet wallet("dummy", WalletDatabase::CreateDummy());
491 
492  JSONRPCRequest request;
493  request.params.setArray();
494  request.params.push_back((pathTemp / "wallet.backup").string());
495  AddWallet(&wallet);
496  ::importwallet(request);
497  RemoveWallet(&wallet);
498 
499  LOCK(wallet.cs_wallet);
500  BOOST_CHECK_EQUAL(wallet.mapWallet.size(), 3);
501  BOOST_CHECK_EQUAL(coinbaseTxns.size(), 103);
502  for (size_t i = 0; i < coinbaseTxns.size(); ++i) {
503  bool found = wallet.GetWalletTx(coinbaseTxns[i].GetHash());
504  bool expected = i >= 100;
505  BOOST_CHECK_EQUAL(found, expected);
506  }
507  }
508 
509  SetMockTime(0);
510 }
511 
512 // Check that GetImmatureCredit() returns a newly calculated value instead of
513 // the cached value after a MarkDirty() call.
514 //
515 // This is a regression test written to verify a bugfix for the immature credit
516 // function. Similar tests probably should be written for the other credit and
517 // debit functions.
518 BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup)
519 {
520  CWallet wallet("dummy", WalletDatabase::CreateDummy());
521  CWalletTx wtx(&wallet, MakeTransactionRef(coinbaseTxns.back()));
522  LOCK2(cs_main, wallet.cs_wallet);
524  wtx.nIndex = 0;
525 
526  // Call GetImmatureCredit() once before adding the key to the wallet to
527  // cache the current immature credit amount, which is 0.
529 
530  // Invalidate the cached value, add the key, and make sure a new immature
531  // credit amount is calculated.
532  wtx.MarkDirty();
533  wallet.AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
535 }
536 
537 static int64_t AddTx(CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
538 {
540  tx.nLockTime = lockTime;
541  SetMockTime(mockTime);
542  CBlockIndex* block = nullptr;
543  if (blockTime > 0) {
544  LOCK(cs_main);
545  auto inserted = mapBlockIndex.emplace(GetRandHash(), new CBlockIndex);
546  assert(inserted.second);
547  const uint256& hash = inserted.first->first;
548  block = inserted.first->second;
549  block->nTime = blockTime;
550  block->phashBlock = &hash;
551  }
552 
553  CWalletTx wtx(&wallet, MakeTransactionRef(tx));
554  if (block) {
555  wtx.SetMerkleBranch(block, 0);
556  }
557  wallet.AddToWallet(wtx);
558  LOCK(wallet.cs_wallet);
559  return wallet.mapWallet.at(wtx.GetHash()).nTimeSmart;
560 }
561 
562 // Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
563 // expanded to cover more corner cases of smart time logic.
564 BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
565 {
566  // New transaction should use clock time if lower than block time.
567  BOOST_CHECK_EQUAL(AddTx(m_wallet, 1, 100, 120), 100);
568 
569  // Test that updating existing transaction does not change smart time.
570  BOOST_CHECK_EQUAL(AddTx(m_wallet, 1, 200, 220), 100);
571 
572  // New transaction should use clock time if there's no block time.
573  BOOST_CHECK_EQUAL(AddTx(m_wallet, 2, 300, 0), 300);
574 
575  // New transaction should use block time if lower than clock time.
576  BOOST_CHECK_EQUAL(AddTx(m_wallet, 3, 420, 400), 400);
577 
578  // New transaction should use latest entry time if higher than
579  // min(block time, clock time).
580  BOOST_CHECK_EQUAL(AddTx(m_wallet, 4, 500, 390), 400);
581 
582  // If there are future entries, new transaction should use time of the
583  // newest entry that is no more than 300 seconds ahead of the clock time.
584  BOOST_CHECK_EQUAL(AddTx(m_wallet, 5, 50, 600), 300);
585 
586  // Reset mock time for other tests.
587  SetMockTime(0);
588 }
589 
590 BOOST_AUTO_TEST_CASE(LoadReceiveRequests)
591 {
592  CTxDestination dest = CKeyID();
593  LOCK(m_wallet.cs_wallet);
594  m_wallet.AddDestData(dest, "misc", "val_misc");
595  m_wallet.AddDestData(dest, "rr0", "val_rr0");
596  m_wallet.AddDestData(dest, "rr1", "val_rr1");
597 
598  auto values = m_wallet.GetDestValues("rr");
599  BOOST_CHECK_EQUAL(values.size(), 2);
600  BOOST_CHECK_EQUAL(values[0], "val_rr0");
601  BOOST_CHECK_EQUAL(values[1], "val_rr1");
602 }
603 
604 class ListCoinsTestingSetup : public TestChain100Setup
605 {
606 public:
608  {
609  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
610  wallet = MakeUnique<CWallet>("mock", WalletDatabase::CreateMock());
611  bool firstRun;
612  wallet->LoadWallet(firstRun);
613  AddKey(*wallet, coinbaseKey);
614  WalletRescanReserver reserver(wallet.get());
615  reserver.reserve();
616  wallet->ScanForWalletTransactions(chainActive.Genesis(), nullptr, reserver);
617  }
618 
620  {
621  wallet.reset();
622  }
623 
625  {
626  CWalletTx wtx;
627  CReserveKey reservekey(wallet.get());
628  CAmount fee;
629  int changePos = -1;
630  std::string error;
631  CCoinControl dummy;
632  BOOST_CHECK(wallet->CreateTransaction({recipient}, wtx, reservekey, fee, changePos, error, dummy));
633  CValidationState state;
634  BOOST_CHECK(wallet->CommitTransaction(wtx, reservekey, nullptr, state));
635  CMutableTransaction blocktx;
636  {
637  LOCK(wallet->cs_wallet);
638  blocktx = CMutableTransaction(*wallet->mapWallet.at(wtx.tx->GetHash()).tx);
639  }
640  CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
641  LOCK(cs_main);
642  LOCK(wallet->cs_wallet);
643  auto it = wallet->mapWallet.find(wtx.GetHash());
644  BOOST_CHECK(it != wallet->mapWallet.end());
645  it->second.SetMerkleBranch(chainActive.Tip(), 1);
646  return it->second;
647  }
648 
649  std::unique_ptr<CWallet> wallet;
650 };
651 
653 {
654  std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
655 
656  // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
657  // address.
658  auto list = wallet->ListCoins();
659  BOOST_CHECK_EQUAL(list.size(), 1);
660  BOOST_CHECK_EQUAL(boost::get<CKeyID>(list.begin()->first).ToString(), coinbaseAddress);
661  BOOST_CHECK_EQUAL(list.begin()->second.size(), 1);
662 
663  // Check initial balance from one mature coinbase transaction.
664  BOOST_CHECK_EQUAL(500 * COIN, wallet->GetAvailableBalance());
665 
666  // Add a transaction creating a change address, and confirm ListCoins still
667  // returns the coin associated with the change address underneath the
668  // coinbaseKey pubkey, even though the change address has a different
669  // pubkey.
670  AddTx(CRecipient{GetScriptForRawPubKey({}), 1 * COIN, false /* subtract fee */});
671  list = wallet->ListCoins();
672  BOOST_CHECK_EQUAL(list.size(), 1);
673  BOOST_CHECK_EQUAL(boost::get<CKeyID>(list.begin()->first).ToString(), coinbaseAddress);
674  BOOST_CHECK_EQUAL(list.begin()->second.size(), 2);
675 
676  // Lock both coins. Confirm number of available coins drops to 0.
677  std::vector<COutput> available;
678  wallet->AvailableCoins(available);
679  BOOST_CHECK_EQUAL(available.size(), 2);
680  for (const auto& group : list) {
681  for (const auto& coin : group.second) {
682  LOCK(wallet->cs_wallet);
683  wallet->LockCoin(COutPoint(coin.tx->GetHash(), coin.i));
684  }
685  }
686  wallet->AvailableCoins(available);
687  BOOST_CHECK_EQUAL(available.size(), 0);
688 
689  // Confirm ListCoins still returns same result as before, despite coins
690  // being locked.
691  list = wallet->ListCoins();
692  BOOST_CHECK_EQUAL(list.size(), 1);
693  BOOST_CHECK_EQUAL(boost::get<CKeyID>(list.begin()->first).ToString(), coinbaseAddress);
694  BOOST_CHECK_EQUAL(list.begin()->second.size(), 2);
695 }
696 
697 class CreateTransactionTestSetup : public TestChain100Setup
698 {
699 public:
700  enum ChangeTest {
704  };
705 
706  // Result strings to test
707  const std::string strInsufficientFunds = "Insufficient funds.";
708  const std::string strAmountNotNegative = "Transaction amounts must not be negative";
709  const std::string strAtLeastOneRecipient = "Transaction must have at least one recipient";
710  const std::string strTooSmallToPayFee = "The transaction amount is too small to pay the fee";
711  const std::string strTooSmallAfterFee = "The transaction amount is too small to send after the fee has been deducted";
712  const std::string strTooSmall = "Transaction amount too small";
713  const std::string strUnableToLocatePrivateSend1 = "Unable to locate enough PrivateSend non-denominated funds for this transaction.";
714  const std::string strUnableToLocatePrivateSend2 = "Unable to locate enough PrivateSend denominated funds for this transaction. PrivateSend uses exact denominated amounts to send funds, you might simply need to mix some more coins.";
715  const std::string strTransactionTooLarge = "Transaction too large";
716  const std::string strTransactionTooLargeForFeePolicy = "Transaction too large for fee policy";
717  const std::string strChangeIndexOutOfRange = "Change index out of range";
718  const std::string strExceededMaxTries = "Exceeded max tries.";
719 
721  {
722  CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
723  wallet = MakeUnique<CWallet>("mock", WalletDatabase::CreateMock());
724  bool firstRun;
725  wallet->LoadWallet(firstRun);
726  AddWallet(wallet.get());
727  AddKey(*wallet, coinbaseKey);
728  WalletRescanReserver reserver(wallet.get());
729  reserver.reserve();
730  wallet->ScanForWalletTransactions(chainActive.Genesis(), nullptr, reserver);
731  }
732 
734  {
735  RemoveWallet(wallet.get());
736  }
737 
738  std::unique_ptr<CWallet> wallet;
740 
741  template <typename T>
742  bool CheckEqual(const T expected, const T actual)
743  {
744  BOOST_CHECK_EQUAL(expected, actual);
745  return expected == actual;
746  }
747 
748  bool CreateTransaction(const std::vector<std::pair<CAmount, bool>>& vecEntries, bool fCreateShouldSucceed = true, ChangeTest changeTest = ChangeTest::Skip)
749  {
750  return CreateTransaction(vecEntries, {}, -1, fCreateShouldSucceed, changeTest);
751  }
752  bool CreateTransaction(const std::vector<std::pair<CAmount, bool>>& vecEntries, std::string strErrorExpected, bool fCreateShouldSucceed = true, ChangeTest changeTest = ChangeTest::Skip)
753  {
754  return CreateTransaction(vecEntries, strErrorExpected, -1, fCreateShouldSucceed, changeTest);
755  }
756 
757  bool CreateTransaction(const std::vector<std::pair<CAmount, bool>>& vecEntries, std::string strErrorExpected, int nChangePosRequest = -1, bool fCreateShouldSucceed = true, ChangeTest changeTest = ChangeTest::Skip)
758  {
759  CWalletTx wtx;
760  CReserveKey reservekey(wallet.get());
761  CAmount nFeeRet;
762  int nChangePos = nChangePosRequest;
763  std::string strError;
764 
765  bool fCreationSucceeded = wallet->CreateTransaction(GetRecipients(vecEntries), wtx, reservekey, nFeeRet, nChangePos, strError, coinControl);
766  bool fHitMaxTries = strError == strExceededMaxTries;
767  // This should never happen.
768  if (fHitMaxTries) {
769  BOOST_CHECK(!fHitMaxTries);
770  return false;
771  }
772  // Verify the creation succeeds if expected and fails if not.
773  if (!CheckEqual(fCreateShouldSucceed, fCreationSucceeded)) {
774  return false;
775  }
776  // Verify the expected error string if there is one provided
777  if (strErrorExpected.size() && !CheckEqual(strErrorExpected, strError)) {
778  return false;
779  }
780  if (!fCreateShouldSucceed) {
781  // No need to evaluate the following if the creation should have failed.
782  return true;
783  }
784  // Verify there is no change output if there wasn't any expected
785  bool fChangeTestPassed = changeTest == ChangeTest::Skip ||
786  (changeTest == ChangeTest::ChangeExpected && nChangePos != -1) ||
787  (changeTest == ChangeTest::NoChangeExpected && nChangePos == -1);
788  BOOST_CHECK(fChangeTestPassed);
789  if (!fChangeTestPassed) {
790  return false;
791  }
792  // Verify the change is at the requested position if there was a request
793  if (nChangePosRequest != -1 && !CheckEqual(nChangePosRequest, nChangePos)) {
794  return false;
795  }
796  // Verify the number of requested outputs does match the resulting outputs
797  return CheckEqual(vecEntries.size(), wtx.tx->vout.size() - (nChangePos != -1 ? 1 : 0));
798  }
799 
800  std::vector<CRecipient> GetRecipients(const std::vector<std::pair<CAmount, bool>>& vecEntries)
801  {
802  std::vector<CRecipient> vecRecipients;
803  for (auto entry : vecEntries) {
804  vecRecipients.push_back({GetScriptForDestination(DecodeDestination(getnewaddress(JSONRPCRequest()).get_str())), entry.first, entry.second});
805  }
806  return vecRecipients;
807  }
808 
809  std::vector<COutPoint> GetCoins(const std::vector<std::pair<CAmount, bool>>& vecEntries)
810  {
811  CWalletTx wtx;
812  CReserveKey reserveKey(wallet.get());
813  CAmount nFeeRet;
814  int nChangePosRet = -1;
815  std::string strError;
817  BOOST_CHECK(wallet->CreateTransaction(GetRecipients(vecEntries), wtx, reserveKey, nFeeRet, nChangePosRet, strError, coinControl));
818  CValidationState state;
819  BOOST_CHECK(wallet->CommitTransaction(wtx, reserveKey, nullptr, state));
820  CMutableTransaction blocktx;
821  {
822  LOCK(wallet->cs_wallet);
823  blocktx = CMutableTransaction(*wallet->mapWallet.at(wtx.tx->GetHash()).tx);
824  }
825  CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
826  LOCK(cs_main);
827  LOCK(wallet->cs_wallet);
828  auto it = wallet->mapWallet.find(wtx.GetHash());
829  BOOST_CHECK(it != wallet->mapWallet.end());
830  it->second.SetMerkleBranch(chainActive.Tip(), 1);
831  wtx = it->second;
832 
833  std::vector<COutPoint> vecOutpoints;
834  size_t n;
835  for (n = 0; n < wtx.tx->vout.size(); ++n) {
836  if (nChangePosRet != -1 && n == nChangePosRet) {
837  // Skip the change output to only return the requested coins
838  continue;
839  }
840  vecOutpoints.push_back(COutPoint(wtx.GetHash(), n));
841  }
842  assert(vecOutpoints.size() == vecEntries.size());
843  return vecOutpoints;
844  }
845 };
846 
848 {
850 
851  auto runTest = [&](const int nTestId, const CAmount nFeeRate, const std::map<int, std::pair<bool, ChangeTest>>& mapExpected) {
852  coinControl.m_feerate = CFeeRate(nFeeRate);
853  const std::map<int, std::vector<std::pair<CAmount, bool>>> mapTestCases{
854  {0, {{1000, false}}},
855  {1, {{1000, true}}},
856  {2, {{10000, false}}},
857  {3, {{10000, true}}},
858  {4, {{34000, false}, {40000, false}}},
859  {5, {{37000, false}, {40000, false}}},
860  {6, {{50000, false}, {50000, false}}},
861  {7, {{50000, true}, {50000, false}}},
862  {8, {{50000, false}, {50001, false}}},
863  {9, {{50000, true}, {50001, true}}},
864  {10, {{100000, false}}},
865  {11, {{100000, true}}},
866  {12, {{100001, false}}},
867  {13, {{100001, true}}}
868  };
869  assert(mapTestCases.size() == mapExpected.size());
870  for (int i = 0; i < mapTestCases.size(); ++i) {
871  if (!CreateTransaction(mapTestCases.at(i), mapExpected.at(i).first, mapExpected.at(i).second)) {
872  std::cout << strprintf("CreateTransactionTest failed at: %d - %d\n", nTestId, i) << std::endl;
873  }
874  }
875  };
876 
877  // First run the tests with only one input containing 100k duffs
878  {
879  coinControl.SetNull();
880  coinControl.Select(GetCoins({{100000, false}})[0]);
881 
882  // Start with fallback feerate
883  runTest(1, DEFAULT_FALLBACK_FEE, {
884  {0, {true, ChangeTest::ChangeExpected}},
885  {1, {true, ChangeTest::ChangeExpected}},
886  {2, {true, ChangeTest::ChangeExpected}},
887  {3, {true, ChangeTest::ChangeExpected}},
888  {4, {true, ChangeTest::ChangeExpected}},
889  {5, {true, ChangeTest::ChangeExpected}},
890  {6, {false, ChangeTest::Skip}},
891  {7, {true, ChangeTest::NoChangeExpected}},
892  {8, {false, ChangeTest::Skip}},
893  {9, {false, ChangeTest::Skip}},
894  {10, {false, ChangeTest::Skip}},
895  {11, {true, ChangeTest::NoChangeExpected}},
896  {12, {false, ChangeTest::Skip}},
897  {13, {false, ChangeTest::Skip}}
898  });
899  // Now with 100x fallback feerate
900  runTest(2, DEFAULT_FALLBACK_FEE * 100, {
901  {0, {true, ChangeTest::ChangeExpected}},
902  {1, {false, ChangeTest::Skip}},
903  {2, {true, ChangeTest::ChangeExpected}},
904  {3, {false, ChangeTest::Skip}},
905  {4, {true, ChangeTest::NoChangeExpected}},
906  {5, {false, ChangeTest::Skip}},
907  {6, {false, ChangeTest::Skip}},
908  {7, {true, ChangeTest::NoChangeExpected}},
909  {8, {false, ChangeTest::Skip}},
910  {9, {false, ChangeTest::Skip}},
911  {10, {false, ChangeTest::Skip}},
912  {11, {true, ChangeTest::NoChangeExpected}},
913  {12, {false, ChangeTest::Skip}},
914  {13, {false, ChangeTest::Skip}}
915  });
916  }
917  // Now use 4 different inputs with a total of 100k duff
918  {
919  coinControl.SetNull();
920  auto setCoins = GetCoins({{1000, false}, {5000, false}, {10000, false}, {84000, false}});
921  for (auto coin : setCoins) {
922  coinControl.Select(coin);
923  }
924 
925  // Start with fallback feerate
926  runTest(3, DEFAULT_FALLBACK_FEE, {
927  {0, {true, ChangeTest::ChangeExpected}},
928  {1, {false, ChangeTest::Skip}},
929  {2, {true, ChangeTest::ChangeExpected}},
930  {3, {true, ChangeTest::ChangeExpected}},
931  {4, {true, ChangeTest::ChangeExpected}},
932  {5, {true, ChangeTest::ChangeExpected}},
933  {6, {false, ChangeTest::Skip}},
934  {7, {true, ChangeTest::NoChangeExpected}},
935  {8, {false, ChangeTest::Skip}},
936  {9, {false, ChangeTest::Skip}},
937  {10, {false, ChangeTest::Skip}},
938  {11, {true, ChangeTest::NoChangeExpected}},
939  {12, {false, ChangeTest::Skip}},
940  {13, {false, ChangeTest::Skip}}
941  });
942  // Now with 100x fallback feerate
943  runTest(4, DEFAULT_FALLBACK_FEE * 100, {
944  {0, {true, ChangeTest::ChangeExpected}},
945  {1, {false, ChangeTest::Skip}},
946  {2, {true, ChangeTest::ChangeExpected}},
947  {3, {false, ChangeTest::Skip}},
948  {4, {false, ChangeTest::Skip}},
949  {5, {false, ChangeTest::Skip}},
950  {6, {false, ChangeTest::Skip}},
951  {7, {false, ChangeTest::Skip}},
952  {8, {false, ChangeTest::Skip}},
953  {9, {false, ChangeTest::Skip}},
954  {10, {false, ChangeTest::Skip}},
955  {11, {true, ChangeTest::NoChangeExpected}},
956  {12, {false, ChangeTest::Skip}},
957  {13, {false, ChangeTest::Skip}}
958  });
959  }
960 
961  // Last use 10 equal inputs with a total of 100k duff
962  {
963  coinControl.SetNull();
964  auto setCoins = GetCoins({{10000, false}, {10000, false}, {10000, false}, {10000, false}, {10000, false},
965  {10000, false}, {10000, false}, {10000, false}, {10000, false}, {10000, false}});
966 
967  for (auto coin : setCoins) {
968  coinControl.Select(coin);
969  }
970 
971  // Start with fallback feerate
972  runTest(5, DEFAULT_FALLBACK_FEE, {
973  {0, {true, ChangeTest::ChangeExpected}},
974  {1, {false, ChangeTest::Skip}},
975  {2, {true, ChangeTest::ChangeExpected}},
976  {3, {true, ChangeTest::ChangeExpected}},
977  {4, {true, ChangeTest::ChangeExpected}},
978  {5, {true, ChangeTest::ChangeExpected}},
979  {6, {false, ChangeTest::Skip}},
980  {7, {true, ChangeTest::NoChangeExpected}},
981  {8, {false, ChangeTest::Skip}},
982  {9, {false, ChangeTest::Skip}},
983  {10, {false, ChangeTest::Skip}},
984  {11, {true, ChangeTest::NoChangeExpected}},
985  {12, {false, ChangeTest::Skip}},
986  {13, {false, ChangeTest::Skip}}
987  });
988  // Now with 100x fallback feerate
989  runTest(6, DEFAULT_FALLBACK_FEE * 100, {
990  {0, {false, ChangeTest::Skip}},
991  {1, {false, ChangeTest::Skip}},
992  {2, {false, ChangeTest::Skip}},
993  {3, {false, ChangeTest::Skip}},
994  {4, {false, ChangeTest::Skip}},
995  {5, {false, ChangeTest::Skip}},
996  {6, {false, ChangeTest::Skip}},
997  {7, {false, ChangeTest::Skip}},
998  {8, {false, ChangeTest::Skip}},
999  {9, {false, ChangeTest::Skip}},
1000  {10, {false, ChangeTest::Skip}},
1001  {11, {false, ChangeTest::Skip}},
1002  {12, {false, ChangeTest::Skip}},
1003  {13, {false, ChangeTest::Skip}}
1004  });
1005  }
1006  // Some tests without selected coins in coinControl, let the wallet decide
1007  // which inputs to use
1008  {
1009  coinControl.SetNull();
1010  auto setCoins = GetCoins({{1000, false}, {1000, false}, {1000, false}, {1000, false}, {1000, false},
1011  {1100, false}, {1200, false}, {1300, false}, {1400, false}, {1500, false},
1012  {3000, false}, {3000, false}, {2000, false}, {2000, false}, {1000, false}});
1013  // Lock all other coins which were already in the wallet
1014  std::vector<COutput> vecAvailable;
1015  {
1016  LOCK2(cs_main, wallet->cs_wallet);
1017  wallet->AvailableCoins(vecAvailable);
1018  for (auto coin : vecAvailable) {
1019  auto out = COutPoint(coin.tx->GetHash(), coin.i);
1020  if (std::find(setCoins.begin(), setCoins.end(), out) == setCoins.end()) {
1021  wallet->LockCoin(out);
1022  }
1023  }
1024  }
1025 
1026  BOOST_CHECK(CreateTransaction({{100, false}}, false));
1027  BOOST_CHECK(CreateTransaction({{1000, true}}, true));
1028  BOOST_CHECK(CreateTransaction({{1100, false}}, true));
1029  BOOST_CHECK(CreateTransaction({{1100, true}}, true));
1030  BOOST_CHECK(CreateTransaction({{2200, false}}, true));
1031  BOOST_CHECK(CreateTransaction({{3300, false}}, true));
1032  BOOST_CHECK(CreateTransaction({{4400, false}}, true));
1033  BOOST_CHECK(CreateTransaction({{5500, false}}, true));
1034  BOOST_CHECK(CreateTransaction({{5500, true}}, true));
1035  BOOST_CHECK(CreateTransaction({{6600, false}}, true));
1036  BOOST_CHECK(CreateTransaction({{7700, false}}, true));
1037  BOOST_CHECK(CreateTransaction({{8800, false}}, true));
1038  BOOST_CHECK(CreateTransaction({{9900, false}}, true));
1039  BOOST_CHECK(CreateTransaction({{9900, true}}, true));
1040  BOOST_CHECK(CreateTransaction({{10000, false}}, true));
1041  BOOST_CHECK(CreateTransaction({{10000, false}, {10000, false}}, false));
1042  BOOST_CHECK(CreateTransaction({{10000, false}, {12500, true}}, true));
1043  BOOST_CHECK(CreateTransaction({{10000, true}, {10000, true}}, true));
1044  BOOST_CHECK(CreateTransaction({{1000, false}, {2000, false}, {3000, false}, {4000, false}}, true));
1045  BOOST_CHECK(CreateTransaction({{1234, false}}, true));
1046  BOOST_CHECK(CreateTransaction({{1234, false}, {4321, false}}, true));
1047  BOOST_CHECK(CreateTransaction({{1234, false}, {4321, false}, {5678, false}}, true));
1048  BOOST_CHECK(CreateTransaction({{1234, false}, {4321, false}, {5678, false}, {8765, false}}, false));
1049  BOOST_CHECK(CreateTransaction({{1234, false}, {4321, false}, {5678, false}, {8765, true}}, true));
1050  BOOST_CHECK(CreateTransaction({{1000000, false}}, false));
1051 
1052  LOCK(wallet->cs_wallet);
1053  wallet->UnlockAllCoins();
1054  }
1055  // Test if the change output ends up at the requested position
1056  {
1057  coinControl.SetNull();
1058  coinControl.Select(GetCoins({{100000, false}})[0]);
1059 
1060  BOOST_CHECK(CreateTransaction({{25000, false}, {25000, false}, {25000, false}}, {}, 0, true, ChangeTest::ChangeExpected));
1061  BOOST_CHECK(CreateTransaction({{25000, false}, {25000, false}, {25000, false}}, {}, 1, true, ChangeTest::ChangeExpected));
1062  BOOST_CHECK(CreateTransaction({{25000, false}, {25000, false}, {25000, false}}, {}, 2, true, ChangeTest::ChangeExpected));
1063  BOOST_CHECK(CreateTransaction({{25000, false}, {25000, false}, {25000, false}}, {}, 3, true, ChangeTest::ChangeExpected));
1064  }
1065  // Test error cases
1066  {
1067  coinControl.SetNull();
1068  // First try to send something without any coins available
1069  {
1070  // Lock all other coins
1071  std::vector<COutput> vecAvailable;
1072  {
1073  LOCK2(cs_main, wallet->cs_wallet);
1074  wallet->AvailableCoins(vecAvailable);
1075  for (auto coin : vecAvailable) {
1076  wallet->LockCoin(COutPoint(coin.tx->GetHash(), coin.i));
1077  }
1078  }
1079 
1080  BOOST_CHECK(CreateTransaction({{1000, false}}, strInsufficientFunds, false));
1081  BOOST_CHECK(CreateTransaction({{1000, true}}, strInsufficientFunds, false));
1082  coinControl.nCoinType = CoinType::ONLY_NONDENOMINATED;
1083  BOOST_CHECK(CreateTransaction({{1000, true}}, strUnableToLocatePrivateSend1, false));
1084  coinControl.nCoinType = CoinType::ONLY_FULLY_MIXED;
1085  BOOST_CHECK(CreateTransaction({{1000, true}}, strUnableToLocatePrivateSend2, false));
1086 
1087  LOCK(wallet->cs_wallet);
1088  wallet->UnlockAllCoins();
1089  }
1090 
1091  // Just to create nCount output recipes to use in tests below
1092  std::vector<std::pair<CAmount, bool>> vecOutputEntries{{5000, false}};
1093  auto createOutputEntries = [&](int nCount) {
1094  while (vecOutputEntries.size() <= nCount) {
1095  vecOutputEntries.push_back(vecOutputEntries.back());
1096  }
1097  if (vecOutputEntries.size() > nCount) {
1098  int nDiff = vecOutputEntries.size() - nCount;
1099  vecOutputEntries.erase(vecOutputEntries.begin(), vecOutputEntries.begin() + nDiff);
1100  }
1101  };
1102 
1103  coinControl.SetNull();
1104  coinControl.Select(GetCoins({{100 * COIN, false}})[0]);
1105 
1106  BOOST_CHECK(CreateTransaction({{-5000, false}}, strAmountNotNegative, false));
1107  BOOST_CHECK(CreateTransaction({}, strAtLeastOneRecipient, false));
1108  BOOST_CHECK(CreateTransaction({{545, false}}, strTooSmall, false));
1109  BOOST_CHECK(CreateTransaction({{545, true}}, strTooSmall, false));
1110  BOOST_CHECK(CreateTransaction({{546, true}}, strTooSmallAfterFee, false));
1111 
1112  createOutputEntries(100);
1113  vecOutputEntries.push_back({600, true});
1114  BOOST_CHECK(CreateTransaction(vecOutputEntries, strTooSmallToPayFee, false));
1115  vecOutputEntries.pop_back();
1116 
1117  createOutputEntries(2934);
1118  BOOST_CHECK(CreateTransaction(vecOutputEntries, {}, true));
1119  createOutputEntries(2935);
1120  BOOST_CHECK(CreateTransaction(vecOutputEntries, strTransactionTooLarge, false));
1121 
1122  auto prevRate = minRelayTxFee;
1123  coinControl.m_feerate = prevRate;
1124  coinControl.fOverrideFeeRate = true;
1125  minRelayTxFee = CFeeRate(prevRate.GetFeePerK() * 10);
1126  BOOST_CHECK(CreateTransaction({{5000, false}}, strTransactionTooLargeForFeePolicy, false));
1127  coinControl.m_feerate.reset();
1128  minRelayTxFee = prevRate;
1129 
1130  BOOST_CHECK(CreateTransaction({{5000, false}, {5000, false}, {5000, false}}, strChangeIndexOutOfRange, 4, false));
1131  }
1132 }
1133 
static std::unique_ptr< BerkeleyDatabase > CreateDummy()
Return object for accessing dummy database with no read/write capabilities.
Definition: db.h:123
#define RANDOM_REPEATS
CDiskBlockPos GetBlockPos() const
Definition: chain.h:261
bool SelectCoinsMinConf(const CAmount &nTargetValue, int nConfMine, int nConfTheirs, uint64_t nMaxAncestors, std::vector< COutput > vCoins, std::set< CInputCoin > &setCoinsRet, CAmount &nValueRet, CoinType nCoinType=CoinType::ALL_COINS) const
Shuffle and select coins until nTargetValue is reached while avoiding small change; This method is st...
Definition: wallet.cpp:3025
static std::unique_ptr< BerkeleyDatabase > CreateMock()
Return object for accessing temporary in-memory database.
Definition: db.h:129
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: validation.h:76
void SetMerkleBranch(const CBlockIndex *pIndex, int posInBlock)
Definition: wallet.cpp:5492
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:80
uint256 GetRandHash()
Definition: random.cpp:384
const CWalletTx * GetWalletTx(const uint256 &hash) const
Definition: wallet.cpp:178
CAmount GetImmatureBalance() const
Definition: wallet.cpp:2666
CCriticalSection cs_wallet
Definition: wallet.h:836
#define strprintf
Definition: tinyformat.h:1066
const uint256 & GetHash() const
Definition: wallet.h:272
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:179
int nIndex
Definition: wallet.h:218
bool RemoveWallet(CWallet *wallet)
Definition: wallet.cpp:63
std::vector< CTxIn > vin
Definition: transaction.h:293
BlockMap & mapBlockIndex
Definition: validation.cpp:215
static const CAmount COIN
Definition: amount.h:14
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Adds a key to the store, and saves it to disk.
Definition: wallet.cpp:405
uint256 hashBlock
Definition: wallet.h:211
void SetMockTime(int64_t nMockTimeIn)
For testing.
Definition: utiltime.cpp:46
CCriticalSection cs_main
Definition: validation.cpp:213
CTxDestination DecodeDestination(const std::string &str)
Definition: base58.cpp:336
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: standard.cpp:264
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
const std::string strUnableToLocatePrivateSend1
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:448
void MarkDirty()
make sure balances are recalculated
Definition: wallet.h:454
uint32_t nTime
Definition: chain.h:212
const std::string strTooSmallAfterFee
const std::string strAtLeastOneRecipient
static void add_coin(const CAmount &nValue, int nAge=6 *24, bool fIsFromMe=false, int nInput=0)
const std::string strTransactionTooLargeForFeePolicy
CAmount GetImmatureCredit(bool fUseCache=true) const
Definition: wallet.cpp:2233
Coin Control Features.
Definition: coincontrol.h:28
UniValue getnewaddress(const JSONRPCRequest &request)
Definition: rpcwallet.cpp:134
CWalletTx & AddTx(CRecipient recipient)
static const CAmount MIN_CHANGE
target minimum change amount
Definition: wallet.h:66
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
uint256 GetBlockHash() const
Definition: chain.h:292
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:346
#define RUN_TESTS
BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup)
#define LOCK2(cs1, cs2)
Definition: sync.h:179
bool push_back(const UniValue &val)
Definition: univalue.cpp:110
void PruneOneBlockFile(const int fileNumber)
Mark one block file as pruned.
static void AddKey(CWallet &wallet, const CKey &key)
BOOST_AUTO_TEST_CASE(coin_selection_tests)
std::unique_ptr< CWallet > wallet
bool CreateTransaction(const std::vector< std::pair< CAmount, bool >> &vecEntries, std::string strErrorExpected, int nChangePosRequest=-1, bool fCreateShouldSucceed=true, ChangeTest changeTest=ChangeTest::Skip)
CTransactionRef tx
Definition: wallet.h:210
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:246
UniValue params
Definition: server.h:42
#define LOCK(cs)
Definition: sync.h:178
const std::string strTransactionTooLarge
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: validation.h:56
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:158
int64_t GetBlockTimeMax() const
Definition: chain.h:302
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
bool CheckEqual(const T expected, const T actual)
bool AddWallet(CWallet *wallet)
Definition: wallet.cpp:53
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:135
static const CAmount CENT
Definition: amount.h:15
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:256
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
static void ApproximateBestSubset(const std::vector< CInputCoin > &vValue, const CAmount &nTotalLower, const CAmount &nTargetValue, std::vector< char > &vfBest, CAmount &nBest, int iterations=1000)
Definition: wallet.cpp:2949
std::vector< CTxOut > vout
Definition: transaction.h:294
bool AddToWallet(const CWalletTx &wtxIn, bool fFlushOnClose=true)
Definition: wallet.cpp:1094
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1336
static std::vector< COutput > vCoins
const std::string strTooSmallToPayFee
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:280
UniValue importmulti(const JSONRPCRequest &request)
Definition: rpcdump.cpp:1306
std::vector< CRecipient > GetRecipients(const std::vector< std::pair< CAmount, bool >> &vecEntries)
const std::string strInsufficientFunds
CBlockIndex * ScanForWalletTransactions(CBlockIndex *pindexStart, CBlockIndex *pindexStop, const WalletRescanReserver &reserver, bool fUpdate=false)
Scan the block chain (starting in pindexStart) for transactions from or to us.
Definition: wallet.cpp:2030
const std::string strChangeIndexOutOfRange
UniValue dumpwallet(const JSONRPCRequest &request)
Definition: rpcdump.cpp:817
Capture information about block/transaction validation.
Definition: validation.h:22
256-bit opaque blob.
Definition: uint256.h:123
std::vector< COutPoint > GetCoins(const std::vector< std::pair< CAmount, bool >> &vecEntries)
bool setArray()
Definition: univalue.cpp:96
#define BOOST_FIXTURE_TEST_SUITE(a, b)
Definition: object.cpp:14
A key allocated from the key pool.
Definition: wallet.h:1273
Testing setup and teardown for wallet.
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:170
const std::string strTooSmall
static bool equal_sets(CoinSet a, CoinSet b)
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:20
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:453
#define BOOST_AUTO_TEST_SUITE_END()
Definition: object.cpp:16
const std::string strExceededMaxTries
static void empty_wallet(void)
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
Definition: wallet.h:715
bool setObject()
Definition: univalue.cpp:103
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
std::map< CKeyID, CKeyMetadata > mapKeyMetadata
Definition: wallet.h:853
static int64_t AddTx(CWallet &wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
bool error(const char *fmt, const Args &... args)
Definition: util.h:222
std::map< uint256, CWalletTx > mapWallet
Definition: wallet.h:896
bool CreateTransaction(const std::vector< std::pair< CAmount, bool >> &vecEntries, bool fCreateShouldSucceed=true, ChangeTest changeTest=ChangeTest::Skip)
A mutable version of CTransaction.
Definition: transaction.h:291
std::set< CInputCoin > CoinSet
void clear()
Definition: univalue.cpp:17
An encapsulated private key.
Definition: key.h:27
CChain & chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:217
const std::string strUnableToLocatePrivateSend2
std::unique_ptr< CWallet > wallet
int nFile
Definition: chain.h:87
bool CreateTransaction(const std::vector< std::pair< CAmount, bool >> &vecEntries, std::string strErrorExpected, bool fCreateShouldSucceed=true, ChangeTest changeTest=ChangeTest::Skip)
static const CWallet testWallet("dummy", WalletDatabase::CreateDummy())
static const CAmount DEFAULT_FALLBACK_FEE
-fallbackfee default
Definition: wallet.h:58
static const int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
Definition: chain.h:29
UniValue importwallet(const JSONRPCRequest &request)
Definition: rpcdump.cpp:468
#define BOOST_CHECK(expr)
Definition: object.cpp:17
std::vector< std::unique_ptr< CWalletTx > > wtxn
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:174
const std::string strAmountNotNegative
Released under the MIT license