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