LCOV - code coverage report
Current view: top level - src/wallet/test - wallet_tests.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 97.1 % 652 633
Test Date: 2025-04-25 04:35:45 Functions: 100.0 % 69 69
Branches: 50.4 % 2766 1395

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

Generated by: LCOV version 2.0-1