Remove unused Boost includes
[bitcoinplatinum.git] / src / wallet / test / wallet_tests.cpp
blob1ee2722883e5ff13a164546c07761341afd43f4d
1 // Copyright (c) 2012-2016 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.
5 #include "wallet/wallet.h"
7 #include <set>
8 #include <stdint.h>
9 #include <utility>
10 #include <vector>
12 #include "consensus/validation.h"
13 #include "rpc/server.h"
14 #include "test/test_bitcoin.h"
15 #include "validation.h"
16 #include "wallet/test/wallet_test_fixture.h"
18 #include <boost/test/unit_test.hpp>
19 #include <univalue.h>
21 extern UniValue importmulti(const JSONRPCRequest& request);
22 extern UniValue dumpwallet(const JSONRPCRequest& request);
23 extern UniValue importwallet(const JSONRPCRequest& request);
25 // how many times to run all the tests to have a chance to catch errors that only show up with particular random shuffles
26 #define RUN_TESTS 100
28 // some tests fail 1% of the time due to bad luck.
29 // we repeat those tests this many times and only complain if all iterations of the test fail
30 #define RANDOM_REPEATS 5
32 std::vector<std::unique_ptr<CWalletTx>> wtxn;
34 typedef std::set<CInputCoin> CoinSet;
36 BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
38 static const CWallet testWallet;
39 static std::vector<COutput> vCoins;
41 static void add_coin(const CAmount& nValue, int nAge = 6*24, bool fIsFromMe = false, int nInput=0)
43 static int nextLockTime = 0;
44 CMutableTransaction tx;
45 tx.nLockTime = nextLockTime++; // so all transactions get different hashes
46 tx.vout.resize(nInput+1);
47 tx.vout[nInput].nValue = nValue;
48 if (fIsFromMe) {
49 // IsFromMe() returns (GetDebit() > 0), and GetDebit() is 0 if vin.empty(),
50 // so stop vin being empty, and cache a non-zero Debit to fake out IsFromMe()
51 tx.vin.resize(1);
53 std::unique_ptr<CWalletTx> wtx(new CWalletTx(&testWallet, MakeTransactionRef(std::move(tx))));
54 if (fIsFromMe)
56 wtx->fDebitCached = true;
57 wtx->nDebitCached = 1;
59 COutput output(wtx.get(), nInput, nAge, true /* spendable */, true /* solvable */, true /* safe */);
60 vCoins.push_back(output);
61 wtxn.emplace_back(std::move(wtx));
64 static void empty_wallet(void)
66 vCoins.clear();
67 wtxn.clear();
70 static bool equal_sets(CoinSet a, CoinSet b)
72 std::pair<CoinSet::iterator, CoinSet::iterator> ret = mismatch(a.begin(), a.end(), b.begin());
73 return ret.first == a.end() && ret.second == b.end();
76 BOOST_AUTO_TEST_CASE(coin_selection_tests)
78 CoinSet setCoinsRet, setCoinsRet2;
79 CAmount nValueRet;
81 LOCK(testWallet.cs_wallet);
83 // test multiple times to allow for differences in the shuffle order
84 for (int i = 0; i < RUN_TESTS; i++)
86 empty_wallet();
88 // with an empty wallet we can't even pay one cent
89 BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet));
91 add_coin(1*CENT, 4); // add a new 1 cent coin
93 // with a new 1 cent coin, we still can't find a mature 1 cent
94 BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet));
96 // but we can find a new 1 cent
97 BOOST_CHECK( testWallet.SelectCoinsMinConf( 1 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
98 BOOST_CHECK_EQUAL(nValueRet, 1 * CENT);
100 add_coin(2*CENT); // add a mature 2 cent coin
102 // we can't make 3 cents of mature coins
103 BOOST_CHECK(!testWallet.SelectCoinsMinConf( 3 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet));
105 // we can make 3 cents of new coins
106 BOOST_CHECK( testWallet.SelectCoinsMinConf( 3 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
107 BOOST_CHECK_EQUAL(nValueRet, 3 * CENT);
109 add_coin(5*CENT); // add a mature 5 cent coin,
110 add_coin(10*CENT, 3, true); // a new 10 cent coin sent from one of our own addresses
111 add_coin(20*CENT); // and a mature 20 cent coin
113 // now we have new: 1+10=11 (of which 10 was self-sent), and mature: 2+5+20=27. total = 38
115 // we can't make 38 cents only if we disallow new coins:
116 BOOST_CHECK(!testWallet.SelectCoinsMinConf(38 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet));
117 // we can't even make 37 cents if we don't allow new coins even if they're from us
118 BOOST_CHECK(!testWallet.SelectCoinsMinConf(38 * CENT, 6, 6, 0, vCoins, setCoinsRet, nValueRet));
119 // but we can make 37 cents if we accept new coins from ourself
120 BOOST_CHECK( testWallet.SelectCoinsMinConf(37 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet));
121 BOOST_CHECK_EQUAL(nValueRet, 37 * CENT);
122 // and we can make 38 cents if we accept all new coins
123 BOOST_CHECK( testWallet.SelectCoinsMinConf(38 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
124 BOOST_CHECK_EQUAL(nValueRet, 38 * CENT);
126 // try making 34 cents from 1,2,5,10,20 - we can't do it exactly
127 BOOST_CHECK( testWallet.SelectCoinsMinConf(34 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
128 BOOST_CHECK_EQUAL(nValueRet, 35 * CENT); // but 35 cents is closest
129 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)
131 // when we try making 7 cents, the smaller coins (1,2,5) are enough. We should see just 2+5
132 BOOST_CHECK( testWallet.SelectCoinsMinConf( 7 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
133 BOOST_CHECK_EQUAL(nValueRet, 7 * CENT);
134 BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
136 // when we try making 8 cents, the smaller coins (1,2,5) are exactly enough.
137 BOOST_CHECK( testWallet.SelectCoinsMinConf( 8 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
138 BOOST_CHECK(nValueRet == 8 * CENT);
139 BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
141 // when we try making 9 cents, no subset of smaller coins is enough, and we get the next bigger coin (10)
142 BOOST_CHECK( testWallet.SelectCoinsMinConf( 9 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
143 BOOST_CHECK_EQUAL(nValueRet, 10 * CENT);
144 BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
146 // now clear out the wallet and start again to test choosing between subsets of smaller coins and the next biggest coin
147 empty_wallet();
149 add_coin( 6*CENT);
150 add_coin( 7*CENT);
151 add_coin( 8*CENT);
152 add_coin(20*CENT);
153 add_coin(30*CENT); // now we have 6+7+8+20+30 = 71 cents total
155 // check that we have 71 and not 72
156 BOOST_CHECK( testWallet.SelectCoinsMinConf(71 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
157 BOOST_CHECK(!testWallet.SelectCoinsMinConf(72 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
159 // 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
160 BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
161 BOOST_CHECK_EQUAL(nValueRet, 20 * CENT); // we should get 20 in one coin
162 BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
164 add_coin( 5*CENT); // now we have 5+6+7+8+20+30 = 75 cents total
166 // 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
167 BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
168 BOOST_CHECK_EQUAL(nValueRet, 18 * CENT); // we should get 18 in 3 coins
169 BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
171 add_coin( 18*CENT); // now we have 5+6+7+8+18+20+30
173 // 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
174 BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
175 BOOST_CHECK_EQUAL(nValueRet, 18 * CENT); // we should get 18 in 1 coin
176 BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); // because in the event of a tie, the biggest coin wins
178 // now try making 11 cents. we should get 5+6
179 BOOST_CHECK( testWallet.SelectCoinsMinConf(11 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
180 BOOST_CHECK_EQUAL(nValueRet, 11 * CENT);
181 BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
183 // check that the smallest bigger coin is used
184 add_coin( 1*COIN);
185 add_coin( 2*COIN);
186 add_coin( 3*COIN);
187 add_coin( 4*COIN); // now we have 5+6+7+8+18+20+30+100+200+300+400 = 1094 cents
188 BOOST_CHECK( testWallet.SelectCoinsMinConf(95 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
189 BOOST_CHECK_EQUAL(nValueRet, 1 * COIN); // we should get 1 BTC in 1 coin
190 BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
192 BOOST_CHECK( testWallet.SelectCoinsMinConf(195 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
193 BOOST_CHECK_EQUAL(nValueRet, 2 * COIN); // we should get 2 BTC in 1 coin
194 BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
196 // empty the wallet and start again, now with fractions of a cent, to test small change avoidance
198 empty_wallet();
199 add_coin(MIN_CHANGE * 1 / 10);
200 add_coin(MIN_CHANGE * 2 / 10);
201 add_coin(MIN_CHANGE * 3 / 10);
202 add_coin(MIN_CHANGE * 4 / 10);
203 add_coin(MIN_CHANGE * 5 / 10);
205 // try making 1 * MIN_CHANGE from the 1.5 * MIN_CHANGE
206 // we'll get change smaller than MIN_CHANGE whatever happens, so can expect MIN_CHANGE exactly
207 BOOST_CHECK( testWallet.SelectCoinsMinConf(MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
208 BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE);
210 // but if we add a bigger coin, small change is avoided
211 add_coin(1111*MIN_CHANGE);
213 // try making 1 from 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 1111 = 1112.5
214 BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
215 BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE); // we should get the exact amount
217 // if we add more small coins:
218 add_coin(MIN_CHANGE * 6 / 10);
219 add_coin(MIN_CHANGE * 7 / 10);
221 // and try again to make 1.0 * MIN_CHANGE
222 BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
223 BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE); // we should get the exact amount
225 // run the 'mtgox' test (see http://blockexplorer.com/tx/29a3efd3ef04f9153d47a990bd7b048a4b2d213daaa5fb8ed670fb85f13bdbcf)
226 // they tried to consolidate 10 50k coins into one 500k coin, and ended up with 50k in change
227 empty_wallet();
228 for (int j = 0; j < 20; j++)
229 add_coin(50000 * COIN);
231 BOOST_CHECK( testWallet.SelectCoinsMinConf(500000 * COIN, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
232 BOOST_CHECK_EQUAL(nValueRet, 500000 * COIN); // we should get the exact amount
233 BOOST_CHECK_EQUAL(setCoinsRet.size(), 10U); // in ten coins
235 // 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),
236 // we need to try finding an exact subset anyway
238 // sometimes it will fail, and so we use the next biggest coin:
239 empty_wallet();
240 add_coin(MIN_CHANGE * 5 / 10);
241 add_coin(MIN_CHANGE * 6 / 10);
242 add_coin(MIN_CHANGE * 7 / 10);
243 add_coin(1111 * MIN_CHANGE);
244 BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
245 BOOST_CHECK_EQUAL(nValueRet, 1111 * MIN_CHANGE); // we get the bigger coin
246 BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
248 // but sometimes it's possible, and we use an exact subset (0.4 + 0.6 = 1.0)
249 empty_wallet();
250 add_coin(MIN_CHANGE * 4 / 10);
251 add_coin(MIN_CHANGE * 6 / 10);
252 add_coin(MIN_CHANGE * 8 / 10);
253 add_coin(1111 * MIN_CHANGE);
254 BOOST_CHECK( testWallet.SelectCoinsMinConf(MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
255 BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE); // we should get the exact amount
256 BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); // in two coins 0.4+0.6
258 // test avoiding small change
259 empty_wallet();
260 add_coin(MIN_CHANGE * 5 / 100);
261 add_coin(MIN_CHANGE * 1);
262 add_coin(MIN_CHANGE * 100);
264 // trying to make 100.01 from these three coins
265 BOOST_CHECK(testWallet.SelectCoinsMinConf(MIN_CHANGE * 10001 / 100, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
266 BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE * 10105 / 100); // we should get all coins
267 BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U);
269 // but if we try to make 99.9, we should take the bigger of the two small coins to avoid small change
270 BOOST_CHECK(testWallet.SelectCoinsMinConf(MIN_CHANGE * 9990 / 100, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
271 BOOST_CHECK_EQUAL(nValueRet, 101 * MIN_CHANGE);
272 BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
274 // test with many inputs
275 for (CAmount amt=1500; amt < COIN; amt*=10) {
276 empty_wallet();
277 // Create 676 inputs (= (old MAX_STANDARD_TX_SIZE == 100000) / 148 bytes per input)
278 for (uint16_t j = 0; j < 676; j++)
279 add_coin(amt);
280 BOOST_CHECK(testWallet.SelectCoinsMinConf(2000, 1, 1, 0, vCoins, setCoinsRet, nValueRet));
281 if (amt - 2000 < MIN_CHANGE) {
282 // needs more than one input:
283 uint16_t returnSize = std::ceil((2000.0 + MIN_CHANGE)/amt);
284 CAmount returnValue = amt * returnSize;
285 BOOST_CHECK_EQUAL(nValueRet, returnValue);
286 BOOST_CHECK_EQUAL(setCoinsRet.size(), returnSize);
287 } else {
288 // one input is sufficient:
289 BOOST_CHECK_EQUAL(nValueRet, amt);
290 BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U);
294 // test randomness
296 empty_wallet();
297 for (int i2 = 0; i2 < 100; i2++)
298 add_coin(COIN);
300 // picking 50 from 100 coins doesn't depend on the shuffle,
301 // but does depend on randomness in the stochastic approximation code
302 BOOST_CHECK(testWallet.SelectCoinsMinConf(50 * COIN, 1, 6, 0, vCoins, setCoinsRet , nValueRet));
303 BOOST_CHECK(testWallet.SelectCoinsMinConf(50 * COIN, 1, 6, 0, vCoins, setCoinsRet2, nValueRet));
304 BOOST_CHECK(!equal_sets(setCoinsRet, setCoinsRet2));
306 int fails = 0;
307 for (int j = 0; j < RANDOM_REPEATS; j++)
309 // selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of the time
310 // run the test RANDOM_REPEATS times and only complain if all of them fail
311 BOOST_CHECK(testWallet.SelectCoinsMinConf(COIN, 1, 6, 0, vCoins, setCoinsRet , nValueRet));
312 BOOST_CHECK(testWallet.SelectCoinsMinConf(COIN, 1, 6, 0, vCoins, setCoinsRet2, nValueRet));
313 if (equal_sets(setCoinsRet, setCoinsRet2))
314 fails++;
316 BOOST_CHECK_NE(fails, RANDOM_REPEATS);
318 // add 75 cents in small change. not enough to make 90 cents,
319 // then try making 90 cents. there are multiple competing "smallest bigger" coins,
320 // one of which should be picked at random
321 add_coin(5 * CENT);
322 add_coin(10 * CENT);
323 add_coin(15 * CENT);
324 add_coin(20 * CENT);
325 add_coin(25 * CENT);
327 fails = 0;
328 for (int j = 0; j < RANDOM_REPEATS; j++)
330 // selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of the time
331 // run the test RANDOM_REPEATS times and only complain if all of them fail
332 BOOST_CHECK(testWallet.SelectCoinsMinConf(90*CENT, 1, 6, 0, vCoins, setCoinsRet , nValueRet));
333 BOOST_CHECK(testWallet.SelectCoinsMinConf(90*CENT, 1, 6, 0, vCoins, setCoinsRet2, nValueRet));
334 if (equal_sets(setCoinsRet, setCoinsRet2))
335 fails++;
337 BOOST_CHECK_NE(fails, RANDOM_REPEATS);
340 empty_wallet();
343 BOOST_AUTO_TEST_CASE(ApproximateBestSubset)
345 CoinSet setCoinsRet;
346 CAmount nValueRet;
348 LOCK(testWallet.cs_wallet);
350 empty_wallet();
352 // Test vValue sort order
353 for (int i = 0; i < 1000; i++)
354 add_coin(1000 * COIN);
355 add_coin(3 * COIN);
357 BOOST_CHECK(testWallet.SelectCoinsMinConf(1003 * COIN, 1, 6, 0, vCoins, setCoinsRet, nValueRet));
358 BOOST_CHECK_EQUAL(nValueRet, 1003 * COIN);
359 BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U);
361 empty_wallet();
364 BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup)
366 LOCK(cs_main);
368 // Cap last block file size, and mine new block in a new block file.
369 CBlockIndex* const nullBlock = nullptr;
370 CBlockIndex* oldTip = chainActive.Tip();
371 GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE;
372 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
373 CBlockIndex* newTip = chainActive.Tip();
375 // Verify ScanForWalletTransactions picks up transactions in both the old
376 // and new block files.
378 CWallet wallet;
379 LOCK(wallet.cs_wallet);
380 wallet.AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
381 BOOST_CHECK_EQUAL(nullBlock, wallet.ScanForWalletTransactions(oldTip));
382 BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 100 * COIN);
385 // Prune the older block file.
386 PruneOneBlockFile(oldTip->GetBlockPos().nFile);
387 UnlinkPrunedFiles({oldTip->GetBlockPos().nFile});
389 // Verify ScanForWalletTransactions only picks transactions in the new block
390 // file.
392 CWallet wallet;
393 LOCK(wallet.cs_wallet);
394 wallet.AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
395 BOOST_CHECK_EQUAL(oldTip, wallet.ScanForWalletTransactions(oldTip));
396 BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 50 * COIN);
399 // Verify importmulti RPC returns failure for a key whose creation time is
400 // before the missing block, and success for a key whose creation time is
401 // after.
403 CWallet wallet;
404 CWallet *backup = ::pwalletMain;
405 ::pwalletMain = &wallet;
406 UniValue keys;
407 keys.setArray();
408 UniValue key;
409 key.setObject();
410 key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey())));
411 key.pushKV("timestamp", 0);
412 key.pushKV("internal", UniValue(true));
413 keys.push_back(key);
414 key.clear();
415 key.setObject();
416 CKey futureKey;
417 futureKey.MakeNewKey(true);
418 key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(futureKey.GetPubKey())));
419 key.pushKV("timestamp", newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1);
420 key.pushKV("internal", UniValue(true));
421 keys.push_back(key);
422 JSONRPCRequest request;
423 request.params.setArray();
424 request.params.push_back(keys);
426 UniValue response = importmulti(request);
427 BOOST_CHECK_EQUAL(response.write(),
428 strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":\"Rescan failed for key with creation "
429 "timestamp %d. There was an error reading a block from time %d, which is after or within %d "
430 "seconds of key creation, and could contain transactions pertaining to the key. As a result, "
431 "transactions and coins using this key may not appear in the wallet. This error could be caused "
432 "by pruning or data corruption (see bitcoind log for details) and could be dealt with by "
433 "downloading and rescanning the relevant blocks (see -reindex and -rescan "
434 "options).\"}},{\"success\":true}]",
435 0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW));
436 ::pwalletMain = backup;
440 // Verify importwallet RPC starts rescan at earliest block with timestamp
441 // greater or equal than key birthday. Previously there was a bug where
442 // importwallet RPC would start the scan at the latest block with timestamp less
443 // than or equal to key birthday.
444 BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup)
446 CWallet *pwalletMainBackup = ::pwalletMain;
447 LOCK(cs_main);
449 // Create two blocks with same timestamp to verify that importwallet rescan
450 // will pick up both blocks, not just the first.
451 const int64_t BLOCK_TIME = chainActive.Tip()->GetBlockTimeMax() + 5;
452 SetMockTime(BLOCK_TIME);
453 coinbaseTxns.emplace_back(*CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
454 coinbaseTxns.emplace_back(*CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
456 // Set key birthday to block time increased by the timestamp window, so
457 // rescan will start at the block time.
458 const int64_t KEY_TIME = BLOCK_TIME + TIMESTAMP_WINDOW;
459 SetMockTime(KEY_TIME);
460 coinbaseTxns.emplace_back(*CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
462 // Import key into wallet and call dumpwallet to create backup file.
464 CWallet wallet;
465 LOCK(wallet.cs_wallet);
466 wallet.mapKeyMetadata[coinbaseKey.GetPubKey().GetID()].nCreateTime = KEY_TIME;
467 wallet.AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
469 JSONRPCRequest request;
470 request.params.setArray();
471 request.params.push_back("wallet.backup");
472 ::pwalletMain = &wallet;
473 ::dumpwallet(request);
476 // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME
477 // were scanned, and no prior blocks were scanned.
479 CWallet wallet;
481 JSONRPCRequest request;
482 request.params.setArray();
483 request.params.push_back("wallet.backup");
484 ::pwalletMain = &wallet;
485 ::importwallet(request);
487 BOOST_CHECK_EQUAL(wallet.mapWallet.size(), 3);
488 BOOST_CHECK_EQUAL(coinbaseTxns.size(), 103);
489 for (size_t i = 0; i < coinbaseTxns.size(); ++i) {
490 bool found = wallet.GetWalletTx(coinbaseTxns[i].GetHash());
491 bool expected = i >= 100;
492 BOOST_CHECK_EQUAL(found, expected);
496 SetMockTime(0);
497 ::pwalletMain = pwalletMainBackup;
500 // Check that GetImmatureCredit() returns a newly calculated value instead of
501 // the cached value after a MarkDirty() call.
503 // This is a regression test written to verify a bugfix for the immature credit
504 // function. Similar tests probably should be written for the other credit and
505 // debit functions.
506 BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup)
508 CWallet wallet;
509 CWalletTx wtx(&wallet, MakeTransactionRef(coinbaseTxns.back()));
510 LOCK2(cs_main, wallet.cs_wallet);
511 wtx.hashBlock = chainActive.Tip()->GetBlockHash();
512 wtx.nIndex = 0;
514 // Call GetImmatureCredit() once before adding the key to the wallet to
515 // cache the current immature credit amount, which is 0.
516 BOOST_CHECK_EQUAL(wtx.GetImmatureCredit(), 0);
518 // Invalidate the cached value, add the key, and make sure a new immature
519 // credit amount is calculated.
520 wtx.MarkDirty();
521 wallet.AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
522 BOOST_CHECK_EQUAL(wtx.GetImmatureCredit(), 50*COIN);
525 static int64_t AddTx(CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
527 CMutableTransaction tx;
528 tx.nLockTime = lockTime;
529 SetMockTime(mockTime);
530 CBlockIndex* block = nullptr;
531 if (blockTime > 0) {
532 auto inserted = mapBlockIndex.emplace(GetRandHash(), new CBlockIndex);
533 assert(inserted.second);
534 const uint256& hash = inserted.first->first;
535 block = inserted.first->second;
536 block->nTime = blockTime;
537 block->phashBlock = &hash;
540 CWalletTx wtx(&wallet, MakeTransactionRef(tx));
541 if (block) {
542 wtx.SetMerkleBranch(block, 0);
544 wallet.AddToWallet(wtx);
545 return wallet.mapWallet.at(wtx.GetHash()).nTimeSmart;
548 // Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
549 // expanded to cover more corner cases of smart time logic.
550 BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
552 CWallet wallet;
554 // New transaction should use clock time if lower than block time.
555 BOOST_CHECK_EQUAL(AddTx(wallet, 1, 100, 120), 100);
557 // Test that updating existing transaction does not change smart time.
558 BOOST_CHECK_EQUAL(AddTx(wallet, 1, 200, 220), 100);
560 // New transaction should use clock time if there's no block time.
561 BOOST_CHECK_EQUAL(AddTx(wallet, 2, 300, 0), 300);
563 // New transaction should use block time if lower than clock time.
564 BOOST_CHECK_EQUAL(AddTx(wallet, 3, 420, 400), 400);
566 // New transaction should use latest entry time if higher than
567 // min(block time, clock time).
568 BOOST_CHECK_EQUAL(AddTx(wallet, 4, 500, 390), 400);
570 // If there are future entries, new transaction should use time of the
571 // newest entry that is no more than 300 seconds ahead of the clock time.
572 BOOST_CHECK_EQUAL(AddTx(wallet, 5, 50, 600), 300);
574 // Reset mock time for other tests.
575 SetMockTime(0);
578 BOOST_AUTO_TEST_CASE(LoadReceiveRequests)
580 CTxDestination dest = CKeyID();
581 pwalletMain->AddDestData(dest, "misc", "val_misc");
582 pwalletMain->AddDestData(dest, "rr0", "val_rr0");
583 pwalletMain->AddDestData(dest, "rr1", "val_rr1");
585 auto values = pwalletMain->GetDestValues("rr");
586 BOOST_CHECK_EQUAL(values.size(), 2);
587 BOOST_CHECK_EQUAL(values[0], "val_rr0");
588 BOOST_CHECK_EQUAL(values[1], "val_rr1");
591 class ListCoinsTestingSetup : public TestChain100Setup
593 public:
594 ListCoinsTestingSetup()
596 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
597 ::bitdb.MakeMock();
598 wallet.reset(new CWallet(std::unique_ptr<CWalletDBWrapper>(new CWalletDBWrapper(&bitdb, "wallet_test.dat"))));
599 bool firstRun;
600 wallet->LoadWallet(firstRun);
601 LOCK(wallet->cs_wallet);
602 wallet->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
603 wallet->ScanForWalletTransactions(chainActive.Genesis());
606 ~ListCoinsTestingSetup()
608 wallet.reset();
609 ::bitdb.Flush(true);
610 ::bitdb.Reset();
613 CWalletTx& AddTx(CRecipient recipient)
615 CWalletTx wtx;
616 CReserveKey reservekey(wallet.get());
617 CAmount fee;
618 int changePos = -1;
619 std::string error;
620 BOOST_CHECK(wallet->CreateTransaction({recipient}, wtx, reservekey, fee, changePos, error));
621 CValidationState state;
622 BOOST_CHECK(wallet->CommitTransaction(wtx, reservekey, nullptr, state));
623 auto it = wallet->mapWallet.find(wtx.GetHash());
624 BOOST_CHECK(it != wallet->mapWallet.end());
625 CreateAndProcessBlock({CMutableTransaction(*it->second.tx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
626 it->second.SetMerkleBranch(chainActive.Tip(), 1);
627 return it->second;
630 std::unique_ptr<CWallet> wallet;
633 BOOST_FIXTURE_TEST_CASE(ListCoins, ListCoinsTestingSetup)
635 std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
636 LOCK(wallet->cs_wallet);
638 // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
639 // address.
640 auto list = wallet->ListCoins();
641 BOOST_CHECK_EQUAL(list.size(), 1);
642 BOOST_CHECK_EQUAL(boost::get<CKeyID>(list.begin()->first).ToString(), coinbaseAddress);
643 BOOST_CHECK_EQUAL(list.begin()->second.size(), 1);
645 // Check initial balance from one mature coinbase transaction.
646 BOOST_CHECK_EQUAL(50 * COIN, wallet->GetAvailableBalance());
648 // Add a transaction creating a change address, and confirm ListCoins still
649 // returns the coin associated with the change address underneath the
650 // coinbaseKey pubkey, even though the change address has a different
651 // pubkey.
652 AddTx(CRecipient{GetScriptForRawPubKey({}), 1 * COIN, false /* subtract fee */});
653 list = wallet->ListCoins();
654 BOOST_CHECK_EQUAL(list.size(), 1);
655 BOOST_CHECK_EQUAL(boost::get<CKeyID>(list.begin()->first).ToString(), coinbaseAddress);
656 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2);
658 // Lock both coins. Confirm number of available coins drops to 0.
659 std::vector<COutput> available;
660 wallet->AvailableCoins(available);
661 BOOST_CHECK_EQUAL(available.size(), 2);
662 for (const auto& group : list) {
663 for (const auto& coin : group.second) {
664 wallet->LockCoin(COutPoint(coin.tx->GetHash(), coin.i));
667 wallet->AvailableCoins(available);
668 BOOST_CHECK_EQUAL(available.size(), 0);
670 // Confirm ListCoins still returns same result as before, despite coins
671 // being locked.
672 list = wallet->ListCoins();
673 BOOST_CHECK_EQUAL(list.size(), 1);
674 BOOST_CHECK_EQUAL(boost::get<CKeyID>(list.begin()->first).ToString(), coinbaseAddress);
675 BOOST_CHECK_EQUAL(list.begin()->second.size(), 2);
678 BOOST_AUTO_TEST_SUITE_END()