1 // Copyright (c) 2012-2020 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <wallet/wallet.h>
6 
7 #include <future>
8 #include <memory>
9 #include <stdint.h>
10 #include <vector>
11 
12 #include <interfaces/chain.h>
13 #include <node/context.h>
14 #include <policy/policy.h>
15 #include <rpc/server.h>
16 #include <test/util/logging.h>
17 #include <test/util/setup_common.h>
18 #include <util/ref.h>
19 #include <util/translation.h>
20 #include <validation.h>
21 #include <wallet/coincontrol.h>
22 #include <wallet/test/wallet_test_fixture.h>
23 
24 #include <boost/test/unit_test.hpp>
25 #include <univalue.h>
26 
27 RPCHelpMan importmulti();
28 RPCHelpMan dumpwallet();
29 RPCHelpMan importwallet();
30 
31 // Ensure that fee levels defined in the wallet are at least as high
32 // as the default levels for node policy.
33 static_assert(DEFAULT_TRANSACTION_MINFEE >= DEFAULT_MIN_RELAY_TX_FEE, "wallet minimum fee is smaller than default relay fee");
34 static_assert(WALLET_INCREMENTAL_RELAY_FEE >= DEFAULT_INCREMENTAL_RELAY_FEE, "wallet incremental fee is smaller than default incremental relay fee");
35 
BOOST_FIXTURE_TEST_SUITE(wallet_tests,WalletTestingSetup)36 BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
37 
38 static std::shared_ptr<CWallet> TestLoadWallet(interfaces::Chain& chain)
39 {
40     DatabaseOptions options;
41     DatabaseStatus status;
42     bilingual_str error;
43     std::vector<bilingual_str> warnings;
44     auto database = MakeWalletDatabase("", options, status, error);
45     auto wallet = CWallet::Create(chain, "", std::move(database), options.create_flags, error, warnings);
46     wallet->postInitProcess();
47     return wallet;
48 }
49 
TestUnloadWallet(std::shared_ptr<CWallet> && wallet)50 static void TestUnloadWallet(std::shared_ptr<CWallet>&& wallet)
51 {
52     SyncWithValidationInterfaceQueue();
53     wallet->m_chain_notifications_handler.reset();
54     UnloadWallet(std::move(wallet));
55 }
56 
TestSimpleSpend(const CTransaction & from,uint32_t index,const CKey & key,const CScript & pubkey)57 static CMutableTransaction TestSimpleSpend(const CTransaction& from, uint32_t index, const CKey& key, const CScript& pubkey)
58 {
59     CMutableTransaction mtx;
60     mtx.vout.push_back({from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey});
61     mtx.vin.push_back({CTxIn{from.GetHash(), index}});
62     FillableSigningProvider keystore;
63     keystore.AddKey(key);
64     std::map<COutPoint, Coin> coins;
65     coins[mtx.vin[0].prevout].out = from.vout[index];
66     std::map<int, std::string> input_errors;
67     BOOST_CHECK(SignTransaction(mtx, &keystore, coins, SIGHASH_ALL, input_errors));
68     return mtx;
69 }
70 
AddKey(CWallet & wallet,const CKey & key)71 static void AddKey(CWallet& wallet, const CKey& key)
72 {
73     auto spk_man = wallet.GetOrCreateLegacyScriptPubKeyMan();
74     LOCK2(wallet.cs_wallet, spk_man->cs_KeyStore);
75     spk_man->AddKeyPubKey(key, key.GetPubKey());
76 }
77 
BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions,TestChain100Setup)78 BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
79 {
80     // Cap last block file size, and mine new block in a new block file.
81     CBlockIndex* oldTip = ::ChainActive().Tip();
82     GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE;
83     CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
84     CBlockIndex* newTip = ::ChainActive().Tip();
85 
86     NodeContext node;
87     auto chain = interfaces::MakeChain(node);
88 
89     // Verify ScanForWalletTransactions fails to read an unknown start block.
90     {
91         CWallet wallet(chain.get(), "", CreateDummyWalletDatabase());
92         {
93             LOCK(wallet.cs_wallet);
94             wallet.SetLastBlockProcessed(::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash());
95         }
96         AddKey(wallet, coinbaseKey);
97         WalletRescanReserver reserver(wallet);
98         reserver.reserve();
99         CWallet::ScanResult result = wallet.ScanForWalletTransactions({} /* start_block */, 0 /* start_height */, {} /* max_height */, reserver, false /* update */);
100         BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::FAILURE);
101         BOOST_CHECK(result.last_failed_block.IsNull());
102         BOOST_CHECK(result.last_scanned_block.IsNull());
103         BOOST_CHECK(!result.last_scanned_height);
104         BOOST_CHECK_EQUAL(wallet.GetBalance().m_mine_immature, 0);
105     }
106 
107     // Verify ScanForWalletTransactions picks up transactions in both the old
108     // and new block files.
109     {
110         CWallet wallet(chain.get(), "", CreateDummyWalletDatabase());
111         {
112             LOCK(wallet.cs_wallet);
113             wallet.SetLastBlockProcessed(::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash());
114         }
115         AddKey(wallet, coinbaseKey);
116         WalletRescanReserver reserver(wallet);
117         reserver.reserve();
118         CWallet::ScanResult result = wallet.ScanForWalletTransactions(oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */, reserver, false /* update */);
119         BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::SUCCESS);
120         BOOST_CHECK(result.last_failed_block.IsNull());
121         BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
122         BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
123         BOOST_CHECK_EQUAL(wallet.GetBalance().m_mine_immature, 100 * COIN);
124     }
125 
126     // Prune the older block file.
127     {
128         LOCK(cs_main);
129         Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(oldTip->GetBlockPos().nFile);
130     }
131     UnlinkPrunedFiles({oldTip->GetBlockPos().nFile});
132 
133     // Verify ScanForWalletTransactions only picks transactions in the new block
134     // file.
135     {
136         CWallet wallet(chain.get(), "", CreateDummyWalletDatabase());
137         {
138             LOCK(wallet.cs_wallet);
139             wallet.SetLastBlockProcessed(::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash());
140         }
141         AddKey(wallet, coinbaseKey);
142         WalletRescanReserver reserver(wallet);
143         reserver.reserve();
144         CWallet::ScanResult result = wallet.ScanForWalletTransactions(oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */, reserver, false /* update */);
145         BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::FAILURE);
146         BOOST_CHECK_EQUAL(result.last_failed_block, oldTip->GetBlockHash());
147         BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
148         BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
149         BOOST_CHECK_EQUAL(wallet.GetBalance().m_mine_immature, 50 * COIN);
150     }
151 
152     // Prune the remaining block file.
153     {
154         LOCK(cs_main);
155         Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(newTip->GetBlockPos().nFile);
156     }
157     UnlinkPrunedFiles({newTip->GetBlockPos().nFile});
158 
159     // Verify ScanForWalletTransactions scans no blocks.
160     {
161         CWallet wallet(chain.get(), "", CreateDummyWalletDatabase());
162         {
163             LOCK(wallet.cs_wallet);
164             wallet.SetLastBlockProcessed(::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash());
165         }
166         AddKey(wallet, coinbaseKey);
167         WalletRescanReserver reserver(wallet);
168         reserver.reserve();
169         CWallet::ScanResult result = wallet.ScanForWalletTransactions(oldTip->GetBlockHash(), oldTip->nHeight, {} /* max_height */, reserver, false /* update */);
170         BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::FAILURE);
171         BOOST_CHECK_EQUAL(result.last_failed_block, newTip->GetBlockHash());
172         BOOST_CHECK(result.last_scanned_block.IsNull());
173         BOOST_CHECK(!result.last_scanned_height);
174         BOOST_CHECK_EQUAL(wallet.GetBalance().m_mine_immature, 0);
175     }
176 }
177 
BOOST_FIXTURE_TEST_CASE(importmulti_rescan,TestChain100Setup)178 BOOST_FIXTURE_TEST_CASE(importmulti_rescan, TestChain100Setup)
179 {
180     // Cap last block file size, and mine new block in a new block file.
181     CBlockIndex* oldTip = ::ChainActive().Tip();
182     GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE;
183     CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
184     CBlockIndex* newTip = ::ChainActive().Tip();
185 
186     NodeContext node;
187     auto chain = interfaces::MakeChain(node);
188 
189     // Prune the older block file.
190     {
191         LOCK(cs_main);
192         Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(oldTip->GetBlockPos().nFile);
193     }
194     UnlinkPrunedFiles({oldTip->GetBlockPos().nFile});
195 
196     // Verify importmulti RPC returns failure for a key whose creation time is
197     // before the missing block, and success for a key whose creation time is
198     // after.
199     {
200         std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(chain.get(), "", CreateDummyWalletDatabase());
201         wallet->SetupLegacyScriptPubKeyMan();
202         WITH_LOCK(wallet->cs_wallet, wallet->SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash()));
203         AddWallet(wallet);
204         UniValue keys;
205         keys.setArray();
206         UniValue key;
207         key.setObject();
208         key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey())));
209         key.pushKV("timestamp", 0);
210         key.pushKV("internal", UniValue(true));
211         keys.push_back(key);
212         key.clear();
213         key.setObject();
214         CKey futureKey;
215         futureKey.MakeNewKey(true);
216         key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(futureKey.GetPubKey())));
217         key.pushKV("timestamp", newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1);
218         key.pushKV("internal", UniValue(true));
219         keys.push_back(key);
220         util::Ref context;
221         JSONRPCRequest request(context);
222         request.params.setArray();
223         request.params.push_back(keys);
224 
225         UniValue response = importmulti().HandleRequest(request);
226         BOOST_CHECK_EQUAL(response.write(),
227             strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":\"Rescan failed for key with creation "
228                       "timestamp %d. There was an error reading a block from time %d, which is after or within %d "
229                       "seconds of key creation, and could contain transactions pertaining to the key. As a result, "
230                       "transactions and coins using this key may not appear in the wallet. This error could be caused "
231                       "by pruning or data corruption (see namecoind log for details) and could be dealt with by "
232                       "downloading and rescanning the relevant blocks (see -reindex and -rescan "
233                       "options).\"}},{\"success\":true}]",
234                               0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW));
235         RemoveWallet(wallet, nullopt);
236     }
237 }
238 
239 // Verify importwallet RPC starts rescan at earliest block with timestamp
240 // greater or equal than key birthday. Previously there was a bug where
241 // importwallet RPC would start the scan at the latest block with timestamp less
242 // than or equal to key birthday.
BOOST_FIXTURE_TEST_CASE(importwallet_rescan,TestChain100Setup)243 BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup)
244 {
245     // Create two blocks with same timestamp to verify that importwallet rescan
246     // will pick up both blocks, not just the first.
247     const int64_t BLOCK_TIME = ::ChainActive().Tip()->GetBlockTimeMax() + 5;
248     SetMockTime(BLOCK_TIME);
249     m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
250     m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
251 
252     // Set key birthday to block time increased by the timestamp window, so
253     // rescan will start at the block time.
254     const int64_t KEY_TIME = BLOCK_TIME + TIMESTAMP_WINDOW;
255     SetMockTime(KEY_TIME);
256     m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
257 
258     NodeContext node;
259     auto chain = interfaces::MakeChain(node);
260 
261     std::string backup_file = (GetDataDir() / "wallet.backup").string();
262 
263     // Import key into wallet and call dumpwallet to create backup file.
264     {
265         std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(chain.get(), "", CreateDummyWalletDatabase());
266         {
267             auto spk_man = wallet->GetOrCreateLegacyScriptPubKeyMan();
268             LOCK2(wallet->cs_wallet, spk_man->cs_KeyStore);
269             spk_man->mapKeyMetadata[coinbaseKey.GetPubKey().GetID()].nCreateTime = KEY_TIME;
270             spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
271 
272             AddWallet(wallet);
273             wallet->SetLastBlockProcessed(::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash());
274         }
275         util::Ref context;
276         JSONRPCRequest request(context);
277         request.params.setArray();
278         request.params.push_back(backup_file);
279 
280         ::dumpwallet().HandleRequest(request);
281         RemoveWallet(wallet, nullopt);
282     }
283 
284     // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME
285     // were scanned, and no prior blocks were scanned.
286     {
287         std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(chain.get(), "", CreateDummyWalletDatabase());
288         LOCK(wallet->cs_wallet);
289         wallet->SetupLegacyScriptPubKeyMan();
290 
291         util::Ref context;
292         JSONRPCRequest request(context);
293         request.params.setArray();
294         request.params.push_back(backup_file);
295         AddWallet(wallet);
296         wallet->SetLastBlockProcessed(::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash());
297         ::importwallet().HandleRequest(request);
298         RemoveWallet(wallet, nullopt);
299 
300         BOOST_CHECK_EQUAL(wallet->mapWallet.size(), 3U);
301         BOOST_CHECK_EQUAL(m_coinbase_txns.size(), 103U);
302         for (size_t i = 0; i < m_coinbase_txns.size(); ++i) {
303             bool found = wallet->GetWalletTx(m_coinbase_txns[i]->GetHash());
304             bool expected = i >= 100;
305             BOOST_CHECK_EQUAL(found, expected);
306         }
307     }
308 
309     SetMockTime(0);
310 }
311 
312 // Check that GetImmatureCredit() returns a newly calculated value instead of
313 // the cached value after a MarkDirty() call.
314 //
315 // This is a regression test written to verify a bugfix for the immature credit
316 // function. Similar tests probably should be written for the other credit and
317 // debit functions.
BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit,TestChain100Setup)318 BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup)
319 {
320     NodeContext node;
321     auto chain = interfaces::MakeChain(node);
322 
323     CWallet wallet(chain.get(), "", CreateDummyWalletDatabase());
324     auto spk_man = wallet.GetOrCreateLegacyScriptPubKeyMan();
325     CWalletTx wtx(&wallet, m_coinbase_txns.back());
326 
327     LOCK2(wallet.cs_wallet, spk_man->cs_KeyStore);
328     wallet.SetLastBlockProcessed(::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash());
329 
330     CWalletTx::Confirmation confirm(CWalletTx::Status::CONFIRMED, ::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash(), 0);
331     wtx.m_confirm = confirm;
332 
333     // Call GetImmatureCredit() once before adding the key to the wallet to
334     // cache the current immature credit amount, which is 0.
335     BOOST_CHECK_EQUAL(wtx.GetImmatureCredit(), 0);
336 
337     // Invalidate the cached value, add the key, and make sure a new immature
338     // credit amount is calculated.
339     wtx.MarkDirty();
340     BOOST_CHECK(spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey()));
341     BOOST_CHECK_EQUAL(wtx.GetImmatureCredit(), 50*COIN);
342 }
343 
AddTx(ChainstateManager & chainman,CWallet & wallet,uint32_t lockTime,int64_t mockTime,int64_t blockTime)344 static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
345 {
346     CMutableTransaction tx;
347     CWalletTx::Confirmation confirm;
348     tx.nLockTime = lockTime;
349     SetMockTime(mockTime);
350     CBlockIndex* block = nullptr;
351     if (blockTime > 0) {
352         LOCK(cs_main);
353         auto inserted = chainman.BlockIndex().emplace(GetRandHash(), new CBlockIndex);
354         assert(inserted.second);
355         const uint256& hash = inserted.first->first;
356         block = inserted.first->second;
357         block->nTime = blockTime;
358         block->phashBlock = &hash;
359         confirm = {CWalletTx::Status::CONFIRMED, block->nHeight, hash, 0};
360     }
361 
362     // If transaction is already in map, to avoid inconsistencies, unconfirmation
363     // is needed before confirm again with different block.
364     return wallet.AddToWallet(MakeTransactionRef(tx), confirm, [&](CWalletTx& wtx, bool /* new_tx */) {
365         wtx.setUnconfirmed();
366         return true;
367     })->nTimeSmart;
368 }
369 
370 // Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
371 // expanded to cover more corner cases of smart time logic.
BOOST_AUTO_TEST_CASE(ComputeTimeSmart)372 BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
373 {
374     // New transaction should use clock time if lower than block time.
375     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100, 120), 100);
376 
377     // Test that updating existing transaction does not change smart time.
378     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200, 220), 100);
379 
380     // New transaction should use clock time if there's no block time.
381     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300, 0), 300);
382 
383     // New transaction should use block time if lower than clock time.
384     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420, 400), 400);
385 
386     // New transaction should use latest entry time if higher than
387     // min(block time, clock time).
388     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500, 390), 400);
389 
390     // If there are future entries, new transaction should use time of the
391     // newest entry that is no more than 300 seconds ahead of the clock time.
392     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50, 600), 300);
393 
394     // Reset mock time for other tests.
395     SetMockTime(0);
396 }
397 
BOOST_AUTO_TEST_CASE(LoadReceiveRequests)398 BOOST_AUTO_TEST_CASE(LoadReceiveRequests)
399 {
400     CTxDestination dest = PKHash();
401     LOCK(m_wallet.cs_wallet);
402     WalletBatch batch{m_wallet.GetDatabase()};
403     m_wallet.AddDestData(batch, dest, "misc", "val_misc");
404     m_wallet.AddDestData(batch, dest, "rr0", "val_rr0");
405     m_wallet.AddDestData(batch, dest, "rr1", "val_rr1");
406 
407     auto values = m_wallet.GetDestValues("rr");
408     BOOST_CHECK_EQUAL(values.size(), 2U);
409     BOOST_CHECK_EQUAL(values[0], "val_rr0");
410     BOOST_CHECK_EQUAL(values[1], "val_rr1");
411 }
412 
413 // Test some watch-only LegacyScriptPubKeyMan methods by the procedure of loading (LoadWatchOnly),
414 // checking (HaveWatchOnly), getting (GetWatchPubKey) and removing (RemoveWatchOnly) a
415 // given PubKey, resp. its corresponding P2PK Script. Results of the the impact on
416 // the address -> PubKey map is dependent on whether the PubKey is a point on the curve
TestWatchOnlyPubKey(LegacyScriptPubKeyMan * spk_man,const CPubKey & add_pubkey)417 static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan* spk_man, const CPubKey& add_pubkey)
418 {
419     CScript p2pk = GetScriptForRawPubKey(add_pubkey);
420     CKeyID add_address = add_pubkey.GetID();
421     CPubKey found_pubkey;
422     LOCK(spk_man->cs_KeyStore);
423 
424     // all Scripts (i.e. also all PubKeys) are added to the general watch-only set
425     BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
426     spk_man->LoadWatchOnly(p2pk);
427     BOOST_CHECK(spk_man->HaveWatchOnly(p2pk));
428 
429     // only PubKeys on the curve shall be added to the watch-only address -> PubKey map
430     bool is_pubkey_fully_valid = add_pubkey.IsFullyValid();
431     if (is_pubkey_fully_valid) {
432         BOOST_CHECK(spk_man->GetWatchPubKey(add_address, found_pubkey));
433         BOOST_CHECK(found_pubkey == add_pubkey);
434     } else {
435         BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
436         BOOST_CHECK(found_pubkey == CPubKey()); // passed key is unchanged
437     }
438 
439     spk_man->RemoveWatchOnly(p2pk);
440     BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
441 
442     if (is_pubkey_fully_valid) {
443         BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
444         BOOST_CHECK(found_pubkey == add_pubkey); // passed key is unchanged
445     }
446 }
447 
448 // Cryptographically invalidate a PubKey whilst keeping length and first byte
PollutePubKey(CPubKey & pubkey)449 static void PollutePubKey(CPubKey& pubkey)
450 {
451     std::vector<unsigned char> pubkey_raw(pubkey.begin(), pubkey.end());
452     std::fill(pubkey_raw.begin()+1, pubkey_raw.end(), 0);
453     pubkey = CPubKey(pubkey_raw);
454     assert(!pubkey.IsFullyValid());
455     assert(pubkey.IsValid());
456 }
457 
458 // Test watch-only logic for PubKeys
BOOST_AUTO_TEST_CASE(WatchOnlyPubKeys)459 BOOST_AUTO_TEST_CASE(WatchOnlyPubKeys)
460 {
461     CKey key;
462     CPubKey pubkey;
463     LegacyScriptPubKeyMan* spk_man = m_wallet.GetOrCreateLegacyScriptPubKeyMan();
464 
465     BOOST_CHECK(!spk_man->HaveWatchOnly());
466 
467     // uncompressed valid PubKey
468     key.MakeNewKey(false);
469     pubkey = key.GetPubKey();
470     assert(!pubkey.IsCompressed());
471     TestWatchOnlyPubKey(spk_man, pubkey);
472 
473     // uncompressed cryptographically invalid PubKey
474     PollutePubKey(pubkey);
475     TestWatchOnlyPubKey(spk_man, pubkey);
476 
477     // compressed valid PubKey
478     key.MakeNewKey(true);
479     pubkey = key.GetPubKey();
480     assert(pubkey.IsCompressed());
481     TestWatchOnlyPubKey(spk_man, pubkey);
482 
483     // compressed cryptographically invalid PubKey
484     PollutePubKey(pubkey);
485     TestWatchOnlyPubKey(spk_man, pubkey);
486 
487     // invalid empty PubKey
488     pubkey = CPubKey();
489     TestWatchOnlyPubKey(spk_man, pubkey);
490 }
491 
492 class ListCoinsTestingSetup : public TestChain100Setup
493 {
494 public:
ListCoinsTestingSetup()495     ListCoinsTestingSetup()
496     {
497         CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
498         wallet = MakeUnique<CWallet>(m_chain.get(), "", CreateMockWalletDatabase());
499         {
500             LOCK2(wallet->cs_wallet, ::cs_main);
501             wallet->SetLastBlockProcessed(::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash());
502         }
503         bool firstRun;
504         wallet->LoadWallet(firstRun);
505         AddKey(*wallet, coinbaseKey);
506         WalletRescanReserver reserver(*wallet);
507         reserver.reserve();
508         CWallet::ScanResult result = wallet->ScanForWalletTransactions(::ChainActive().Genesis()->GetBlockHash(), 0 /* start_height */, {} /* max_height */, reserver, false /* update */);
509         BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::SUCCESS);
510         BOOST_CHECK_EQUAL(result.last_scanned_block, ::ChainActive().Tip()->GetBlockHash());
511         BOOST_CHECK_EQUAL(*result.last_scanned_height, ::ChainActive().Height());
512         BOOST_CHECK(result.last_failed_block.IsNull());
513     }
514 
~ListCoinsTestingSetup()515     ~ListCoinsTestingSetup()
516     {
517         wallet.reset();
518     }
519 
AddTx(CRecipient recipient)520     CWalletTx& AddTx(CRecipient recipient)
521     {
522         CTransactionRef tx;
523         CAmount fee;
524         int changePos = -1;
525         bilingual_str error;
526         CCoinControl dummy;
527         FeeCalculation fee_calc_out;
528         {
529             BOOST_CHECK(wallet->CreateTransaction({recipient}, nullptr, tx, fee, changePos, error, dummy, fee_calc_out));
530         }
531         wallet->CommitTransaction(tx, {}, {});
532         CMutableTransaction blocktx;
533         {
534             LOCK(wallet->cs_wallet);
535             blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).tx);
536         }
537         CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
538 
539         LOCK(wallet->cs_wallet);
540         wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, ::ChainActive().Tip()->GetBlockHash());
541         auto it = wallet->mapWallet.find(tx->GetHash());
542         BOOST_CHECK(it != wallet->mapWallet.end());
543         CWalletTx::Confirmation confirm(CWalletTx::Status::CONFIRMED, ::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash(), 1);
544         it->second.m_confirm = confirm;
545         return it->second;
546     }
547 
548     std::unique_ptr<interfaces::Chain> m_chain = interfaces::MakeChain(m_node);
549     std::unique_ptr<CWallet> wallet;
550 };
551 
BOOST_FIXTURE_TEST_CASE(ListCoins,ListCoinsTestingSetup)552 BOOST_FIXTURE_TEST_CASE(ListCoins, ListCoinsTestingSetup)
553 {
554     std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
555 
556     // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
557     // address.
558     std::map<CTxDestination, std::vector<COutput>> list;
559     {
560         LOCK(wallet->cs_wallet);
561         list = wallet->ListCoins();
562     }
563     BOOST_CHECK_EQUAL(list.size(), 1U);
564     BOOST_CHECK_EQUAL(boost::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
565     BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
566 
567     // Check initial balance from one mature coinbase transaction.
568     BOOST_CHECK_EQUAL(50 * COIN, wallet->GetAvailableBalance());
569 
570     // Add a transaction creating a change address, and confirm ListCoins still
571     // returns the coin associated with the change address underneath the
572     // coinbaseKey pubkey, even though the change address has a different
573     // pubkey.
574     AddTx(CRecipient{GetScriptForRawPubKey({}), 1 * COIN, false /* subtract fee */});
575     {
576         LOCK(wallet->cs_wallet);
577         list = wallet->ListCoins();
578     }
579     BOOST_CHECK_EQUAL(list.size(), 1U);
580     BOOST_CHECK_EQUAL(boost::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
581     BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
582 
583     // Lock both coins. Confirm number of available coins drops to 0.
584     {
585         LOCK(wallet->cs_wallet);
586         std::vector<COutput> available;
587         wallet->AvailableCoins(available);
588         BOOST_CHECK_EQUAL(available.size(), 2U);
589     }
590     for (const auto& group : list) {
591         for (const auto& coin : group.second) {
592             LOCK(wallet->cs_wallet);
593             wallet->LockCoin(COutPoint(coin.tx->GetHash(), coin.i));
594         }
595     }
596     {
597         LOCK(wallet->cs_wallet);
598         std::vector<COutput> available;
599         wallet->AvailableCoins(available);
600         BOOST_CHECK_EQUAL(available.size(), 0U);
601     }
602     // Confirm ListCoins still returns same result as before, despite coins
603     // being locked.
604     {
605         LOCK(wallet->cs_wallet);
606         list = wallet->ListCoins();
607     }
608     BOOST_CHECK_EQUAL(list.size(), 1U);
609     BOOST_CHECK_EQUAL(boost::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
610     BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
611 }
612 
BOOST_FIXTURE_TEST_CASE(wallet_disableprivkeys,TestChain100Setup)613 BOOST_FIXTURE_TEST_CASE(wallet_disableprivkeys, TestChain100Setup)
614 {
615     NodeContext node;
616     auto chain = interfaces::MakeChain(node);
617     std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(chain.get(), "", CreateDummyWalletDatabase());
618     wallet->SetupLegacyScriptPubKeyMan();
619     wallet->SetMinVersion(FEATURE_LATEST);
620     wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
621     BOOST_CHECK(!wallet->TopUpKeyPool(1000));
622     CTxDestination dest;
623     std::string error;
624     BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, "", dest, error));
625 }
626 
627 // Explicit calculation which is used to test the wallet constant
628 // We get the same virtual size due to rounding(weight/4) for both use_max_sig values
CalculateNestedKeyhashInputSize(bool use_max_sig)629 static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
630 {
631     // Generate ephemeral valid pubkey
632     CKey key;
633     key.MakeNewKey(true);
634     CPubKey pubkey = key.GetPubKey();
635 
636     // Generate pubkey hash
637     uint160 key_hash(Hash160(pubkey));
638 
639     // Create inner-script to enter into keystore. Key hash can't be 0...
640     CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end());
641 
642     // Create outer P2SH script for the output
643     uint160 script_id(Hash160(inner_script));
644     CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL;
645 
646     // Add inner-script to key store and key to watchonly
647     FillableSigningProvider keystore;
648     keystore.AddCScript(inner_script);
649     keystore.AddKeyPubKey(key, pubkey);
650 
651     // Fill in dummy signatures for fee calculation.
652     SignatureData sig_data;
653 
654     if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) {
655         // We're hand-feeding it correct arguments; shouldn't happen
656         assert(false);
657     }
658 
659     CTxIn tx_in;
660     UpdateInput(tx_in, sig_data);
661     return (size_t)GetVirtualTransactionInputSize(tx_in);
662 }
663 
BOOST_FIXTURE_TEST_CASE(dummy_input_size_test,TestChain100Setup)664 BOOST_FIXTURE_TEST_CASE(dummy_input_size_test, TestChain100Setup)
665 {
666     BOOST_CHECK_EQUAL(CalculateNestedKeyhashInputSize(false), DUMMY_NESTED_P2WPKH_INPUT_SIZE);
667     BOOST_CHECK_EQUAL(CalculateNestedKeyhashInputSize(true), DUMMY_NESTED_P2WPKH_INPUT_SIZE);
668 }
669 
malformed_descriptor(std::ios_base::failure e)670 bool malformed_descriptor(std::ios_base::failure e)
671 {
672     std::string s(e.what());
673     return s.find("Missing checksum") != std::string::npos;
674 }
675 
BOOST_FIXTURE_TEST_CASE(wallet_descriptor_test,BasicTestingSetup)676 BOOST_FIXTURE_TEST_CASE(wallet_descriptor_test, BasicTestingSetup)
677 {
678     std::vector<unsigned char> malformed_record;
679     CVectorWriter vw(0, 0, malformed_record, 0);
680     vw << std::string("notadescriptor");
681     vw << (uint64_t)0;
682     vw << (int32_t)0;
683     vw << (int32_t)0;
684     vw << (int32_t)1;
685 
686     VectorReader vr(0, 0, malformed_record, 0);
687     WalletDescriptor w_desc;
688     BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure, malformed_descriptor);
689 }
690 
691 //! Test CWallet::Create() and its behavior handling potential race
692 //! conditions if it's called the same time an incoming transaction shows up in
693 //! the mempool or a new block.
694 //!
695 //! It isn't possible to verify there aren't race condition in every case, so
696 //! this test just checks two specific cases and ensures that timing of
697 //! notifications in these cases doesn't prevent the wallet from detecting
698 //! transactions.
699 //!
700 //! In the first case, block and mempool transactions are created before the
701 //! wallet is loaded, but notifications about these transactions are delayed
702 //! until after it is loaded. The notifications are superfluous in this case, so
703 //! the test verifies the transactions are detected before they arrive.
704 //!
705 //! In the second case, block and mempool transactions are created after the
706 //! wallet rescan and notifications are immediately synced, to verify the wallet
707 //! must already have a handler in place for them, and there's no gap after
708 //! rescanning where new transactions in new blocks could be lost.
BOOST_FIXTURE_TEST_CASE(CreateWallet,TestChain100Setup)709 BOOST_FIXTURE_TEST_CASE(CreateWallet, TestChain100Setup)
710 {
711     // Create new wallet with known key and unload it.
712     auto chain = interfaces::MakeChain(m_node);
713     auto wallet = TestLoadWallet(*chain);
714     CKey key;
715     key.MakeNewKey(true);
716     AddKey(*wallet, key);
717     TestUnloadWallet(std::move(wallet));
718 
719 
720     // Add log hook to detect AddToWallet events from rescans, blockConnected,
721     // and transactionAddedToMempool notifications
722     int addtx_count = 0;
723     DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) {
724         if (s) ++addtx_count;
725         return false;
726     });
727 
728 
729     bool rescan_completed = false;
730     DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) {
731         if (s) rescan_completed = true;
732         return false;
733     });
734 
735 
736     // Block the queue to prevent the wallet receiving blockConnected and
737     // transactionAddedToMempool notifications, and create block and mempool
738     // transactions paying to the wallet
739     std::promise<void> promise;
740     CallFunctionInValidationInterfaceQueue([&promise] {
741         promise.get_future().wait();
742     });
743     std::string error;
744     m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
745     auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
746     m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
747     auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
748     BOOST_CHECK(chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
749 
750 
751     // Reload wallet and make sure new transactions are detected despite events
752     // being blocked
753     wallet = TestLoadWallet(*chain);
754     BOOST_CHECK(rescan_completed);
755     BOOST_CHECK_EQUAL(addtx_count, 2);
756     {
757         LOCK(wallet->cs_wallet);
758         BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
759         BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
760     }
761 
762 
763     // Unblock notification queue and make sure stale blockConnected and
764     // transactionAddedToMempool events are processed
765     promise.set_value();
766     SyncWithValidationInterfaceQueue();
767     BOOST_CHECK_EQUAL(addtx_count, 4);
768 
769 
770     TestUnloadWallet(std::move(wallet));
771 
772 
773     // Load wallet again, this time creating new block and mempool transactions
774     // paying to the wallet as the wallet finishes loading and syncing the
775     // queue so the events have to be handled immediately. Releasing the wallet
776     // lock during the sync is a little artificial but is needed to avoid a
777     // deadlock during the sync and simulates a new block notification happening
778     // as soon as possible.
779     addtx_count = 0;
780     auto handler = HandleLoadWallet([&](std::unique_ptr<interfaces::Wallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->wallet()->cs_wallet) {
781             BOOST_CHECK(rescan_completed);
782             m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
783             block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
784             m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
785             mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
786             BOOST_CHECK(chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
787             LEAVE_CRITICAL_SECTION(wallet->wallet()->cs_wallet);
788             SyncWithValidationInterfaceQueue();
789             ENTER_CRITICAL_SECTION(wallet->wallet()->cs_wallet);
790         });
791     wallet = TestLoadWallet(*chain);
792     BOOST_CHECK_EQUAL(addtx_count, 4);
793     {
794         LOCK(wallet->cs_wallet);
795         BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
796         BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
797     }
798 
799 
800     TestUnloadWallet(std::move(wallet));
801 }
802 
BOOST_FIXTURE_TEST_CASE(ZapSelectTx,TestChain100Setup)803 BOOST_FIXTURE_TEST_CASE(ZapSelectTx, TestChain100Setup)
804 {
805     auto chain = interfaces::MakeChain(m_node);
806     auto wallet = TestLoadWallet(*chain);
807     CKey key;
808     key.MakeNewKey(true);
809     AddKey(*wallet, key);
810 
811     std::string error;
812     m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
813     auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
814     CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
815 
816     SyncWithValidationInterfaceQueue();
817 
818     {
819         auto block_hash = block_tx.GetHash();
820         auto prev_hash = m_coinbase_txns[0]->GetHash();
821 
822         LOCK(wallet->cs_wallet);
823         BOOST_CHECK(wallet->HasWalletSpend(prev_hash));
824         BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 1u);
825 
826         std::vector<uint256> vHashIn{ block_hash }, vHashOut;
827         BOOST_CHECK_EQUAL(wallet->ZapSelectTx(vHashIn, vHashOut), DBErrors::LOAD_OK);
828 
829         BOOST_CHECK(!wallet->HasWalletSpend(prev_hash));
830         BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 0u);
831     }
832 
833     TestUnloadWallet(std::move(wallet));
834 }
835 
836 BOOST_AUTO_TEST_SUITE_END()
837