LCOV - code coverage report
Current view: top level - src/wallet/test - wallet_tests.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 97.2 % 650 632
Test Date: 2024-11-04 05:10:19 Functions: 100.0 % 69 69
Branches: 50.4 % 2762 1393

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2012-2022 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 <addresstype.h>
      13                 :             : #include <interfaces/chain.h>
      14                 :             : #include <key_io.h>
      15                 :             : #include <node/blockstorage.h>
      16                 :             : #include <policy/policy.h>
      17                 :             : #include <rpc/server.h>
      18                 :             : #include <script/solver.h>
      19                 :             : #include <test/util/logging.h>
      20                 :             : #include <test/util/random.h>
      21                 :             : #include <test/util/setup_common.h>
      22                 :             : #include <util/translation.h>
      23                 :             : #include <validation.h>
      24                 :             : #include <validationinterface.h>
      25                 :             : #include <wallet/coincontrol.h>
      26                 :             : #include <wallet/context.h>
      27                 :             : #include <wallet/receive.h>
      28                 :             : #include <wallet/spend.h>
      29                 :             : #include <wallet/test/util.h>
      30                 :             : #include <wallet/test/wallet_test_fixture.h>
      31                 :             : 
      32                 :             : #include <boost/test/unit_test.hpp>
      33                 :             : #include <univalue.h>
      34                 :             : 
      35                 :             : using node::MAX_BLOCKFILE_SIZE;
      36                 :             : 
      37                 :             : namespace wallet {
      38                 :             : RPCHelpMan importmulti();
      39                 :             : RPCHelpMan dumpwallet();
      40                 :             : RPCHelpMan importwallet();
      41                 :             : 
      42                 :             : // Ensure that fee levels defined in the wallet are at least as high
      43                 :             : // as the default levels for node policy.
      44                 :             : static_assert(DEFAULT_TRANSACTION_MINFEE >= DEFAULT_MIN_RELAY_TX_FEE, "wallet minimum fee is smaller than default relay fee");
      45                 :             : static_assert(WALLET_INCREMENTAL_RELAY_FEE >= DEFAULT_INCREMENTAL_RELAY_FEE, "wallet incremental fee is smaller than default incremental relay fee");
      46                 :             : 
      47                 :             : BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
      48                 :             : 
      49                 :           5 : static CMutableTransaction TestSimpleSpend(const CTransaction& from, uint32_t index, const CKey& key, const CScript& pubkey)
      50                 :             : {
      51                 :           5 :     CMutableTransaction mtx;
      52         [ +  - ]:           5 :     mtx.vout.emplace_back(from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey);
      53         [ +  - ]:          15 :     mtx.vin.push_back({CTxIn{from.GetHash(), index}});
      54                 :           5 :     FillableSigningProvider keystore;
      55         [ +  - ]:           5 :     keystore.AddKey(key);
      56         [ +  - ]:           5 :     std::map<COutPoint, Coin> coins;
      57         [ +  - ]:           5 :     coins[mtx.vin[0].prevout].out = from.vout[index];
      58         [ +  - ]:           5 :     std::map<int, bilingual_str> input_errors;
      59   [ +  -  +  -  :          10 :     BOOST_CHECK(SignTransaction(mtx, &keystore, coins, SIGHASH_ALL, input_errors));
                   +  - ]
      60                 :          10 :     return mtx;
      61                 :           5 : }
      62                 :             : 
      63                 :           7 : static void AddKey(CWallet& wallet, const CKey& key)
      64                 :             : {
      65                 :           7 :     LOCK(wallet.cs_wallet);
      66                 :           7 :     FlatSigningProvider provider;
      67         [ +  - ]:           7 :     std::string error;
      68   [ +  -  +  -  :          21 :     auto descs = Parse("combo(" + EncodeSecret(key) + ")", provider, error, /* require_checksum=*/ false);
                   +  - ]
      69         [ -  + ]:           7 :     assert(descs.size() == 1);
      70         [ +  - ]:           7 :     auto& desc = descs.at(0);
      71   [ +  -  +  - ]:           7 :     WalletDescriptor w_desc(std::move(desc), 0, 0, 1, 1);
      72   [ +  -  +  -  :           7 :     if (!wallet.AddWalletDescriptor(w_desc, provider, "", false)) assert(false);
                   -  + ]
      73         [ +  - ]:          14 : }
      74                 :             : 
      75   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
      76                 :             : {
      77                 :             :     // Cap last block file size, and mine new block in a new block file.
      78   [ +  -  +  -  :           4 :     CBlockIndex* oldTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
                   +  - ]
      79   [ +  -  +  - ]:           3 :     WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);
      80         [ +  - ]:           2 :     CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
      81   [ +  -  +  -  :           4 :     CBlockIndex* newTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
                   +  - ]
      82                 :             : 
      83                 :             :     // Verify ScanForWalletTransactions fails to read an unknown start block.
      84                 :           1 :     {
      85   [ +  -  +  -  :           2 :         CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
                   +  - ]
      86                 :           1 :         {
      87         [ +  - ]:           1 :             LOCK(wallet.cs_wallet);
      88   [ +  -  +  - ]:           1 :             LOCK(Assert(m_node.chainman)->GetMutex());
      89         [ +  - ]:           1 :             wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
      90   [ +  -  +  -  :           2 :             wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
             +  -  +  - ]
      91         [ +  - ]:           1 :         }
      92         [ +  - ]:           1 :         AddKey(wallet, coinbaseKey);
      93                 :           1 :         WalletRescanReserver reserver(wallet);
      94                 :           1 :         reserver.reserve();
      95         [ +  - ]:           1 :         CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/{}, /*start_height=*/0, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
      96   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::FAILURE);
      97   [ +  -  +  -  :           2 :         BOOST_CHECK(result.last_failed_block.IsNull());
                   +  - ]
      98   [ +  -  +  -  :           2 :         BOOST_CHECK(result.last_scanned_block.IsNull());
                   +  - ]
      99   [ +  -  +  -  :           2 :         BOOST_CHECK(!result.last_scanned_height);
                   +  - ]
     100   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
                   +  - ]
     101                 :           1 :     }
     102                 :             : 
     103                 :             :     // Verify ScanForWalletTransactions picks up transactions in both the old
     104                 :             :     // and new block files.
     105                 :           1 :     {
     106   [ +  -  +  -  :           2 :         CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
                   +  - ]
     107                 :           1 :         {
     108         [ +  - ]:           1 :             LOCK(wallet.cs_wallet);
     109   [ +  -  +  - ]:           1 :             LOCK(Assert(m_node.chainman)->GetMutex());
     110         [ +  - ]:           1 :             wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
     111   [ +  -  +  -  :           2 :             wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
             +  -  +  - ]
     112         [ +  - ]:           1 :         }
     113         [ +  - ]:           1 :         AddKey(wallet, coinbaseKey);
     114                 :           1 :         WalletRescanReserver reserver(wallet);
     115                 :           1 :         std::chrono::steady_clock::time_point fake_time;
     116                 :           8 :         reserver.setNow([&] { fake_time += 60s; return fake_time; });
     117                 :           1 :         reserver.reserve();
     118                 :             : 
     119                 :           1 :         {
     120                 :           1 :             CBlockLocator locator;
     121   [ +  -  +  -  :           3 :             BOOST_CHECK(!WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
          +  -  +  -  +  
                      - ]
     122   [ +  -  +  - ]:           2 :             BOOST_CHECK(locator.IsNull());
     123                 :             :         }
     124                 :             : 
     125         [ +  - ]:           1 :         CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/true);
     126   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::SUCCESS);
     127   [ +  -  +  -  :           2 :         BOOST_CHECK(result.last_failed_block.IsNull());
                   +  - ]
     128   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
     129   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
     130   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 100 * COIN);
                   +  - ]
     131                 :             : 
     132                 :           1 :         {
     133                 :           1 :             CBlockLocator locator;
     134   [ +  -  +  -  :           3 :             BOOST_CHECK(WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
          +  -  +  -  +  
                      - ]
     135   [ +  -  +  - ]:           2 :             BOOST_CHECK(!locator.IsNull());
     136                 :           0 :         }
     137                 :           1 :     }
     138                 :             : 
     139                 :             :     // Prune the older block file.
     140                 :           1 :     int file_number;
     141                 :           1 :     {
     142                 :           1 :         LOCK(cs_main);
     143                 :           1 :         file_number = oldTip->GetBlockPos().nFile;
     144   [ +  -  +  - ]:           1 :         Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
     145                 :           0 :     }
     146         [ +  - ]:           1 :     m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
     147                 :             : 
     148                 :             :     // Verify ScanForWalletTransactions only picks transactions in the new block
     149                 :             :     // file.
     150                 :           1 :     {
     151   [ +  -  +  -  :           2 :         CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
                   +  - ]
     152                 :           1 :         {
     153         [ +  - ]:           1 :             LOCK(wallet.cs_wallet);
     154   [ +  -  +  - ]:           1 :             LOCK(Assert(m_node.chainman)->GetMutex());
     155         [ +  - ]:           1 :             wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
     156   [ +  -  +  -  :           2 :             wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
             +  -  +  - ]
     157         [ +  - ]:           1 :         }
     158         [ +  - ]:           1 :         AddKey(wallet, coinbaseKey);
     159                 :           1 :         WalletRescanReserver reserver(wallet);
     160                 :           1 :         reserver.reserve();
     161         [ +  - ]:           1 :         CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
     162   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::FAILURE);
     163   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(result.last_failed_block, oldTip->GetBlockHash());
     164   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
     165   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
     166   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 50 * COIN);
                   +  - ]
     167                 :           1 :     }
     168                 :             : 
     169                 :             :     // Prune the remaining block file.
     170                 :           1 :     {
     171                 :           1 :         LOCK(cs_main);
     172                 :           1 :         file_number = newTip->GetBlockPos().nFile;
     173   [ +  -  +  - ]:           1 :         Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
     174                 :           0 :     }
     175         [ +  - ]:           1 :     m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
     176                 :             : 
     177                 :             :     // Verify ScanForWalletTransactions scans no blocks.
     178                 :           1 :     {
     179   [ +  -  +  -  :           2 :         CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
                   +  - ]
     180                 :           1 :         {
     181         [ +  - ]:           1 :             LOCK(wallet.cs_wallet);
     182   [ +  -  +  - ]:           1 :             LOCK(Assert(m_node.chainman)->GetMutex());
     183         [ +  - ]:           1 :             wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
     184   [ +  -  +  -  :           2 :             wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
             +  -  +  - ]
     185         [ +  - ]:           1 :         }
     186         [ +  - ]:           1 :         AddKey(wallet, coinbaseKey);
     187                 :           1 :         WalletRescanReserver reserver(wallet);
     188                 :           1 :         reserver.reserve();
     189         [ +  - ]:           1 :         CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
     190   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::FAILURE);
     191   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(result.last_failed_block, newTip->GetBlockHash());
     192   [ +  -  +  -  :           2 :         BOOST_CHECK(result.last_scanned_block.IsNull());
                   +  - ]
     193   [ +  -  +  -  :           2 :         BOOST_CHECK(!result.last_scanned_height);
                   +  - ]
     194   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
                   +  - ]
     195                 :           1 :     }
     196                 :           1 : }
     197                 :             : 
     198   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(importmulti_rescan, TestChain100Setup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     199                 :             : {
     200                 :             :     // Cap last block file size, and mine new block in a new block file.
     201   [ +  -  +  -  :           4 :     CBlockIndex* oldTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
                   +  - ]
     202   [ +  -  +  - ]:           3 :     WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);
     203         [ +  - ]:           2 :     CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
     204   [ +  -  +  -  :           4 :     CBlockIndex* newTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
                   +  - ]
     205                 :             : 
     206                 :             :     // Prune the older block file.
     207                 :           1 :     int file_number;
     208                 :           1 :     {
     209                 :           1 :         LOCK(cs_main);
     210                 :           1 :         file_number = oldTip->GetBlockPos().nFile;
     211   [ +  -  +  - ]:           1 :         Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
     212                 :           0 :     }
     213         [ +  - ]:           1 :     m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
     214                 :             : 
     215                 :             :     // Verify importmulti RPC returns failure for a key whose creation time is
     216                 :             :     // before the missing block, and success for a key whose creation time is
     217                 :             :     // after.
     218                 :           1 :     {
     219   [ +  -  +  - ]:           1 :         const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
     220         [ +  - ]:           1 :         wallet->SetupLegacyScriptPubKeyMan();
     221         [ +  - ]:           2 :         WITH_LOCK(wallet->cs_wallet, wallet->SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash()));
     222         [ +  - ]:           1 :         WalletContext context;
     223                 :           1 :         context.args = &m_args;
     224         [ +  - ]:           1 :         AddWallet(context, wallet);
     225         [ +  - ]:           1 :         UniValue keys;
     226         [ +  - ]:           1 :         keys.setArray();
     227         [ +  - ]:           1 :         UniValue key;
     228         [ +  - ]:           1 :         key.setObject();
     229   [ +  -  +  -  :           3 :         key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey())));
          +  -  +  -  +  
                -  +  - ]
     230   [ +  -  +  -  :           2 :         key.pushKV("timestamp", 0);
                   +  - ]
     231   [ +  -  +  -  :           2 :         key.pushKV("internal", UniValue(true));
                   +  - ]
     232   [ +  -  +  - ]:           1 :         keys.push_back(key);
     233         [ +  - ]:           1 :         key.clear();
     234         [ +  - ]:           1 :         key.setObject();
     235                 :           1 :         CKey futureKey = GenerateRandomKey();
     236   [ +  -  +  -  :           3 :         key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(futureKey.GetPubKey())));
          +  -  +  -  +  
                -  +  - ]
     237   [ +  -  +  -  :           2 :         key.pushKV("timestamp", newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1);
                   +  - ]
     238   [ +  -  +  -  :           2 :         key.pushKV("internal", UniValue(true));
                   +  - ]
     239         [ +  - ]:           1 :         keys.push_back(std::move(key));
     240                 :           1 :         JSONRPCRequest request;
     241                 :           1 :         request.context = &context;
     242         [ +  - ]:           1 :         request.params.setArray();
     243         [ +  - ]:           1 :         request.params.push_back(std::move(keys));
     244                 :             : 
     245   [ +  -  +  - ]:           1 :         UniValue response = importmulti().HandleRequest(request);
     246   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(response.write(),
             +  -  +  - ]
     247                 :             :             strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":\"Rescan failed for key with creation "
     248                 :             :                       "timestamp %d. There was an error reading a block from time %d, which is after or within %d "
     249                 :             :                       "seconds of key creation, and could contain transactions pertaining to the key. As a result, "
     250                 :             :                       "transactions and coins using this key may not appear in the wallet. This error could be caused "
     251                 :             :                       "by pruning or data corruption (see bitcoind log for details) and could be dealt with by "
     252                 :             :                       "downloading and rescanning the relevant blocks (see -reindex option and rescanblockchain "
     253                 :             :                       "RPC).\"}},{\"success\":true}]",
     254                 :             :                               0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW));
     255         [ +  - ]:           1 :         RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
     256         [ +  - ]:           1 :     }
     257                 :           1 : }
     258                 :             : 
     259                 :             : // Verify importwallet RPC starts rescan at earliest block with timestamp
     260                 :             : // greater or equal than key birthday. Previously there was a bug where
     261                 :             : // importwallet RPC would start the scan at the latest block with timestamp less
     262                 :             : // than or equal to key birthday.
     263   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     264                 :             : {
     265                 :             :     // Create two blocks with same timestamp to verify that importwallet rescan
     266                 :             :     // will pick up both blocks, not just the first.
     267   [ +  -  +  -  :           4 :     const int64_t BLOCK_TIME = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip()->GetBlockTimeMax() + 5);
                   +  - ]
     268                 :           1 :     SetMockTime(BLOCK_TIME);
     269   [ +  -  +  - ]:           2 :     m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
     270   [ +  -  +  - ]:           2 :     m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
     271                 :             : 
     272                 :             :     // Set key birthday to block time increased by the timestamp window, so
     273                 :             :     // rescan will start at the block time.
     274                 :           1 :     const int64_t KEY_TIME = BLOCK_TIME + TIMESTAMP_WINDOW;
     275                 :           1 :     SetMockTime(KEY_TIME);
     276   [ +  -  +  - ]:           2 :     m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
     277                 :             : 
     278   [ +  -  +  - ]:           4 :     std::string backup_file = fs::PathToString(m_args.GetDataDirNet() / "wallet.backup");
     279                 :             : 
     280                 :             :     // Import key into wallet and call dumpwallet to create backup file.
     281                 :           1 :     {
     282         [ +  - ]:           1 :         WalletContext context;
     283                 :           1 :         context.args = &m_args;
     284   [ +  -  +  - ]:           1 :         const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
     285                 :           1 :         {
     286         [ +  - ]:           1 :             auto spk_man = wallet->GetOrCreateLegacyScriptPubKeyMan();
     287   [ +  -  +  - ]:           1 :             LOCK2(wallet->cs_wallet, spk_man->cs_KeyStore);
     288   [ +  -  +  -  :           1 :             spk_man->mapKeyMetadata[coinbaseKey.GetPubKey().GetID()].nCreateTime = KEY_TIME;
                   +  - ]
     289   [ +  -  +  - ]:           1 :             spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
     290                 :             : 
     291         [ +  - ]:           1 :             AddWallet(context, wallet);
     292   [ +  -  +  - ]:           1 :             LOCK(Assert(m_node.chainman)->GetMutex());
     293   [ +  -  +  -  :           2 :             wallet->SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
             +  -  +  - ]
     294   [ +  -  +  - ]:           2 :         }
     295                 :           1 :         JSONRPCRequest request;
     296                 :           1 :         request.context = &context;
     297         [ +  - ]:           1 :         request.params.setArray();
     298   [ +  -  +  - ]:           1 :         request.params.push_back(backup_file);
     299                 :             : 
     300   [ +  -  +  - ]:           1 :         wallet::dumpwallet().HandleRequest(request);
     301         [ +  - ]:           1 :         RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
     302         [ +  - ]:           2 :     }
     303                 :             : 
     304                 :             :     // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME
     305                 :             :     // were scanned, and no prior blocks were scanned.
     306                 :           1 :     {
     307   [ +  -  +  - ]:           1 :         const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
     308         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     309         [ +  - ]:           1 :         wallet->SetupLegacyScriptPubKeyMan();
     310                 :             : 
     311         [ +  - ]:           1 :         WalletContext context;
     312                 :           1 :         context.args = &m_args;
     313                 :           1 :         JSONRPCRequest request;
     314                 :           1 :         request.context = &context;
     315         [ +  - ]:           1 :         request.params.setArray();
     316   [ +  -  +  - ]:           1 :         request.params.push_back(backup_file);
     317         [ +  - ]:           1 :         AddWallet(context, wallet);
     318   [ +  -  +  - ]:           1 :         LOCK(Assert(m_node.chainman)->GetMutex());
     319   [ +  -  +  -  :           2 :         wallet->SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
             +  -  +  - ]
     320   [ +  -  +  - ]:           1 :         wallet::importwallet().HandleRequest(request);
     321         [ +  - ]:           1 :         RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt);
     322                 :             : 
     323   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(wallet->mapWallet.size(), 3U);
     324   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(m_coinbase_txns.size(), 103U);
     325         [ +  + ]:         104 :         for (size_t i = 0; i < m_coinbase_txns.size(); ++i) {
     326         [ +  - ]:         103 :             bool found = wallet->GetWalletTx(m_coinbase_txns[i]->GetHash());
     327                 :         103 :             bool expected = i >= 100;
     328   [ +  -  +  - ]:         103 :             BOOST_CHECK_EQUAL(found, expected);
     329                 :             :         }
     330   [ +  -  +  - ]:           3 :     }
     331                 :           1 : }
     332                 :             : 
     333                 :             : // This test verifies that wallet settings can be added and removed
     334                 :             : // concurrently, ensuring no race conditions occur during either process.
     335   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(write_wallet_settings_concurrently, TestingSetup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     336                 :             : {
     337                 :           1 :     auto chain = m_node.chain.get();
     338                 :           1 :     const auto NUM_WALLETS{5};
     339                 :             : 
     340                 :             :     // Since we're counting the number of wallets, ensure we start without any.
     341   [ +  -  +  -  :           2 :     BOOST_REQUIRE(chain->getRwSetting("wallet").isNull());
                   +  - ]
     342                 :             : 
     343                 :           3 :     const auto& check_concurrent_wallet = [&](const auto& settings_function, int num_expected_wallets) {
     344                 :           2 :         std::vector<std::thread> threads;
     345         [ +  - ]:           2 :         threads.reserve(NUM_WALLETS);
     346   [ +  -  +  + ]:          12 :         for (auto i{0}; i < NUM_WALLETS; ++i) threads.emplace_back(settings_function, i);
     347   [ +  -  +  + ]:          12 :         for (auto& t : threads) t.join();
     348                 :             : 
     349   [ +  -  +  - ]:           2 :         auto wallets = chain->getRwSetting("wallet");
     350   [ +  -  +  -  :           2 :         BOOST_CHECK_EQUAL(wallets.getValues().size(), num_expected_wallets);
                   +  - ]
     351                 :           3 :     };
     352                 :             : 
     353                 :             :     // Add NUM_WALLETS wallets concurrently, ensure we end up with NUM_WALLETS stored.
     354                 :           6 :     check_concurrent_wallet([&chain](int i) {
     355   [ +  -  +  - ]:           5 :         Assert(AddWalletSetting(*chain, strprintf("wallet_%d", i)));
     356                 :           5 :     },
     357                 :             :                             /*num_expected_wallets=*/NUM_WALLETS);
     358                 :             : 
     359                 :             :     // Remove NUM_WALLETS wallets concurrently, ensure we end up with 0 wallets.
     360                 :           6 :     check_concurrent_wallet([&chain](int i) {
     361   [ +  -  +  - ]:           5 :         Assert(RemoveWalletSetting(*chain, strprintf("wallet_%d", i)));
     362                 :           5 :     },
     363                 :             :                             /*num_expected_wallets=*/0);
     364                 :           1 : }
     365                 :             : 
     366                 :             : // Check that GetImmatureCredit() returns a newly calculated value instead of
     367                 :             : // the cached value after a MarkDirty() call.
     368                 :             : //
     369                 :             : // This is a regression test written to verify a bugfix for the immature credit
     370                 :             : // function. Similar tests probably should be written for the other credit and
     371                 :             : // debit functions.
     372   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     373                 :             : {
     374   [ +  -  +  -  :           2 :     CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
                   +  - ]
     375                 :             : 
     376         [ +  - ]:           1 :     LOCK(wallet.cs_wallet);
     377   [ +  -  +  - ]:           1 :     LOCK(Assert(m_node.chainman)->GetMutex());
     378   [ +  -  +  -  :           3 :     CWalletTx wtx{m_coinbase_txns.back(), TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/0}};
          +  -  +  -  -  
                      + ]
     379         [ +  - ]:           1 :     wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
     380         [ +  - ]:           1 :     wallet.SetupDescriptorScriptPubKeyMans();
     381                 :             : 
     382   [ +  -  +  -  :           2 :     wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
             +  -  +  - ]
     383                 :             : 
     384                 :             :     // Call GetImmatureCredit() once before adding the key to the wallet to
     385                 :             :     // cache the current immature credit amount, which is 0.
     386   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(CachedTxGetImmatureCredit(wallet, wtx, ISMINE_SPENDABLE), 0);
                   +  - ]
     387                 :             : 
     388                 :             :     // Invalidate the cached value, add the key, and make sure a new immature
     389                 :             :     // credit amount is calculated.
     390         [ +  - ]:           1 :     wtx.MarkDirty();
     391         [ +  - ]:           1 :     AddKey(wallet, coinbaseKey);
     392   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(CachedTxGetImmatureCredit(wallet, wtx, ISMINE_SPENDABLE), 50*COIN);
                   +  - ]
     393   [ +  -  +  - ]:           3 : }
     394                 :             : 
     395                 :           6 : static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
     396                 :             : {
     397                 :           6 :     CMutableTransaction tx;
     398         [ +  - ]:           6 :     TxState state = TxStateInactive{};
     399                 :           6 :     tx.nLockTime = lockTime;
     400         [ +  - ]:           6 :     SetMockTime(mockTime);
     401                 :           6 :     CBlockIndex* block = nullptr;
     402         [ +  + ]:           6 :     if (blockTime > 0) {
     403         [ +  - ]:           5 :         LOCK(cs_main);
     404         [ +  - ]:           5 :         auto inserted = chainman.BlockIndex().emplace(std::piecewise_construct, std::make_tuple(GetRandHash()), std::make_tuple());
     405         [ -  + ]:           5 :         assert(inserted.second);
     406                 :           5 :         const uint256& hash = inserted.first->first;
     407                 :           5 :         block = &inserted.first->second;
     408                 :           5 :         block->nTime = blockTime;
     409                 :           5 :         block->phashBlock = &hash;
     410         [ +  - ]:           5 :         state = TxStateConfirmed{hash, block->nHeight, /*index=*/0};
     411                 :           5 :     }
     412   [ +  -  +  - ]:          18 :     return wallet.AddToWallet(MakeTransactionRef(tx), state, [&](CWalletTx& wtx, bool /* new_tx */) {
     413                 :             :         // Assign wtx.m_state to simplify test and avoid the need to simulate
     414                 :             :         // reorg events. Without this, AddToWallet asserts false when the same
     415                 :             :         // transaction is confirmed in different blocks.
     416                 :           6 :         wtx.m_state = state;
     417                 :           6 :         return true;
     418         [ +  - ]:           6 :     })->nTimeSmart;
     419                 :           6 : }
     420                 :             : 
     421                 :             : // Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
     422                 :             : // expanded to cover more corner cases of smart time logic.
     423   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     424                 :             : {
     425                 :             :     // New transaction should use clock time if lower than block time.
     426         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100, 120), 100);
     427                 :             : 
     428                 :             :     // Test that updating existing transaction does not change smart time.
     429         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200, 220), 100);
     430                 :             : 
     431                 :             :     // New transaction should use clock time if there's no block time.
     432         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300, 0), 300);
     433                 :             : 
     434                 :             :     // New transaction should use block time if lower than clock time.
     435         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420, 400), 400);
     436                 :             : 
     437                 :             :     // New transaction should use latest entry time if higher than
     438                 :             :     // min(block time, clock time).
     439         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500, 390), 400);
     440                 :             : 
     441                 :             :     // If there are future entries, new transaction should use time of the
     442                 :             :     // newest entry that is no more than 300 seconds ahead of the clock time.
     443         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50, 600), 300);
     444                 :           1 : }
     445                 :             : 
     446                 :           3 : void TestLoadWallet(const std::string& name, DatabaseFormat format, std::function<void(std::shared_ptr<CWallet>)> f)
     447                 :             : {
     448                 :           3 :     node::NodeContext node;
     449         [ +  - ]:           3 :     auto chain{interfaces::MakeChain(node)};
     450         [ +  - ]:           3 :     DatabaseOptions options;
     451         [ +  - ]:           3 :     options.require_format = format;
     452                 :           3 :     DatabaseStatus status;
     453         [ +  - ]:           3 :     bilingual_str error;
     454                 :           3 :     std::vector<bilingual_str> warnings;
     455         [ +  - ]:           3 :     auto database{MakeWalletDatabase(name, options, status, error)};
     456         [ +  - ]:           3 :     auto wallet{std::make_shared<CWallet>(chain.get(), "", std::move(database))};
     457   [ +  -  +  -  :           3 :     BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::LOAD_OK);
                   +  - ]
     458   [ +  -  +  -  :          15 :     WITH_LOCK(wallet->cs_wallet, f(wallet));
             +  -  +  - ]
     459                 :           6 : }
     460                 :             : 
     461   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(LoadReceiveRequests, TestingSetup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     462                 :             : {
     463         [ +  + ]:           2 :     for (DatabaseFormat format : DATABASE_FORMATS) {
     464                 :           1 :         const std::string name{strprintf("receive-requests-%i", format)};
     465         [ +  - ]:           2 :         TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
     466   [ +  -  +  - ]:           2 :             BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
     467                 :           1 :             WalletBatch batch{wallet->GetDatabase()};
     468   [ +  -  +  -  :           2 :             BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), true));
             +  -  +  - ]
     469   [ +  -  +  -  :           2 :             BOOST_CHECK(batch.WriteAddressPreviouslySpent(ScriptHash(), true));
             +  -  +  - ]
     470   [ +  -  +  -  :           2 :             BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "0", "val_rr00"));
          +  -  +  -  +  
                -  +  - ]
     471   [ +  -  +  -  :           2 :             BOOST_CHECK(wallet->EraseAddressReceiveRequest(batch, PKHash(), "0"));
          +  -  +  -  +  
                      - ]
     472   [ +  -  +  -  :           2 :             BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr10"));
          +  -  +  -  +  
                -  +  - ]
     473   [ +  -  +  -  :           2 :             BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr11"));
          +  -  +  -  +  
                -  +  - ]
     474   [ +  -  +  -  :           2 :             BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, ScriptHash(), "2", "val_rr20"));
          +  -  +  -  +  
                      - ]
     475                 :           1 :         });
     476         [ +  - ]:           2 :         TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
     477   [ +  -  +  - ]:           2 :             BOOST_CHECK(wallet->IsAddressPreviouslySpent(PKHash()));
     478   [ +  -  +  - ]:           2 :             BOOST_CHECK(wallet->IsAddressPreviouslySpent(ScriptHash()));
     479                 :           1 :             auto requests = wallet->GetAddressReceiveRequests();
     480                 :           1 :             auto erequests = {"val_rr11", "val_rr20"};
     481   [ +  -  +  -  :           2 :             BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
                   +  - ]
     482         [ +  - ]:           1 :             RunWithinTxn(wallet->GetDatabase(), /*process_desc*/"test", [](WalletBatch& batch){
     483   [ +  -  +  - ]:           2 :                 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), false));
     484   [ +  -  +  - ]:           2 :                 BOOST_CHECK(batch.EraseAddressData(ScriptHash()));
     485                 :           1 :                 return true;
     486                 :             :             });
     487                 :           1 :         });
     488         [ +  - ]:           3 :         TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
     489   [ +  -  +  - ]:           2 :             BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
     490   [ +  -  +  - ]:           2 :             BOOST_CHECK(!wallet->IsAddressPreviouslySpent(ScriptHash()));
     491                 :           1 :             auto requests = wallet->GetAddressReceiveRequests();
     492                 :           1 :             auto erequests = {"val_rr11"};
     493   [ +  -  +  -  :           2 :             BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
                   +  - ]
     494                 :           1 :         });
     495                 :           1 :     }
     496                 :           1 : }
     497                 :             : 
     498                 :             : // Test some watch-only LegacyScriptPubKeyMan methods by the procedure of loading (LoadWatchOnly),
     499                 :             : // checking (HaveWatchOnly), getting (GetWatchPubKey) and removing (RemoveWatchOnly) a
     500                 :             : // given PubKey, resp. its corresponding P2PK Script. Results of the impact on
     501                 :             : // the address -> PubKey map is dependent on whether the PubKey is a point on the curve
     502                 :           5 : static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan* spk_man, const CPubKey& add_pubkey)
     503                 :             : {
     504                 :           5 :     CScript p2pk = GetScriptForRawPubKey(add_pubkey);
     505         [ +  - ]:           5 :     CKeyID add_address = add_pubkey.GetID();
     506         [ +  - ]:           5 :     CPubKey found_pubkey;
     507         [ +  - ]:           5 :     LOCK(spk_man->cs_KeyStore);
     508                 :             : 
     509                 :             :     // all Scripts (i.e. also all PubKeys) are added to the general watch-only set
     510   [ +  -  +  -  :          10 :     BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
             +  -  +  - ]
     511         [ +  - ]:           5 :     spk_man->LoadWatchOnly(p2pk);
     512   [ +  -  +  -  :          10 :     BOOST_CHECK(spk_man->HaveWatchOnly(p2pk));
             +  -  +  - ]
     513                 :             : 
     514                 :             :     // only PubKeys on the curve shall be added to the watch-only address -> PubKey map
     515         [ +  - ]:           5 :     bool is_pubkey_fully_valid = add_pubkey.IsFullyValid();
     516         [ +  + ]:           5 :     if (is_pubkey_fully_valid) {
     517   [ +  -  +  -  :           4 :         BOOST_CHECK(spk_man->GetWatchPubKey(add_address, found_pubkey));
             +  -  +  - ]
     518   [ +  -  +  - ]:           4 :         BOOST_CHECK(found_pubkey == add_pubkey);
     519                 :             :     } else {
     520   [ +  -  +  -  :           6 :         BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
             +  -  +  - ]
     521   [ +  -  +  - ]:           6 :         BOOST_CHECK(found_pubkey == CPubKey()); // passed key is unchanged
     522                 :             :     }
     523                 :             : 
     524         [ +  - ]:           5 :     spk_man->RemoveWatchOnly(p2pk);
     525   [ +  -  +  -  :          10 :     BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk));
             +  -  +  + ]
     526                 :             : 
     527         [ +  + ]:           5 :     if (is_pubkey_fully_valid) {
     528   [ +  -  +  -  :           4 :         BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey));
             +  -  +  - ]
     529   [ +  -  +  - ]:           4 :         BOOST_CHECK(found_pubkey == add_pubkey); // passed key is unchanged
     530                 :             :     }
     531                 :           5 : }
     532                 :             : 
     533                 :             : // Cryptographically invalidate a PubKey whilst keeping length and first byte
     534                 :           2 : static void PollutePubKey(CPubKey& pubkey)
     535                 :             : {
     536         [ -  + ]:           2 :     assert(pubkey.size() >= 1);
     537                 :           2 :     std::vector<unsigned char> pubkey_raw;
     538         [ +  - ]:           2 :     pubkey_raw.push_back(pubkey[0]);
     539         [ +  - ]:           2 :     pubkey_raw.insert(pubkey_raw.end(), pubkey.size() - 1, 0);
     540                 :           2 :     pubkey = CPubKey(pubkey_raw);
     541   [ +  -  -  + ]:           2 :     assert(!pubkey.IsFullyValid());
     542         [ -  + ]:           2 :     assert(pubkey.IsValid());
     543                 :           2 : }
     544                 :             : 
     545                 :             : // Test watch-only logic for PubKeys
     546   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(WatchOnlyPubKeys)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     547                 :             : {
     548                 :           1 :     CKey key;
     549         [ +  - ]:           1 :     CPubKey pubkey;
     550         [ +  - ]:           1 :     LegacyScriptPubKeyMan* spk_man = m_wallet.GetOrCreateLegacyScriptPubKeyMan();
     551                 :             : 
     552   [ +  -  +  -  :           2 :     BOOST_CHECK(!spk_man->HaveWatchOnly());
             +  -  +  - ]
     553                 :             : 
     554                 :             :     // uncompressed valid PubKey
     555         [ +  - ]:           1 :     key.MakeNewKey(false);
     556         [ +  - ]:           1 :     pubkey = key.GetPubKey();
     557         [ -  + ]:           1 :     assert(!pubkey.IsCompressed());
     558         [ +  - ]:           1 :     TestWatchOnlyPubKey(spk_man, pubkey);
     559                 :             : 
     560                 :             :     // uncompressed cryptographically invalid PubKey
     561         [ +  - ]:           1 :     PollutePubKey(pubkey);
     562         [ +  - ]:           1 :     TestWatchOnlyPubKey(spk_man, pubkey);
     563                 :             : 
     564                 :             :     // compressed valid PubKey
     565         [ +  - ]:           1 :     key.MakeNewKey(true);
     566         [ +  - ]:           1 :     pubkey = key.GetPubKey();
     567         [ -  + ]:           1 :     assert(pubkey.IsCompressed());
     568         [ +  - ]:           1 :     TestWatchOnlyPubKey(spk_man, pubkey);
     569                 :             : 
     570                 :             :     // compressed cryptographically invalid PubKey
     571         [ +  - ]:           1 :     PollutePubKey(pubkey);
     572         [ +  - ]:           1 :     TestWatchOnlyPubKey(spk_man, pubkey);
     573                 :             : 
     574                 :             :     // invalid empty PubKey
     575         [ +  - ]:           1 :     pubkey = CPubKey();
     576         [ +  - ]:           1 :     TestWatchOnlyPubKey(spk_man, pubkey);
     577                 :           1 : }
     578                 :             : 
     579                 :             : class ListCoinsTestingSetup : public TestChain100Setup
     580                 :             : {
     581                 :             : public:
     582                 :           2 :     ListCoinsTestingSetup()
     583         [ +  - ]:           2 :     {
     584   [ +  -  +  -  :           4 :         CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
                   +  - ]
     585   [ +  -  +  -  :           6 :         wallet = CreateSyncedWallet(*m_node.chain, WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain()), coinbaseKey);
          +  -  -  +  -  
             +  +  -  +  
                      - ]
     586   [ +  -  -  - ]:           4 :     }
     587                 :             : 
     588                 :           2 :     ~ListCoinsTestingSetup()
     589                 :             :     {
     590         [ +  - ]:           2 :         wallet.reset();
     591         [ -  + ]:           2 :     }
     592                 :             : 
     593                 :           5 :     CWalletTx& AddTx(CRecipient recipient)
     594                 :             :     {
     595                 :           5 :         CTransactionRef tx;
     596         [ +  - ]:           5 :         CCoinControl dummy;
     597                 :           5 :         {
     598   [ +  -  +  -  :          15 :             auto res = CreateTransaction(*wallet, {recipient}, /*change_pos=*/std::nullopt, dummy);
             +  +  -  - ]
     599   [ +  -  +  - ]:          10 :             BOOST_CHECK(res);
     600                 :           5 :             tx = res->tx;
     601                 :           0 :         }
     602   [ +  -  +  - ]:          15 :         wallet->CommitTransaction(tx, {}, {});
     603         [ +  - ]:           5 :         CMutableTransaction blocktx;
     604                 :           5 :         {
     605         [ +  - ]:           5 :             LOCK(wallet->cs_wallet);
     606   [ +  -  +  -  :          10 :             blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).tx);
                   +  - ]
     607                 :           0 :         }
     608   [ +  -  +  -  :          20 :         CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
          +  -  +  -  +  
                +  -  - ]
     609                 :             : 
     610         [ +  - ]:           5 :         LOCK(wallet->cs_wallet);
     611   [ +  -  +  - ]:           5 :         LOCK(Assert(m_node.chainman)->GetMutex());
     612   [ +  -  +  -  :          10 :         wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
                   +  - ]
     613         [ +  - ]:           5 :         auto it = wallet->mapWallet.find(tx->GetHash());
     614   [ +  -  +  -  :          10 :         BOOST_CHECK(it != wallet->mapWallet.end());
                   +  - ]
     615   [ +  -  +  -  :          10 :         it->second.m_state = TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/1};
                   +  - ]
     616         [ +  - ]:           5 :         return it->second;
     617   [ +  -  +  -  :          30 :     }
          +  -  +  -  +  
                      - ]
     618                 :             : 
     619                 :             :     std::unique_ptr<CWallet> wallet;
     620                 :             : };
     621                 :             : 
     622   [ +  -  +  -  :          10 : BOOST_FIXTURE_TEST_CASE(ListCoinsTest, ListCoinsTestingSetup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     623                 :             : {
     624                 :           1 :     std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
     625                 :             : 
     626                 :             :     // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
     627                 :             :     // address.
     628         [ +  - ]:           1 :     std::map<CTxDestination, std::vector<COutput>> list;
     629                 :           1 :     {
     630         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     631   [ +  -  +  - ]:           2 :         list = ListCoins(*wallet);
     632                 :           0 :     }
     633   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(list.size(), 1U);
     634   [ +  -  -  +  :           1 :     BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
             +  -  +  - ]
     635   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
     636                 :             : 
     637                 :             :     // Check initial balance from one mature coinbase transaction.
     638   [ +  -  +  -  :           3 :     BOOST_CHECK_EQUAL(50 * COIN, WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet).GetTotalAmount()));
                   +  - ]
     639                 :             : 
     640                 :             :     // Add a transaction creating a change address, and confirm ListCoins still
     641                 :             :     // returns the coin associated with the change address underneath the
     642                 :             :     // coinbaseKey pubkey, even though the change address has a different
     643                 :             :     // pubkey.
     644         [ +  - ]:           1 :     AddTx(CRecipient{PubKeyDestination{{}}, 1 * COIN, /*subtract_fee=*/false});
     645                 :           1 :     {
     646         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     647   [ +  -  +  - ]:           2 :         list = ListCoins(*wallet);
     648                 :           0 :     }
     649   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(list.size(), 1U);
     650   [ +  -  -  +  :           1 :     BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
             +  -  +  - ]
     651   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
     652                 :             : 
     653                 :             :     // Lock both coins. Confirm number of available coins drops to 0.
     654                 :           1 :     {
     655         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     656   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(AvailableCoinsListUnspent(*wallet).Size(), 2U);
          +  -  +  -  +  
                      - ]
     657                 :           0 :     }
     658         [ +  + ]:           2 :     for (const auto& group : list) {
     659         [ +  + ]:           3 :         for (const auto& coin : group.second) {
     660         [ +  - ]:           2 :             LOCK(wallet->cs_wallet);
     661         [ +  - ]:           2 :             wallet->LockCoin(coin.outpoint);
     662                 :           2 :         }
     663                 :             :     }
     664                 :           1 :     {
     665         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     666   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(AvailableCoinsListUnspent(*wallet).Size(), 0U);
          +  -  +  -  +  
                      - ]
     667                 :           0 :     }
     668                 :             :     // Confirm ListCoins still returns same result as before, despite coins
     669                 :             :     // being locked.
     670                 :           1 :     {
     671         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     672   [ +  -  +  - ]:           2 :         list = ListCoins(*wallet);
     673                 :           0 :     }
     674   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(list.size(), 1U);
     675   [ +  -  -  +  :           1 :     BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
             +  -  +  - ]
     676   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
     677                 :           1 : }
     678                 :             : 
     679                 :           4 : void TestCoinsResult(ListCoinsTest& context, OutputType out_type, CAmount amount,
     680                 :             :                      std::map<OutputType, size_t>& expected_coins_sizes)
     681                 :             : {
     682                 :           4 :     LOCK(context.wallet->cs_wallet);
     683   [ +  -  +  -  :           4 :     util::Result<CTxDestination> dest = Assert(context.wallet->GetNewDestination(out_type, ""));
                   +  - ]
     684   [ +  -  +  - ]:           8 :     CWalletTx& wtx = context.AddTx(CRecipient{*dest, amount, /*fSubtractFeeFromAmount=*/true});
     685                 :           4 :     CoinFilterParams filter;
     686                 :           4 :     filter.skip_locked = false;
     687         [ +  - ]:           4 :     CoinsResult available_coins = AvailableCoins(*context.wallet, nullptr, std::nullopt, filter);
     688                 :             :     // Lock outputs so they are not spent in follow-up transactions
     689   [ +  -  +  + ]:          12 :     for (uint32_t i = 0; i < wtx.tx->vout.size(); i++) context.wallet->LockCoin({wtx.GetHash(), i});
     690   [ +  -  +  -  :          24 :     for (const auto& [type, size] : expected_coins_sizes) BOOST_CHECK_EQUAL(size, available_coins.coins[type].size());
             +  -  +  + ]
     691         [ +  - ]:           8 : }
     692                 :             : 
     693   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(BasicOutputTypesTest, ListCoinsTest)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     694                 :             : {
     695                 :           1 :     std::map<OutputType, size_t> expected_coins_sizes;
     696   [ +  -  +  + ]:           5 :     for (const auto& out_type : OUTPUT_TYPES) { expected_coins_sizes[out_type] = 0U; }
     697                 :             : 
     698                 :             :     // Verify our wallet has one usable coinbase UTXO before starting
     699                 :             :     // This UTXO is a P2PK, so it should show up in the Other bucket
     700         [ +  - ]:           1 :     expected_coins_sizes[OutputType::UNKNOWN] = 1U;
     701         [ +  - ]:           3 :     CoinsResult available_coins = WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet));
     702   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(available_coins.Size(), expected_coins_sizes[OutputType::UNKNOWN]);
             +  -  +  - ]
     703   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(available_coins.coins[OutputType::UNKNOWN].size(), expected_coins_sizes[OutputType::UNKNOWN]);
             +  -  +  - ]
     704                 :             : 
     705                 :             :     // We will create a self transfer for each of the OutputTypes and
     706                 :             :     // verify it is put in the correct bucket after running GetAvailablecoins
     707                 :             :     //
     708                 :             :     // For each OutputType, We expect 2 UTXOs in our wallet following the self transfer:
     709                 :             :     //   1. One UTXO as the recipient
     710                 :             :     //   2. One UTXO from the change, due to payment address matching logic
     711                 :             : 
     712         [ +  + ]:           5 :     for (const auto& out_type : OUTPUT_TYPES) {
     713         [ -  + ]:           4 :         if (out_type == OutputType::UNKNOWN) continue;
     714         [ +  - ]:           4 :         expected_coins_sizes[out_type] = 2U;
     715         [ +  - ]:           4 :         TestCoinsResult(*this, out_type, 1 * COIN, expected_coins_sizes);
     716                 :             :     }
     717                 :           1 : }
     718                 :             : 
     719   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(wallet_disableprivkeys, TestChain100Setup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     720                 :             : {
     721                 :           1 :     {
     722   [ +  -  +  - ]:           1 :         const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
     723         [ +  - ]:           1 :         wallet->SetupLegacyScriptPubKeyMan();
     724         [ +  - ]:           1 :         wallet->SetMinVersion(FEATURE_LATEST);
     725         [ +  - ]:           1 :         wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
     726   [ +  -  +  -  :           2 :         BOOST_CHECK(!wallet->TopUpKeyPool(1000));
             +  -  +  - ]
     727   [ +  -  +  -  :           2 :         BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, ""));
          +  -  +  -  +  
                      - ]
     728                 :           0 :     }
     729                 :           1 :     {
     730   [ +  -  +  - ]:           1 :         const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
     731         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     732         [ +  - ]:           1 :         wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
     733         [ +  - ]:           1 :         wallet->SetMinVersion(FEATURE_LATEST);
     734         [ +  - ]:           1 :         wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
     735   [ +  -  +  -  :           2 :         BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, ""));
          +  -  +  -  +  
                      - ]
     736         [ +  - ]:           1 :     }
     737                 :           1 : }
     738                 :             : 
     739                 :             : // Explicit calculation which is used to test the wallet constant
     740                 :             : // We get the same virtual size due to rounding(weight/4) for both use_max_sig values
     741                 :           2 : static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
     742                 :             : {
     743                 :             :     // Generate ephemeral valid pubkey
     744                 :           2 :     CKey key = GenerateRandomKey();
     745         [ +  - ]:           2 :     CPubKey pubkey = key.GetPubKey();
     746                 :             : 
     747                 :             :     // Generate pubkey hash
     748         [ +  - ]:           2 :     uint160 key_hash(Hash160(pubkey));
     749                 :             : 
     750                 :             :     // Create inner-script to enter into keystore. Key hash can't be 0...
     751   [ +  -  +  - ]:           2 :     CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end());
     752                 :             : 
     753                 :             :     // Create outer P2SH script for the output
     754         [ +  - ]:           2 :     uint160 script_id(Hash160(inner_script));
     755   [ +  -  +  -  :           2 :     CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL;
                   +  - ]
     756                 :             : 
     757                 :             :     // Add inner-script to key store and key to watchonly
     758                 :           2 :     FillableSigningProvider keystore;
     759         [ +  - ]:           2 :     keystore.AddCScript(inner_script);
     760         [ +  - ]:           2 :     keystore.AddKeyPubKey(key, pubkey);
     761                 :             : 
     762                 :             :     // Fill in dummy signatures for fee calculation.
     763                 :           2 :     SignatureData sig_data;
     764                 :             : 
     765   [ +  +  +  -  :           2 :     if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) {
                   -  + ]
     766                 :             :         // We're hand-feeding it correct arguments; shouldn't happen
     767                 :           0 :         assert(false);
     768                 :             :     }
     769                 :             : 
     770                 :           2 :     CTxIn tx_in;
     771         [ +  - ]:           2 :     UpdateInput(tx_in, sig_data);
     772         [ +  - ]:           2 :     return (size_t)GetVirtualTransactionInputSize(tx_in);
     773                 :           2 : }
     774                 :             : 
     775   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(dummy_input_size_test, TestChain100Setup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     776                 :             : {
     777         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(CalculateNestedKeyhashInputSize(false), DUMMY_NESTED_P2WPKH_INPUT_SIZE);
     778         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(CalculateNestedKeyhashInputSize(true), DUMMY_NESTED_P2WPKH_INPUT_SIZE);
     779                 :           1 : }
     780                 :             : 
     781                 :           1 : bool malformed_descriptor(std::ios_base::failure e)
     782                 :             : {
     783                 :           1 :     std::string s(e.what());
     784                 :           1 :     return s.find("Missing checksum") != std::string::npos;
     785                 :           1 : }
     786                 :             : 
     787   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(wallet_descriptor_test, BasicTestingSetup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     788                 :             : {
     789                 :           1 :     std::vector<unsigned char> malformed_record;
     790         [ +  - ]:           1 :     VectorWriter vw{malformed_record, 0};
     791         [ +  - ]:           2 :     vw << std::string("notadescriptor");
     792         [ +  - ]:           1 :     vw << uint64_t{0};
     793         [ +  - ]:           1 :     vw << int32_t{0};
     794         [ +  - ]:           1 :     vw << int32_t{0};
     795         [ +  - ]:           1 :     vw << int32_t{1};
     796                 :             : 
     797                 :           1 :     SpanReader vr{malformed_record};
     798                 :           1 :     WalletDescriptor w_desc;
     799   [ +  -  -  +  :           2 :     BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure, malformed_descriptor);
          -  -  -  -  -  
          +  +  -  +  -  
                   +  - ]
     800                 :           1 : }
     801                 :             : 
     802                 :             : //! Test CWallet::Create() and its behavior handling potential race
     803                 :             : //! conditions if it's called the same time an incoming transaction shows up in
     804                 :             : //! the mempool or a new block.
     805                 :             : //!
     806                 :             : //! It isn't possible to verify there aren't race condition in every case, so
     807                 :             : //! this test just checks two specific cases and ensures that timing of
     808                 :             : //! notifications in these cases doesn't prevent the wallet from detecting
     809                 :             : //! transactions.
     810                 :             : //!
     811                 :             : //! In the first case, block and mempool transactions are created before the
     812                 :             : //! wallet is loaded, but notifications about these transactions are delayed
     813                 :             : //! until after it is loaded. The notifications are superfluous in this case, so
     814                 :             : //! the test verifies the transactions are detected before they arrive.
     815                 :             : //!
     816                 :             : //! In the second case, block and mempool transactions are created after the
     817                 :             : //! wallet rescan and notifications are immediately synced, to verify the wallet
     818                 :             : //! must already have a handler in place for them, and there's no gap after
     819                 :             : //! rescanning where new transactions in new blocks could be lost.
     820   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(CreateWallet, TestChain100Setup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     821                 :             : {
     822   [ +  -  +  - ]:           2 :     m_args.ForceSetArg("-unsafesqlitesync", "1");
     823                 :             :     // Create new wallet with known key and unload it.
     824                 :           1 :     WalletContext context;
     825                 :           1 :     context.args = &m_args;
     826         [ +  - ]:           1 :     context.chain = m_node.chain.get();
     827         [ +  - ]:           1 :     auto wallet = TestLoadWallet(context);
     828                 :           1 :     CKey key = GenerateRandomKey();
     829         [ +  - ]:           1 :     AddKey(*wallet, key);
     830         [ +  - ]:           1 :     TestUnloadWallet(std::move(wallet));
     831                 :             : 
     832                 :             : 
     833                 :             :     // Add log hook to detect AddToWallet events from rescans, blockConnected,
     834                 :             :     // and transactionAddedToMempool notifications
     835                 :           1 :     int addtx_count = 0;
     836         [ +  - ]:          11 :     DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) {
     837         [ +  + ]:          10 :         if (s) ++addtx_count;
     838                 :          10 :         return false;
     839   [ +  -  +  - ]:           2 :     });
     840                 :             : 
     841                 :             : 
     842                 :           1 :     bool rescan_completed = false;
     843         [ +  - ]:           3 :     DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) {
     844         [ +  + ]:           2 :         if (s) rescan_completed = true;
     845                 :           2 :         return false;
     846   [ +  -  +  - ]:           2 :     });
     847                 :             : 
     848                 :             : 
     849                 :             :     // Block the queue to prevent the wallet receiving blockConnected and
     850                 :             :     // transactionAddedToMempool notifications, and create block and mempool
     851                 :             :     // transactions paying to the wallet
     852         [ +  - ]:           1 :     std::promise<void> promise;
     853         [ +  - ]:           2 :     m_node.validation_signals->CallFunctionInValidationInterfaceQueue([&promise] {
     854         [ +  - ]:           1 :         promise.get_future().wait();
     855                 :           1 :     });
     856         [ +  - ]:           1 :     std::string error;
     857   [ +  -  +  -  :           2 :     m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
             +  -  +  - ]
     858   [ +  -  +  -  :           1 :     auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
                   +  - ]
     859   [ +  -  +  -  :           4 :     m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
          +  -  +  -  +  
             -  +  +  -  
                      - ]
     860   [ +  -  +  -  :           1 :     auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
                   +  - ]
     861   [ +  -  +  -  :           4 :     BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
          +  -  +  -  +  
                -  +  - ]
     862                 :             : 
     863                 :             : 
     864                 :             :     // Reload wallet and make sure new transactions are detected despite events
     865                 :             :     // being blocked
     866                 :             :     // Loading will also ask for current mempool transactions
     867   [ +  -  -  + ]:           2 :     wallet = TestLoadWallet(context);
     868   [ +  -  +  -  :           2 :     BOOST_CHECK(rescan_completed);
                   +  - ]
     869                 :             :     // AddToWallet events for block_tx and mempool_tx (x2)
     870   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(addtx_count, 3);
     871                 :           1 :     {
     872         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     873   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
             +  -  +  - ]
     874   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
          +  -  +  -  +  
                      - ]
     875                 :           0 :     }
     876                 :             : 
     877                 :             : 
     878                 :             :     // Unblock notification queue and make sure stale blockConnected and
     879                 :             :     // transactionAddedToMempool events are processed
     880         [ +  - ]:           1 :     promise.set_value();
     881         [ +  - ]:           1 :     m_node.validation_signals->SyncWithValidationInterfaceQueue();
     882                 :             :     // AddToWallet events for block_tx and mempool_tx events are counted a
     883                 :             :     // second time as the notification queue is processed
     884   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(addtx_count, 5);
     885                 :             : 
     886                 :             : 
     887         [ +  - ]:           1 :     TestUnloadWallet(std::move(wallet));
     888                 :             : 
     889                 :             : 
     890                 :             :     // Load wallet again, this time creating new block and mempool transactions
     891                 :             :     // paying to the wallet as the wallet finishes loading and syncing the
     892                 :             :     // queue so the events have to be handled immediately. Releasing the wallet
     893                 :             :     // lock during the sync is a little artificial but is needed to avoid a
     894                 :             :     // deadlock during the sync and simulates a new block notification happening
     895                 :             :     // as soon as possible.
     896                 :           1 :     addtx_count = 0;
     897         [ +  - ]:           2 :     auto handler = HandleLoadWallet(context, [&](std::unique_ptr<interfaces::Wallet> wallet) {
     898         [ +  - ]:           2 :             BOOST_CHECK(rescan_completed);
     899   [ +  -  +  - ]:           2 :             m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
     900         [ +  - ]:           2 :             block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
     901   [ +  -  +  -  :           4 :             m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
          +  -  +  +  -  
                      - ]
     902         [ +  - ]:           2 :             mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
     903   [ +  -  +  -  :           4 :             BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
             +  -  +  - ]
     904                 :           1 :             m_node.validation_signals->SyncWithValidationInterfaceQueue();
     905         [ +  - ]:           3 :         });
     906   [ +  -  -  + ]:           2 :     wallet = TestLoadWallet(context);
     907                 :             :     // Since mempool transactions are requested at the end of loading, there will
     908                 :             :     // be 2 additional AddToWallet calls, one from the previous test, and a duplicate for mempool_tx
     909   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(addtx_count, 2 + 2);
     910                 :           1 :     {
     911         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     912   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
             +  -  +  - ]
     913   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
          +  -  +  -  +  
                      - ]
     914                 :           0 :     }
     915                 :             : 
     916                 :             : 
     917         [ +  - ]:           1 :     TestUnloadWallet(std::move(wallet));
     918   [ +  -  -  + ]:           4 : }
     919                 :             : 
     920   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(CreateWalletWithoutChain, BasicTestingSetup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     921                 :             : {
     922                 :           1 :     WalletContext context;
     923                 :           1 :     context.args = &m_args;
     924         [ +  - ]:           1 :     auto wallet = TestLoadWallet(context);
     925   [ +  -  +  -  :           2 :     BOOST_CHECK(wallet);
                   +  - ]
     926         [ +  - ]:           1 :     WaitForDeleteWallet(std::move(wallet));
     927                 :           1 : }
     928                 :             : 
     929   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(RemoveTxs, TestChain100Setup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     930                 :             : {
     931   [ +  -  +  - ]:           2 :     m_args.ForceSetArg("-unsafesqlitesync", "1");
     932                 :           1 :     WalletContext context;
     933                 :           1 :     context.args = &m_args;
     934         [ +  - ]:           1 :     context.chain = m_node.chain.get();
     935         [ +  - ]:           1 :     auto wallet = TestLoadWallet(context);
     936                 :           1 :     CKey key = GenerateRandomKey();
     937         [ +  - ]:           1 :     AddKey(*wallet, key);
     938                 :             : 
     939         [ +  - ]:           1 :     std::string error;
     940   [ +  -  +  -  :           2 :     m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
             +  -  +  - ]
     941   [ +  -  +  -  :           1 :     auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
                   +  - ]
     942   [ +  -  +  -  :           4 :     CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
          +  -  +  -  +  
                +  -  - ]
     943                 :             : 
     944         [ +  - ]:           1 :     m_node.validation_signals->SyncWithValidationInterfaceQueue();
     945                 :             : 
     946                 :           1 :     {
     947         [ +  - ]:           1 :         auto block_hash = block_tx.GetHash();
     948         [ +  - ]:           1 :         auto prev_tx = m_coinbase_txns[0];
     949                 :             : 
     950         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     951   [ +  -  +  -  :           2 :         BOOST_CHECK(wallet->HasWalletSpend(prev_tx));
             +  -  +  - ]
     952   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 1u);
                   +  - ]
     953                 :             : 
     954         [ +  - ]:           1 :         std::vector<uint256> vHashIn{ block_hash };
     955   [ +  -  +  -  :           2 :         BOOST_CHECK(wallet->RemoveTxs(vHashIn));
             +  -  +  - ]
     956                 :             : 
     957   [ +  -  +  -  :           2 :         BOOST_CHECK(!wallet->HasWalletSpend(prev_tx));
             +  -  +  - ]
     958   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 0u);
                   +  - ]
     959   [ +  -  +  - ]:           2 :     }
     960                 :             : 
     961         [ +  - ]:           1 :     TestUnloadWallet(std::move(wallet));
     962   [ +  -  -  + ]:           2 : }
     963                 :             : 
     964                 :             : /**
     965                 :             :  * Checks a wallet invalid state where the inputs (prev-txs) of a new arriving transaction are not marked dirty,
     966                 :             :  * while the transaction that spends them exist inside the in-memory wallet tx map (not stored on db due a db write failure).
     967                 :             :  */
     968   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(wallet_sync_tx_invalid_state_test, TestingSetup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     969                 :             : {
     970   [ +  -  +  -  :           2 :     CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
                   +  - ]
     971                 :           1 :     {
     972         [ +  - ]:           1 :         LOCK(wallet.cs_wallet);
     973         [ +  - ]:           1 :         wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
     974         [ +  - ]:           1 :         wallet.SetupDescriptorScriptPubKeyMans();
     975                 :           0 :     }
     976                 :             : 
     977                 :             :     // Add tx to wallet
     978   [ +  -  +  -  :           2 :     const auto op_dest{*Assert(wallet.GetNewDestination(OutputType::BECH32M, ""))};
             +  -  +  - ]
     979                 :             : 
     980         [ +  - ]:           1 :     CMutableTransaction mtx;
     981   [ +  -  +  - ]:           1 :     mtx.vout.emplace_back(COIN, GetScriptForDestination(op_dest));
     982         [ +  - ]:           1 :     mtx.vin.emplace_back(Txid::FromUint256(m_rng.rand256()), 0);
     983   [ +  -  +  -  :           3 :     const auto& tx_id_to_spend = wallet.AddToWallet(MakeTransactionRef(mtx), TxStateInMempool{})->GetHash();
                   +  - ]
     984                 :             : 
     985                 :           1 :     {
     986                 :             :         // Cache and verify available balance for the wtx
     987         [ +  - ]:           1 :         LOCK(wallet.cs_wallet);
     988         [ +  - ]:           1 :         const CWalletTx* wtx_to_spend = wallet.GetWalletTx(tx_id_to_spend);
     989   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(CachedTxGetAvailableCredit(wallet, *wtx_to_spend), 1 * COIN);
             +  -  +  - ]
     990                 :           0 :     }
     991                 :             : 
     992                 :             :     // Now the good case:
     993                 :             :     // 1) Add a transaction that spends the previously created transaction
     994                 :             :     // 2) Verify that the available balance of this new tx and the old one is updated (prev tx is marked dirty)
     995                 :             : 
     996                 :           1 :     mtx.vin.clear();
     997         [ +  - ]:           1 :     mtx.vin.emplace_back(tx_id_to_spend, 0);
     998   [ +  -  +  - ]:           2 :     wallet.transactionAddedToMempool(MakeTransactionRef(mtx));
     999         [ +  - ]:           1 :     const auto good_tx_id{mtx.GetHash()};
    1000                 :             : 
    1001                 :           1 :     {
    1002                 :             :         // Verify balance update for the new tx and the old one
    1003         [ +  - ]:           1 :         LOCK(wallet.cs_wallet);
    1004         [ +  - ]:           1 :         const CWalletTx* new_wtx = wallet.GetWalletTx(good_tx_id.ToUint256());
    1005   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(CachedTxGetAvailableCredit(wallet, *new_wtx), 1 * COIN);
                   +  - ]
    1006                 :             : 
    1007                 :             :         // Now the old wtx
    1008         [ +  - ]:           1 :         const CWalletTx* wtx_to_spend = wallet.GetWalletTx(tx_id_to_spend);
    1009   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(CachedTxGetAvailableCredit(wallet, *wtx_to_spend), 0 * COIN);
             +  -  +  - ]
    1010                 :           0 :     }
    1011                 :             : 
    1012                 :             :     // Now the bad case:
    1013                 :             :     // 1) Make db always fail
    1014                 :             :     // 2) Try to add a transaction that spends the previously created transaction and
    1015                 :             :     //    verify that we are not moving forward if the wallet cannot store it
    1016         [ +  - ]:           1 :     GetMockableDatabase(wallet).m_pass = false;
    1017                 :           1 :     mtx.vin.clear();
    1018         [ +  - ]:           1 :     mtx.vin.emplace_back(good_tx_id, 0);
    1019   [ +  -  +  -  :           4 :     BOOST_CHECK_EXCEPTION(wallet.transactionAddedToMempool(MakeTransactionRef(mtx)),
          -  +  -  -  -  
          -  -  +  +  -  
             +  -  +  - ]
    1020                 :             :                           std::runtime_error,
    1021                 :             :                           HasReason("DB error adding transaction to wallet, write failed"));
    1022                 :           1 : }
    1023                 :             : 
    1024                 :             : BOOST_AUTO_TEST_SUITE_END()
    1025                 :             : } // namespace wallet
        

Generated by: LCOV version 2.0-1