LCOV - code coverage report
Current view: top level - src/wallet/test - wallet_tests.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 97.1 % 651 632
Test Date: 2024-08-28 05:13:07 Functions: 100.0 % 69 69
Branches: 50.4 % 2772 1398

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

Generated by: LCOV version 2.0-1