LCOV - code coverage report
Current view: top level - src/wallet/test - wallet_tests.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 97.0 % 466 452
Test Date: 2025-07-10 04:37:56 Functions: 100.0 % 54 54
Branches: 50.5 % 2002 1011

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2012-present 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 <cstdint>
       8                 :             : #include <future>
       9                 :             : #include <memory>
      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                 :             : 
      39                 :             : // Ensure that fee levels defined in the wallet are at least as high
      40                 :             : // as the default levels for node policy.
      41                 :             : static_assert(DEFAULT_TRANSACTION_MINFEE >= DEFAULT_MIN_RELAY_TX_FEE, "wallet minimum fee is smaller than default relay fee");
      42                 :             : static_assert(WALLET_INCREMENTAL_RELAY_FEE >= DEFAULT_INCREMENTAL_RELAY_FEE, "wallet incremental fee is smaller than default incremental relay fee");
      43                 :             : 
      44                 :             : BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
      45                 :             : 
      46                 :           5 : static CMutableTransaction TestSimpleSpend(const CTransaction& from, uint32_t index, const CKey& key, const CScript& pubkey)
      47                 :             : {
      48                 :           5 :     CMutableTransaction mtx;
      49         [ +  - ]:           5 :     mtx.vout.emplace_back(from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey);
      50         [ +  - ]:          15 :     mtx.vin.push_back({CTxIn{from.GetHash(), index}});
      51                 :           5 :     FillableSigningProvider keystore;
      52         [ +  - ]:           5 :     keystore.AddKey(key);
      53         [ +  - ]:           5 :     std::map<COutPoint, Coin> coins;
      54         [ +  - ]:           5 :     coins[mtx.vin[0].prevout].out = from.vout[index];
      55         [ +  - ]:           5 :     std::map<int, bilingual_str> input_errors;
      56   [ +  -  +  -  :          10 :     BOOST_CHECK(SignTransaction(mtx, &keystore, coins, SIGHASH_ALL, input_errors));
                   +  - ]
      57                 :          10 :     return mtx;
      58                 :           5 : }
      59                 :             : 
      60                 :           6 : static void AddKey(CWallet& wallet, const CKey& key)
      61                 :             : {
      62                 :           6 :     LOCK(wallet.cs_wallet);
      63                 :           6 :     FlatSigningProvider provider;
      64         [ +  - ]:           6 :     std::string error;
      65   [ +  -  +  -  :          18 :     auto descs = Parse("combo(" + EncodeSecret(key) + ")", provider, error, /* require_checksum=*/ false);
                   +  - ]
      66         [ -  + ]:           6 :     assert(descs.size() == 1);
      67         [ +  - ]:           6 :     auto& desc = descs.at(0);
      68   [ +  -  +  - ]:           6 :     WalletDescriptor w_desc(std::move(desc), 0, 0, 1, 1);
      69   [ +  -  +  -  :          12 :     Assert(wallet.AddWalletDescriptor(w_desc, provider, "", false));
                   +  - ]
      70         [ +  - ]:          12 : }
      71                 :             : 
      72   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(update_non_range_descriptor, TestingSetup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
      73                 :             : {
      74   [ +  -  +  -  :           2 :     CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
                   +  - ]
      75                 :           1 :     {
      76         [ +  - ]:           1 :         LOCK(wallet.cs_wallet);
      77         [ +  - ]:           1 :         wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
      78                 :           1 :         auto key{GenerateRandomKey()};
      79   [ +  -  +  - ]:           2 :         auto desc_str{"combo(" + EncodeSecret(key) + ")"};
      80                 :           1 :         FlatSigningProvider provider;
      81         [ +  - ]:           1 :         std::string error;
      82         [ +  - ]:           1 :         auto descs{Parse(desc_str, provider, error, /* require_checksum=*/ false)};
      83         [ +  - ]:           1 :         auto& desc{descs.at(0)};
      84   [ +  -  +  - ]:           1 :         WalletDescriptor w_desc{std::move(desc), 0, 0, 0, 0};
      85   [ +  -  +  -  :           2 :         BOOST_CHECK(wallet.AddWalletDescriptor(w_desc, provider, "", false));
          +  -  +  -  +  
                      - ]
      86                 :             :         // Wallet should update the non-range descriptor successfully
      87   [ +  -  +  -  :           2 :         BOOST_CHECK(wallet.AddWalletDescriptor(w_desc, provider, "", false));
             +  -  +  - ]
      88         [ +  - ]:           1 :     }
      89                 :           1 : }
      90                 :             : 
      91   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
      92                 :             : {
      93                 :             :     // Cap last block file size, and mine new block in a new block file.
      94   [ +  -  +  -  :           4 :     CBlockIndex* oldTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
                   +  - ]
      95   [ +  -  +  - ]:           3 :     WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);
      96         [ +  - ]:           2 :     CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
      97   [ +  -  +  -  :           4 :     CBlockIndex* newTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip());
                   +  - ]
      98                 :             : 
      99                 :             :     // Verify ScanForWalletTransactions fails to read an unknown start block.
     100                 :           1 :     {
     101   [ +  -  +  -  :           2 :         CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
                   +  - ]
     102                 :           1 :         {
     103         [ +  - ]:           1 :             LOCK(wallet.cs_wallet);
     104   [ +  -  +  - ]:           1 :             LOCK(Assert(m_node.chainman)->GetMutex());
     105         [ +  - ]:           1 :             wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
     106   [ +  -  +  -  :           2 :             wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
             +  -  +  - ]
     107         [ +  - ]:           1 :         }
     108         [ +  - ]:           1 :         AddKey(wallet, coinbaseKey);
     109                 :           1 :         WalletRescanReserver reserver(wallet);
     110                 :           1 :         reserver.reserve();
     111         [ +  - ]:           1 :         CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/{}, /*start_height=*/0, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
     112   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::FAILURE);
     113   [ +  -  +  -  :           2 :         BOOST_CHECK(result.last_failed_block.IsNull());
                   +  - ]
     114   [ +  -  +  -  :           2 :         BOOST_CHECK(result.last_scanned_block.IsNull());
                   +  - ]
     115   [ +  -  +  -  :           2 :         BOOST_CHECK(!result.last_scanned_height);
                   +  - ]
     116   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
                   +  - ]
     117                 :           1 :     }
     118                 :             : 
     119                 :             :     // Verify ScanForWalletTransactions picks up transactions in both the old
     120                 :             :     // and new block files.
     121                 :           1 :     {
     122   [ +  -  +  -  :           2 :         CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
                   +  - ]
     123                 :           1 :         {
     124         [ +  - ]:           1 :             LOCK(wallet.cs_wallet);
     125   [ +  -  +  - ]:           1 :             LOCK(Assert(m_node.chainman)->GetMutex());
     126         [ +  - ]:           1 :             wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
     127         [ +  - ]:           1 :             wallet.SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash());
     128         [ +  - ]:           1 :         }
     129         [ +  - ]:           1 :         AddKey(wallet, coinbaseKey);
     130                 :           1 :         WalletRescanReserver reserver(wallet);
     131                 :           1 :         std::chrono::steady_clock::time_point fake_time;
     132                 :           8 :         reserver.setNow([&] { fake_time += 60s; return fake_time; });
     133                 :           1 :         reserver.reserve();
     134                 :             : 
     135                 :           1 :         {
     136                 :           1 :             CBlockLocator locator;
     137   [ +  -  +  -  :           3 :             BOOST_CHECK(WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
          +  -  +  -  +  
                      - ]
     138   [ +  -  +  -  :           2 :             BOOST_CHECK(!locator.IsNull() && locator.vHave.front() == newTip->GetBlockHash());
             -  +  +  - ]
     139                 :           0 :         }
     140                 :             : 
     141         [ +  - ]:           1 :         CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/true);
     142   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::SUCCESS);
     143   [ +  -  +  -  :           2 :         BOOST_CHECK(result.last_failed_block.IsNull());
                   +  - ]
     144   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
     145   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
     146   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 100 * COIN);
                   +  - ]
     147                 :             : 
     148                 :           1 :         {
     149                 :           1 :             CBlockLocator locator;
     150   [ +  -  +  -  :           3 :             BOOST_CHECK(WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator));
          +  -  +  -  +  
                      - ]
     151   [ +  -  +  -  :           2 :             BOOST_CHECK(!locator.IsNull() && locator.vHave.front() == newTip->GetBlockHash());
             -  +  +  - ]
     152                 :           0 :         }
     153                 :           1 :     }
     154                 :             : 
     155                 :             :     // Prune the older block file.
     156                 :           1 :     int file_number;
     157                 :           1 :     {
     158                 :           1 :         LOCK(cs_main);
     159                 :           1 :         file_number = oldTip->GetBlockPos().nFile;
     160   [ +  -  +  - ]:           1 :         Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
     161                 :           0 :     }
     162         [ +  - ]:           1 :     m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
     163                 :             : 
     164                 :             :     // Verify ScanForWalletTransactions only picks transactions in the new block
     165                 :             :     // file.
     166                 :           1 :     {
     167   [ +  -  +  -  :           2 :         CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
                   +  - ]
     168                 :           1 :         {
     169         [ +  - ]:           1 :             LOCK(wallet.cs_wallet);
     170   [ +  -  +  - ]:           1 :             LOCK(Assert(m_node.chainman)->GetMutex());
     171         [ +  - ]:           1 :             wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
     172   [ +  -  +  -  :           2 :             wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
             +  -  +  - ]
     173         [ +  - ]:           1 :         }
     174         [ +  - ]:           1 :         AddKey(wallet, coinbaseKey);
     175                 :           1 :         WalletRescanReserver reserver(wallet);
     176                 :           1 :         reserver.reserve();
     177         [ +  - ]:           1 :         CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
     178   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::FAILURE);
     179   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(result.last_failed_block, oldTip->GetBlockHash());
     180   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash());
     181   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight);
     182   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 50 * COIN);
                   +  - ]
     183                 :           1 :     }
     184                 :             : 
     185                 :             :     // Prune the remaining block file.
     186                 :           1 :     {
     187                 :           1 :         LOCK(cs_main);
     188                 :           1 :         file_number = newTip->GetBlockPos().nFile;
     189   [ +  -  +  - ]:           1 :         Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number);
     190                 :           0 :     }
     191         [ +  - ]:           1 :     m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number});
     192                 :             : 
     193                 :             :     // Verify ScanForWalletTransactions scans no blocks.
     194                 :           1 :     {
     195   [ +  -  +  -  :           2 :         CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
                   +  - ]
     196                 :           1 :         {
     197         [ +  - ]:           1 :             LOCK(wallet.cs_wallet);
     198   [ +  -  +  - ]:           1 :             LOCK(Assert(m_node.chainman)->GetMutex());
     199         [ +  - ]:           1 :             wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
     200   [ +  -  +  -  :           2 :             wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
             +  -  +  - ]
     201                 :             :         }
     202         [ +  - ]:           1 :         AddKey(wallet, coinbaseKey);
     203                 :           1 :         WalletRescanReserver reserver(wallet);
     204                 :           1 :         reserver.reserve();
     205         [ +  - ]:           1 :         CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false);
     206   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::FAILURE);
     207   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(result.last_failed_block, newTip->GetBlockHash());
     208   [ +  -  +  -  :           2 :         BOOST_CHECK(result.last_scanned_block.IsNull());
                   +  - ]
     209   [ +  -  +  -  :           2 :         BOOST_CHECK(!result.last_scanned_height);
                   +  - ]
     210   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0);
                   +  - ]
     211                 :           1 :     }
     212                 :           1 : }
     213                 :             : 
     214                 :             : // This test verifies that wallet settings can be added and removed
     215                 :             : // concurrently, ensuring no race conditions occur during either process.
     216   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(write_wallet_settings_concurrently, TestingSetup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     217                 :             : {
     218                 :           1 :     auto chain = m_node.chain.get();
     219                 :           1 :     const auto NUM_WALLETS{5};
     220                 :             : 
     221                 :             :     // Since we're counting the number of wallets, ensure we start without any.
     222   [ +  -  +  -  :           2 :     BOOST_REQUIRE(chain->getRwSetting("wallet").isNull());
                   +  - ]
     223                 :             : 
     224                 :           3 :     const auto& check_concurrent_wallet = [&](const auto& settings_function, int num_expected_wallets) {
     225                 :           2 :         std::vector<std::thread> threads;
     226         [ +  - ]:           2 :         threads.reserve(NUM_WALLETS);
     227   [ +  -  +  + ]:          12 :         for (auto i{0}; i < NUM_WALLETS; ++i) threads.emplace_back(settings_function, i);
     228   [ +  -  +  + ]:          12 :         for (auto& t : threads) t.join();
     229                 :             : 
     230   [ +  -  +  - ]:           2 :         auto wallets = chain->getRwSetting("wallet");
     231   [ +  -  +  -  :           2 :         BOOST_CHECK_EQUAL(wallets.getValues().size(), num_expected_wallets);
                   +  - ]
     232                 :           3 :     };
     233                 :             : 
     234                 :             :     // Add NUM_WALLETS wallets concurrently, ensure we end up with NUM_WALLETS stored.
     235                 :           6 :     check_concurrent_wallet([&chain](int i) {
     236   [ +  -  +  - ]:           5 :         Assert(AddWalletSetting(*chain, strprintf("wallet_%d", i)));
     237                 :           5 :     },
     238                 :             :                             /*num_expected_wallets=*/NUM_WALLETS);
     239                 :             : 
     240                 :             :     // Remove NUM_WALLETS wallets concurrently, ensure we end up with 0 wallets.
     241                 :           6 :     check_concurrent_wallet([&chain](int i) {
     242   [ +  -  +  - ]:           5 :         Assert(RemoveWalletSetting(*chain, strprintf("wallet_%d", i)));
     243                 :           5 :     },
     244                 :             :                             /*num_expected_wallets=*/0);
     245                 :           1 : }
     246                 :             : 
     247                 :           6 : static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
     248                 :             : {
     249                 :           6 :     CMutableTransaction tx;
     250         [ +  - ]:           6 :     TxState state = TxStateInactive{};
     251                 :           6 :     tx.nLockTime = lockTime;
     252         [ +  - ]:           6 :     SetMockTime(mockTime);
     253                 :           6 :     CBlockIndex* block = nullptr;
     254         [ +  + ]:           6 :     if (blockTime > 0) {
     255         [ +  - ]:           5 :         LOCK(cs_main);
     256         [ +  - ]:           5 :         auto inserted = chainman.BlockIndex().emplace(std::piecewise_construct, std::make_tuple(GetRandHash()), std::make_tuple());
     257         [ -  + ]:           5 :         assert(inserted.second);
     258                 :           5 :         const uint256& hash = inserted.first->first;
     259                 :           5 :         block = &inserted.first->second;
     260                 :           5 :         block->nTime = blockTime;
     261                 :           5 :         block->phashBlock = &hash;
     262         [ +  - ]:           5 :         state = TxStateConfirmed{hash, block->nHeight, /*index=*/0};
     263                 :           5 :     }
     264   [ +  -  +  - ]:          18 :     return wallet.AddToWallet(MakeTransactionRef(tx), state, [&](CWalletTx& wtx, bool /* new_tx */) {
     265                 :             :         // Assign wtx.m_state to simplify test and avoid the need to simulate
     266                 :             :         // reorg events. Without this, AddToWallet asserts false when the same
     267                 :             :         // transaction is confirmed in different blocks.
     268                 :           6 :         wtx.m_state = state;
     269                 :           6 :         return true;
     270         [ +  - ]:           6 :     })->nTimeSmart;
     271                 :           6 : }
     272                 :             : 
     273                 :             : // Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
     274                 :             : // expanded to cover more corner cases of smart time logic.
     275   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     276                 :             : {
     277                 :             :     // New transaction should use clock time if lower than block time.
     278         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100, 120), 100);
     279                 :             : 
     280                 :             :     // Test that updating existing transaction does not change smart time.
     281         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200, 220), 100);
     282                 :             : 
     283                 :             :     // New transaction should use clock time if there's no block time.
     284         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300, 0), 300);
     285                 :             : 
     286                 :             :     // New transaction should use block time if lower than clock time.
     287         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420, 400), 400);
     288                 :             : 
     289                 :             :     // New transaction should use latest entry time if higher than
     290                 :             :     // min(block time, clock time).
     291         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500, 390), 400);
     292                 :             : 
     293                 :             :     // If there are future entries, new transaction should use time of the
     294                 :             :     // newest entry that is no more than 300 seconds ahead of the clock time.
     295         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50, 600), 300);
     296                 :           1 : }
     297                 :             : 
     298                 :           3 : void TestLoadWallet(const std::string& name, DatabaseFormat format, std::function<void(std::shared_ptr<CWallet>)> f)
     299                 :             : {
     300                 :           3 :     node::NodeContext node;
     301         [ +  - ]:           3 :     auto chain{interfaces::MakeChain(node)};
     302         [ +  - ]:           3 :     DatabaseOptions options;
     303         [ +  - ]:           3 :     options.require_format = format;
     304                 :           3 :     DatabaseStatus status;
     305         [ +  - ]:           3 :     bilingual_str error;
     306                 :           3 :     std::vector<bilingual_str> warnings;
     307         [ +  - ]:           3 :     auto database{MakeWalletDatabase(name, options, status, error)};
     308         [ +  - ]:           3 :     auto wallet{std::make_shared<CWallet>(chain.get(), "", std::move(database))};
     309   [ +  -  +  -  :           3 :     BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::LOAD_OK);
                   +  - ]
     310   [ +  -  +  -  :          15 :     WITH_LOCK(wallet->cs_wallet, f(wallet));
             +  -  +  - ]
     311                 :           6 : }
     312                 :             : 
     313   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(LoadReceiveRequests, TestingSetup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     314                 :             : {
     315         [ +  + ]:           2 :     for (DatabaseFormat format : DATABASE_FORMATS) {
     316                 :           1 :         const std::string name{strprintf("receive-requests-%i", format)};
     317         [ +  - ]:           2 :         TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
     318   [ +  -  +  - ]:           2 :             BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
     319                 :           1 :             WalletBatch batch{wallet->GetDatabase()};
     320   [ +  -  +  -  :           2 :             BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), true));
             +  -  +  - ]
     321   [ +  -  +  -  :           2 :             BOOST_CHECK(batch.WriteAddressPreviouslySpent(ScriptHash(), true));
             +  -  +  - ]
     322   [ +  -  +  -  :           2 :             BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "0", "val_rr00"));
          +  -  +  -  +  
                -  +  - ]
     323   [ +  -  +  -  :           2 :             BOOST_CHECK(wallet->EraseAddressReceiveRequest(batch, PKHash(), "0"));
          +  -  +  -  +  
                      - ]
     324   [ +  -  +  -  :           2 :             BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr10"));
          +  -  +  -  +  
                -  +  - ]
     325   [ +  -  +  -  :           2 :             BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr11"));
          +  -  +  -  +  
                -  +  - ]
     326   [ +  -  +  -  :           2 :             BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, ScriptHash(), "2", "val_rr20"));
          +  -  +  -  +  
                      - ]
     327                 :           1 :         });
     328         [ +  - ]:           2 :         TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
     329   [ +  -  +  - ]:           2 :             BOOST_CHECK(wallet->IsAddressPreviouslySpent(PKHash()));
     330   [ +  -  +  - ]:           2 :             BOOST_CHECK(wallet->IsAddressPreviouslySpent(ScriptHash()));
     331                 :           1 :             auto requests = wallet->GetAddressReceiveRequests();
     332                 :           1 :             auto erequests = {"val_rr11", "val_rr20"};
     333   [ +  -  +  -  :           2 :             BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
                   +  - ]
     334         [ +  - ]:           1 :             RunWithinTxn(wallet->GetDatabase(), /*process_desc*/"test", [](WalletBatch& batch){
     335   [ +  -  +  - ]:           2 :                 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), false));
     336   [ +  -  +  - ]:           2 :                 BOOST_CHECK(batch.EraseAddressData(ScriptHash()));
     337                 :           1 :                 return true;
     338                 :             :             });
     339                 :           1 :         });
     340         [ +  - ]:           3 :         TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
     341   [ +  -  +  - ]:           2 :             BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
     342   [ +  -  +  - ]:           2 :             BOOST_CHECK(!wallet->IsAddressPreviouslySpent(ScriptHash()));
     343                 :           1 :             auto requests = wallet->GetAddressReceiveRequests();
     344                 :           1 :             auto erequests = {"val_rr11"};
     345   [ +  -  +  -  :           2 :             BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
                   +  - ]
     346                 :           1 :         });
     347                 :           1 :     }
     348                 :           1 : }
     349                 :             : 
     350                 :             : class ListCoinsTestingSetup : public TestChain100Setup
     351                 :             : {
     352                 :             : public:
     353                 :           2 :     ListCoinsTestingSetup()
     354         [ +  - ]:           2 :     {
     355   [ +  -  +  -  :           4 :         CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
                   +  - ]
     356   [ +  -  +  -  :           6 :         wallet = CreateSyncedWallet(*m_node.chain, WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain()), coinbaseKey);
          +  -  -  +  -  
             +  +  -  +  
                      - ]
     357   [ +  -  -  - ]:           4 :     }
     358                 :             : 
     359                 :           2 :     ~ListCoinsTestingSetup()
     360                 :             :     {
     361         [ +  - ]:           2 :         wallet.reset();
     362         [ -  + ]:           2 :     }
     363                 :             : 
     364                 :           5 :     CWalletTx& AddTx(CRecipient recipient)
     365                 :             :     {
     366                 :           5 :         CTransactionRef tx;
     367         [ +  - ]:           5 :         CCoinControl dummy;
     368                 :           5 :         {
     369   [ +  -  +  -  :          15 :             auto res = CreateTransaction(*wallet, {recipient}, /*change_pos=*/std::nullopt, dummy);
             +  +  -  - ]
     370   [ +  -  +  - ]:          10 :             BOOST_CHECK(res);
     371                 :           5 :             tx = res->tx;
     372                 :           0 :         }
     373   [ +  -  +  - ]:          15 :         wallet->CommitTransaction(tx, {}, {});
     374         [ +  - ]:           5 :         CMutableTransaction blocktx;
     375                 :           5 :         {
     376         [ +  - ]:           5 :             LOCK(wallet->cs_wallet);
     377   [ +  -  +  - ]:           5 :             blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).tx);
     378                 :           0 :         }
     379   [ +  -  +  -  :          20 :         CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
          +  -  +  -  +  
                +  -  - ]
     380                 :             : 
     381         [ +  - ]:           5 :         LOCK(wallet->cs_wallet);
     382   [ +  -  +  - ]:           5 :         LOCK(Assert(m_node.chainman)->GetMutex());
     383   [ +  -  +  -  :          10 :         wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
                   +  - ]
     384         [ +  - ]:           5 :         auto it = wallet->mapWallet.find(tx->GetHash());
     385   [ +  -  +  -  :          15 :         BOOST_CHECK(it != wallet->mapWallet.end());
             +  -  +  - ]
     386   [ +  -  +  -  :          10 :         it->second.m_state = TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/1};
                   +  - ]
     387         [ +  - ]:           5 :         return it->second;
     388   [ +  -  +  -  :          30 :     }
          +  -  +  -  +  
                      - ]
     389                 :             : 
     390                 :             :     std::unique_ptr<CWallet> wallet;
     391                 :             : };
     392                 :             : 
     393   [ +  -  +  -  :          10 : BOOST_FIXTURE_TEST_CASE(ListCoinsTest, ListCoinsTestingSetup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     394                 :             : {
     395                 :           1 :     std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
     396                 :             : 
     397                 :             :     // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
     398                 :             :     // address.
     399         [ +  - ]:           1 :     std::map<CTxDestination, std::vector<COutput>> list;
     400                 :           1 :     {
     401         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     402   [ +  -  +  - ]:           2 :         list = ListCoins(*wallet);
     403                 :           0 :     }
     404   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(list.size(), 1U);
     405   [ +  -  -  +  :           1 :     BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
             +  -  +  - ]
     406   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
     407                 :             : 
     408                 :             :     // Check initial balance from one mature coinbase transaction.
     409   [ +  -  +  -  :           3 :     BOOST_CHECK_EQUAL(50 * COIN, WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet).GetTotalAmount()));
                   +  - ]
     410                 :             : 
     411                 :             :     // Add a transaction creating a change address, and confirm ListCoins still
     412                 :             :     // returns the coin associated with the change address underneath the
     413                 :             :     // coinbaseKey pubkey, even though the change address has a different
     414                 :             :     // pubkey.
     415         [ +  - ]:           1 :     AddTx(CRecipient{PubKeyDestination{{}}, 1 * COIN, /*subtract_fee=*/false});
     416                 :           1 :     {
     417         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     418   [ +  -  +  - ]:           2 :         list = ListCoins(*wallet);
     419                 :           0 :     }
     420   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(list.size(), 1U);
     421   [ +  -  -  +  :           1 :     BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
             +  -  +  - ]
     422   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
     423                 :             : 
     424                 :             :     // Lock both coins. Confirm number of available coins drops to 0.
     425                 :           1 :     {
     426         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     427   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(AvailableCoinsListUnspent(*wallet).Size(), 2U);
          +  -  +  -  +  
                      - ]
     428                 :           0 :     }
     429         [ +  + ]:           2 :     for (const auto& group : list) {
     430         [ +  + ]:           3 :         for (const auto& coin : group.second) {
     431         [ +  - ]:           2 :             LOCK(wallet->cs_wallet);
     432         [ +  - ]:           2 :             wallet->LockCoin(coin.outpoint);
     433                 :           2 :         }
     434                 :             :     }
     435                 :           1 :     {
     436         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     437   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(AvailableCoinsListUnspent(*wallet).Size(), 0U);
          +  -  +  -  +  
                      - ]
     438                 :           0 :     }
     439                 :             :     // Confirm ListCoins still returns same result as before, despite coins
     440                 :             :     // being locked.
     441                 :           1 :     {
     442         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     443   [ +  -  +  - ]:           2 :         list = ListCoins(*wallet);
     444                 :           0 :     }
     445   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(list.size(), 1U);
     446   [ +  -  -  +  :           1 :     BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
             +  -  +  - ]
     447   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
     448                 :           1 : }
     449                 :             : 
     450                 :           4 : void TestCoinsResult(ListCoinsTest& context, OutputType out_type, CAmount amount,
     451                 :             :                      std::map<OutputType, size_t>& expected_coins_sizes)
     452                 :             : {
     453                 :           4 :     LOCK(context.wallet->cs_wallet);
     454   [ +  -  +  -  :           4 :     util::Result<CTxDestination> dest = Assert(context.wallet->GetNewDestination(out_type, ""));
                   +  - ]
     455   [ +  -  +  - ]:           8 :     CWalletTx& wtx = context.AddTx(CRecipient{*dest, amount, /*fSubtractFeeFromAmount=*/true});
     456                 :           4 :     CoinFilterParams filter;
     457                 :           4 :     filter.skip_locked = false;
     458         [ +  - ]:           4 :     CoinsResult available_coins = AvailableCoins(*context.wallet, nullptr, std::nullopt, filter);
     459                 :             :     // Lock outputs so they are not spent in follow-up transactions
     460   [ +  -  +  + ]:          12 :     for (uint32_t i = 0; i < wtx.tx->vout.size(); i++) context.wallet->LockCoin({wtx.GetHash(), i});
     461   [ +  -  +  -  :          24 :     for (const auto& [type, size] : expected_coins_sizes) BOOST_CHECK_EQUAL(size, available_coins.coins[type].size());
             +  -  +  + ]
     462         [ +  - ]:           8 : }
     463                 :             : 
     464   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(BasicOutputTypesTest, ListCoinsTest)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     465                 :             : {
     466                 :           1 :     std::map<OutputType, size_t> expected_coins_sizes;
     467   [ +  -  +  + ]:           5 :     for (const auto& out_type : OUTPUT_TYPES) { expected_coins_sizes[out_type] = 0U; }
     468                 :             : 
     469                 :             :     // Verify our wallet has one usable coinbase UTXO before starting
     470                 :             :     // This UTXO is a P2PK, so it should show up in the Other bucket
     471         [ +  - ]:           1 :     expected_coins_sizes[OutputType::UNKNOWN] = 1U;
     472         [ +  - ]:           3 :     CoinsResult available_coins = WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet));
     473   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(available_coins.Size(), expected_coins_sizes[OutputType::UNKNOWN]);
             +  -  +  - ]
     474   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(available_coins.coins[OutputType::UNKNOWN].size(), expected_coins_sizes[OutputType::UNKNOWN]);
             +  -  +  - ]
     475                 :             : 
     476                 :             :     // We will create a self transfer for each of the OutputTypes and
     477                 :             :     // verify it is put in the correct bucket after running GetAvailablecoins
     478                 :             :     //
     479                 :             :     // For each OutputType, We expect 2 UTXOs in our wallet following the self transfer:
     480                 :             :     //   1. One UTXO as the recipient
     481                 :             :     //   2. One UTXO from the change, due to payment address matching logic
     482                 :             : 
     483         [ +  + ]:           5 :     for (const auto& out_type : OUTPUT_TYPES) {
     484         [ -  + ]:           4 :         if (out_type == OutputType::UNKNOWN) continue;
     485         [ +  - ]:           4 :         expected_coins_sizes[out_type] = 2U;
     486         [ +  - ]:           4 :         TestCoinsResult(*this, out_type, 1 * COIN, expected_coins_sizes);
     487                 :             :     }
     488                 :           1 : }
     489                 :             : 
     490   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(wallet_disableprivkeys, TestChain100Setup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     491                 :             : {
     492   [ +  -  +  - ]:           1 :     const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
     493         [ +  - ]:           1 :     LOCK(wallet->cs_wallet);
     494         [ +  - ]:           1 :     wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
     495         [ +  - ]:           1 :     wallet->SetMinVersion(FEATURE_LATEST);
     496         [ +  - ]:           1 :     wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
     497   [ +  -  +  -  :           2 :     BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, ""));
          +  -  +  -  +  
                      - ]
     498         [ +  - ]:           2 : }
     499                 :             : 
     500                 :             : // Explicit calculation which is used to test the wallet constant
     501                 :             : // We get the same virtual size due to rounding(weight/4) for both use_max_sig values
     502                 :           2 : static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
     503                 :             : {
     504                 :             :     // Generate ephemeral valid pubkey
     505                 :           2 :     CKey key = GenerateRandomKey();
     506         [ +  - ]:           2 :     CPubKey pubkey = key.GetPubKey();
     507                 :             : 
     508                 :             :     // Generate pubkey hash
     509         [ +  - ]:           2 :     uint160 key_hash(Hash160(pubkey));
     510                 :             : 
     511                 :             :     // Create inner-script to enter into keystore. Key hash can't be 0...
     512   [ +  -  +  - ]:           2 :     CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end());
     513                 :             : 
     514                 :             :     // Create outer P2SH script for the output
     515         [ +  - ]:           2 :     uint160 script_id(Hash160(inner_script));
     516   [ +  -  +  -  :           2 :     CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL;
                   +  - ]
     517                 :             : 
     518                 :             :     // Add inner-script to key store and key to watchonly
     519                 :           2 :     FillableSigningProvider keystore;
     520         [ +  - ]:           2 :     keystore.AddCScript(inner_script);
     521         [ +  - ]:           2 :     keystore.AddKeyPubKey(key, pubkey);
     522                 :             : 
     523                 :             :     // Fill in dummy signatures for fee calculation.
     524                 :           2 :     SignatureData sig_data;
     525                 :             : 
     526   [ +  +  +  -  :           2 :     if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) {
                   -  + ]
     527                 :             :         // We're hand-feeding it correct arguments; shouldn't happen
     528                 :           0 :         assert(false);
     529                 :             :     }
     530                 :             : 
     531                 :           2 :     CTxIn tx_in;
     532         [ +  - ]:           2 :     UpdateInput(tx_in, sig_data);
     533         [ +  - ]:           2 :     return (size_t)GetVirtualTransactionInputSize(tx_in);
     534                 :           2 : }
     535                 :             : 
     536   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(dummy_input_size_test, TestChain100Setup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     537                 :             : {
     538         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(CalculateNestedKeyhashInputSize(false), DUMMY_NESTED_P2WPKH_INPUT_SIZE);
     539         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(CalculateNestedKeyhashInputSize(true), DUMMY_NESTED_P2WPKH_INPUT_SIZE);
     540                 :           1 : }
     541                 :             : 
     542                 :           1 : bool malformed_descriptor(std::ios_base::failure e)
     543                 :             : {
     544                 :           1 :     std::string s(e.what());
     545                 :           1 :     return s.find("Missing checksum") != std::string::npos;
     546                 :           1 : }
     547                 :             : 
     548   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(wallet_descriptor_test, BasicTestingSetup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     549                 :             : {
     550                 :           1 :     std::vector<unsigned char> malformed_record;
     551         [ +  - ]:           1 :     VectorWriter vw{malformed_record, 0};
     552         [ +  - ]:           2 :     vw << std::string("notadescriptor");
     553         [ +  - ]:           1 :     vw << uint64_t{0};
     554         [ +  - ]:           1 :     vw << int32_t{0};
     555         [ +  - ]:           1 :     vw << int32_t{0};
     556         [ +  - ]:           1 :     vw << int32_t{1};
     557                 :             : 
     558                 :           1 :     SpanReader vr{malformed_record};
     559                 :           1 :     WalletDescriptor w_desc;
     560   [ +  -  -  +  :           2 :     BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure, malformed_descriptor);
          -  -  -  -  -  
          +  +  -  +  -  
                   +  - ]
     561                 :           1 : }
     562                 :             : 
     563                 :             : //! Test CWallet::Create() and its behavior handling potential race
     564                 :             : //! conditions if it's called the same time an incoming transaction shows up in
     565                 :             : //! the mempool or a new block.
     566                 :             : //!
     567                 :             : //! It isn't possible to verify there aren't race condition in every case, so
     568                 :             : //! this test just checks two specific cases and ensures that timing of
     569                 :             : //! notifications in these cases doesn't prevent the wallet from detecting
     570                 :             : //! transactions.
     571                 :             : //!
     572                 :             : //! In the first case, block and mempool transactions are created before the
     573                 :             : //! wallet is loaded, but notifications about these transactions are delayed
     574                 :             : //! until after it is loaded. The notifications are superfluous in this case, so
     575                 :             : //! the test verifies the transactions are detected before they arrive.
     576                 :             : //!
     577                 :             : //! In the second case, block and mempool transactions are created after the
     578                 :             : //! wallet rescan and notifications are immediately synced, to verify the wallet
     579                 :             : //! must already have a handler in place for them, and there's no gap after
     580                 :             : //! rescanning where new transactions in new blocks could be lost.
     581   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(CreateWallet, TestChain100Setup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     582                 :             : {
     583   [ +  -  +  - ]:           2 :     m_args.ForceSetArg("-unsafesqlitesync", "1");
     584                 :             :     // Create new wallet with known key and unload it.
     585                 :           1 :     WalletContext context;
     586                 :           1 :     context.args = &m_args;
     587         [ +  - ]:           1 :     context.chain = m_node.chain.get();
     588         [ +  - ]:           1 :     auto wallet = TestLoadWallet(context);
     589                 :           1 :     CKey key = GenerateRandomKey();
     590         [ +  - ]:           1 :     AddKey(*wallet, key);
     591         [ +  - ]:           1 :     TestUnloadWallet(std::move(wallet));
     592                 :             : 
     593                 :             : 
     594                 :             :     // Add log hook to detect AddToWallet events from rescans, blockConnected,
     595                 :             :     // and transactionAddedToMempool notifications
     596                 :           1 :     int addtx_count = 0;
     597         [ +  - ]:          11 :     DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) {
     598         [ +  + ]:          10 :         if (s) ++addtx_count;
     599                 :          10 :         return false;
     600   [ +  -  +  - ]:           2 :     });
     601                 :             : 
     602                 :             : 
     603                 :           1 :     bool rescan_completed = false;
     604         [ +  - ]:           3 :     DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) {
     605         [ +  + ]:           2 :         if (s) rescan_completed = true;
     606                 :           2 :         return false;
     607   [ +  -  +  - ]:           2 :     });
     608                 :             : 
     609                 :             : 
     610                 :             :     // Block the queue to prevent the wallet receiving blockConnected and
     611                 :             :     // transactionAddedToMempool notifications, and create block and mempool
     612                 :             :     // transactions paying to the wallet
     613         [ +  - ]:           1 :     std::promise<void> promise;
     614         [ +  - ]:           2 :     m_node.validation_signals->CallFunctionInValidationInterfaceQueue([&promise] {
     615         [ +  - ]:           1 :         promise.get_future().wait();
     616                 :           1 :     });
     617         [ +  - ]:           1 :     std::string error;
     618   [ +  -  +  -  :           2 :     m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
             +  -  +  - ]
     619   [ +  -  +  -  :           1 :     auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
                   +  - ]
     620   [ +  -  +  -  :           4 :     m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
          +  -  +  -  +  
             -  +  +  -  
                      - ]
     621   [ +  -  +  -  :           1 :     auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
                   +  - ]
     622   [ +  -  +  -  :           4 :     BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
          +  -  +  -  +  
                -  +  - ]
     623                 :             : 
     624                 :             : 
     625                 :             :     // Reload wallet and make sure new transactions are detected despite events
     626                 :             :     // being blocked
     627                 :             :     // Loading will also ask for current mempool transactions
     628   [ +  -  -  + ]:           2 :     wallet = TestLoadWallet(context);
     629   [ +  -  +  -  :           2 :     BOOST_CHECK(rescan_completed);
                   +  - ]
     630                 :             :     // AddToWallet events for block_tx and mempool_tx (x2)
     631   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(addtx_count, 3);
     632                 :           1 :     {
     633         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     634   [ +  -  +  -  :           2 :         BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
                   +  - ]
     635   [ +  -  +  -  :           2 :         BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
             +  -  +  - ]
     636                 :           0 :     }
     637                 :             : 
     638                 :             : 
     639                 :             :     // Unblock notification queue and make sure stale blockConnected and
     640                 :             :     // transactionAddedToMempool events are processed
     641         [ +  - ]:           1 :     promise.set_value();
     642         [ +  - ]:           1 :     m_node.validation_signals->SyncWithValidationInterfaceQueue();
     643                 :             :     // AddToWallet events for block_tx and mempool_tx events are counted a
     644                 :             :     // second time as the notification queue is processed
     645   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(addtx_count, 5);
     646                 :             : 
     647                 :             : 
     648         [ +  - ]:           1 :     TestUnloadWallet(std::move(wallet));
     649                 :             : 
     650                 :             : 
     651                 :             :     // Load wallet again, this time creating new block and mempool transactions
     652                 :             :     // paying to the wallet as the wallet finishes loading and syncing the
     653                 :             :     // queue so the events have to be handled immediately. Releasing the wallet
     654                 :             :     // lock during the sync is a little artificial but is needed to avoid a
     655                 :             :     // deadlock during the sync and simulates a new block notification happening
     656                 :             :     // as soon as possible.
     657                 :           1 :     addtx_count = 0;
     658         [ +  - ]:           2 :     auto handler = HandleLoadWallet(context, [&](std::unique_ptr<interfaces::Wallet> wallet) {
     659         [ +  - ]:           2 :             BOOST_CHECK(rescan_completed);
     660   [ +  -  +  - ]:           2 :             m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
     661         [ +  - ]:           2 :             block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
     662   [ +  -  +  -  :           4 :             m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
          +  -  +  +  -  
                      - ]
     663         [ +  - ]:           2 :             mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
     664   [ +  -  +  -  :           4 :             BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
             +  -  +  - ]
     665                 :           1 :             m_node.validation_signals->SyncWithValidationInterfaceQueue();
     666         [ +  - ]:           3 :         });
     667   [ +  -  -  + ]:           2 :     wallet = TestLoadWallet(context);
     668                 :             :     // Since mempool transactions are requested at the end of loading, there will
     669                 :             :     // be 2 additional AddToWallet calls, one from the previous test, and a duplicate for mempool_tx
     670   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(addtx_count, 2 + 2);
     671                 :           1 :     {
     672         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     673   [ +  -  +  -  :           2 :         BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
                   +  - ]
     674   [ +  -  +  -  :           2 :         BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
             +  -  +  - ]
     675                 :           0 :     }
     676                 :             : 
     677                 :             : 
     678         [ +  - ]:           1 :     TestUnloadWallet(std::move(wallet));
     679   [ +  -  +  -  :           5 : }
             +  -  -  + ]
     680                 :             : 
     681   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(CreateWalletWithoutChain, BasicTestingSetup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     682                 :             : {
     683                 :           1 :     WalletContext context;
     684                 :           1 :     context.args = &m_args;
     685         [ +  - ]:           1 :     auto wallet = TestLoadWallet(context);
     686   [ +  -  +  -  :           2 :     BOOST_CHECK(wallet);
                   +  - ]
     687         [ +  - ]:           1 :     WaitForDeleteWallet(std::move(wallet));
     688                 :           1 : }
     689                 :             : 
     690   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(RemoveTxs, TestChain100Setup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     691                 :             : {
     692   [ +  -  +  - ]:           2 :     m_args.ForceSetArg("-unsafesqlitesync", "1");
     693                 :           1 :     WalletContext context;
     694                 :           1 :     context.args = &m_args;
     695         [ +  - ]:           1 :     context.chain = m_node.chain.get();
     696         [ +  - ]:           1 :     auto wallet = TestLoadWallet(context);
     697                 :           1 :     CKey key = GenerateRandomKey();
     698         [ +  - ]:           1 :     AddKey(*wallet, key);
     699                 :             : 
     700         [ +  - ]:           1 :     std::string error;
     701   [ +  -  +  -  :           2 :     m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
             +  -  +  - ]
     702   [ +  -  +  -  :           1 :     auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
                   +  - ]
     703   [ +  -  +  -  :           4 :     CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
          +  -  +  -  +  
                +  -  - ]
     704                 :             : 
     705         [ +  - ]:           1 :     m_node.validation_signals->SyncWithValidationInterfaceQueue();
     706                 :             : 
     707                 :           1 :     {
     708         [ +  - ]:           1 :         auto block_hash = block_tx.GetHash();
     709         [ +  - ]:           1 :         auto prev_tx = m_coinbase_txns[0];
     710                 :             : 
     711         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     712   [ +  -  +  -  :           2 :         BOOST_CHECK(wallet->HasWalletSpend(prev_tx));
             +  -  +  - ]
     713   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 1u);
                   +  - ]
     714                 :             : 
     715         [ +  - ]:           1 :         std::vector<Txid> vHashIn{ block_hash };
     716   [ +  -  +  -  :           2 :         BOOST_CHECK(wallet->RemoveTxs(vHashIn));
             +  -  +  - ]
     717                 :             : 
     718   [ +  -  +  -  :           2 :         BOOST_CHECK(!wallet->HasWalletSpend(prev_tx));
             +  -  +  - ]
     719   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 0u);
                   +  - ]
     720   [ +  -  +  - ]:           2 :     }
     721                 :             : 
     722         [ +  - ]:           1 :     TestUnloadWallet(std::move(wallet));
     723   [ +  -  -  + ]:           2 : }
     724                 :             : 
     725                 :             : BOOST_AUTO_TEST_SUITE_END()
     726                 :             : } // namespace wallet
        

Generated by: LCOV version 2.0-1