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: 96.7 % 513 496
Test Date: 2025-06-01 05:54:06 Functions: 100.0 % 58 58
Branches: 50.4 % 2272 1144

             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                 :             : 
      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                 :           7 : static void AddKey(CWallet& wallet, const CKey& key)
      61                 :             : {
      62                 :           7 :     LOCK(wallet.cs_wallet);
      63                 :           7 :     FlatSigningProvider provider;
      64         [ +  - ]:           7 :     std::string error;
      65   [ +  -  +  -  :          21 :     auto descs = Parse("combo(" + EncodeSecret(key) + ")", provider, error, /* require_checksum=*/ false);
                   +  - ]
      66         [ -  + ]:           7 :     assert(descs.size() == 1);
      67         [ +  - ]:           7 :     auto& desc = descs.at(0);
      68   [ +  -  +  - ]:           7 :     WalletDescriptor w_desc(std::move(desc), 0, 0, 1, 1);
      69   [ +  -  +  -  :          14 :     Assert(wallet.AddWalletDescriptor(w_desc, provider, "", false));
                   +  - ]
      70         [ +  - ]:          14 : }
      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         [ +  - ]:           1 :         }
     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                 :             : // Check that GetImmatureCredit() returns a newly calculated value instead of
     248                 :             : // the cached value after a MarkDirty() call.
     249                 :             : //
     250                 :             : // This is a regression test written to verify a bugfix for the immature credit
     251                 :             : // function. Similar tests probably should be written for the other credit and
     252                 :             : // debit functions.
     253   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     254                 :             : {
     255   [ +  -  +  -  :           2 :     CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
                   +  - ]
     256                 :             : 
     257         [ +  - ]:           1 :     LOCK(wallet.cs_wallet);
     258   [ +  -  +  - ]:           1 :     LOCK(Assert(m_node.chainman)->GetMutex());
     259   [ +  -  +  -  :           3 :     CWalletTx wtx{m_coinbase_txns.back(), TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/0}};
          +  -  +  -  -  
                      + ]
     260         [ +  - ]:           1 :     wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
     261         [ +  - ]:           1 :     wallet.SetupDescriptorScriptPubKeyMans();
     262                 :             : 
     263   [ +  -  +  -  :           2 :     wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
             +  -  +  - ]
     264                 :             : 
     265                 :             :     // Call GetImmatureCredit() once before adding the key to the wallet to
     266                 :             :     // cache the current immature credit amount, which is 0.
     267   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(CachedTxGetImmatureCredit(wallet, wtx, ISMINE_SPENDABLE), 0);
                   +  - ]
     268                 :             : 
     269                 :             :     // Invalidate the cached value, add the key, and make sure a new immature
     270                 :             :     // credit amount is calculated.
     271         [ +  - ]:           1 :     wtx.MarkDirty();
     272         [ +  - ]:           1 :     AddKey(wallet, coinbaseKey);
     273   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(CachedTxGetImmatureCredit(wallet, wtx, ISMINE_SPENDABLE), 50*COIN);
                   +  - ]
     274   [ +  -  +  - ]:           3 : }
     275                 :             : 
     276                 :           6 : static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime)
     277                 :             : {
     278                 :           6 :     CMutableTransaction tx;
     279         [ +  - ]:           6 :     TxState state = TxStateInactive{};
     280                 :           6 :     tx.nLockTime = lockTime;
     281         [ +  - ]:           6 :     SetMockTime(mockTime);
     282                 :           6 :     CBlockIndex* block = nullptr;
     283         [ +  + ]:           6 :     if (blockTime > 0) {
     284         [ +  - ]:           5 :         LOCK(cs_main);
     285         [ +  - ]:           5 :         auto inserted = chainman.BlockIndex().emplace(std::piecewise_construct, std::make_tuple(GetRandHash()), std::make_tuple());
     286         [ -  + ]:           5 :         assert(inserted.second);
     287                 :           5 :         const uint256& hash = inserted.first->first;
     288                 :           5 :         block = &inserted.first->second;
     289                 :           5 :         block->nTime = blockTime;
     290                 :           5 :         block->phashBlock = &hash;
     291         [ +  - ]:           5 :         state = TxStateConfirmed{hash, block->nHeight, /*index=*/0};
     292                 :           5 :     }
     293   [ +  -  +  - ]:          18 :     return wallet.AddToWallet(MakeTransactionRef(tx), state, [&](CWalletTx& wtx, bool /* new_tx */) {
     294                 :             :         // Assign wtx.m_state to simplify test and avoid the need to simulate
     295                 :             :         // reorg events. Without this, AddToWallet asserts false when the same
     296                 :             :         // transaction is confirmed in different blocks.
     297                 :           6 :         wtx.m_state = state;
     298                 :           6 :         return true;
     299         [ +  - ]:           6 :     })->nTimeSmart;
     300                 :           6 : }
     301                 :             : 
     302                 :             : // Simple test to verify assignment of CWalletTx::nSmartTime value. Could be
     303                 :             : // expanded to cover more corner cases of smart time logic.
     304   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(ComputeTimeSmart)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     305                 :             : {
     306                 :             :     // New transaction should use clock time if lower than block time.
     307         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100, 120), 100);
     308                 :             : 
     309                 :             :     // Test that updating existing transaction does not change smart time.
     310         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200, 220), 100);
     311                 :             : 
     312                 :             :     // New transaction should use clock time if there's no block time.
     313         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300, 0), 300);
     314                 :             : 
     315                 :             :     // New transaction should use block time if lower than clock time.
     316         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420, 400), 400);
     317                 :             : 
     318                 :             :     // New transaction should use latest entry time if higher than
     319                 :             :     // min(block time, clock time).
     320         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500, 390), 400);
     321                 :             : 
     322                 :             :     // If there are future entries, new transaction should use time of the
     323                 :             :     // newest entry that is no more than 300 seconds ahead of the clock time.
     324         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50, 600), 300);
     325                 :           1 : }
     326                 :             : 
     327                 :           3 : void TestLoadWallet(const std::string& name, DatabaseFormat format, std::function<void(std::shared_ptr<CWallet>)> f)
     328                 :             : {
     329                 :           3 :     node::NodeContext node;
     330         [ +  - ]:           3 :     auto chain{interfaces::MakeChain(node)};
     331         [ +  - ]:           3 :     DatabaseOptions options;
     332         [ +  - ]:           3 :     options.require_format = format;
     333                 :           3 :     DatabaseStatus status;
     334         [ +  - ]:           3 :     bilingual_str error;
     335                 :           3 :     std::vector<bilingual_str> warnings;
     336         [ +  - ]:           3 :     auto database{MakeWalletDatabase(name, options, status, error)};
     337         [ +  - ]:           3 :     auto wallet{std::make_shared<CWallet>(chain.get(), "", std::move(database))};
     338   [ +  -  +  -  :           3 :     BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::LOAD_OK);
                   +  - ]
     339   [ +  -  +  -  :          15 :     WITH_LOCK(wallet->cs_wallet, f(wallet));
             +  -  +  - ]
     340                 :           6 : }
     341                 :             : 
     342   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(LoadReceiveRequests, TestingSetup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     343                 :             : {
     344         [ +  + ]:           2 :     for (DatabaseFormat format : DATABASE_FORMATS) {
     345                 :           1 :         const std::string name{strprintf("receive-requests-%i", format)};
     346         [ +  - ]:           2 :         TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
     347   [ +  -  +  - ]:           2 :             BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
     348                 :           1 :             WalletBatch batch{wallet->GetDatabase()};
     349   [ +  -  +  -  :           2 :             BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), true));
             +  -  +  - ]
     350   [ +  -  +  -  :           2 :             BOOST_CHECK(batch.WriteAddressPreviouslySpent(ScriptHash(), true));
             +  -  +  - ]
     351   [ +  -  +  -  :           2 :             BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "0", "val_rr00"));
          +  -  +  -  +  
                -  +  - ]
     352   [ +  -  +  -  :           2 :             BOOST_CHECK(wallet->EraseAddressReceiveRequest(batch, PKHash(), "0"));
          +  -  +  -  +  
                      - ]
     353   [ +  -  +  -  :           2 :             BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr10"));
          +  -  +  -  +  
                -  +  - ]
     354   [ +  -  +  -  :           2 :             BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr11"));
          +  -  +  -  +  
                -  +  - ]
     355   [ +  -  +  -  :           2 :             BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, ScriptHash(), "2", "val_rr20"));
          +  -  +  -  +  
                      - ]
     356                 :           1 :         });
     357         [ +  - ]:           2 :         TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
     358   [ +  -  +  - ]:           2 :             BOOST_CHECK(wallet->IsAddressPreviouslySpent(PKHash()));
     359   [ +  -  +  - ]:           2 :             BOOST_CHECK(wallet->IsAddressPreviouslySpent(ScriptHash()));
     360                 :           1 :             auto requests = wallet->GetAddressReceiveRequests();
     361                 :           1 :             auto erequests = {"val_rr11", "val_rr20"};
     362   [ +  -  +  -  :           2 :             BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
                   +  - ]
     363         [ +  - ]:           1 :             RunWithinTxn(wallet->GetDatabase(), /*process_desc*/"test", [](WalletBatch& batch){
     364   [ +  -  +  - ]:           2 :                 BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), false));
     365   [ +  -  +  - ]:           2 :                 BOOST_CHECK(batch.EraseAddressData(ScriptHash()));
     366                 :           1 :                 return true;
     367                 :             :             });
     368                 :           1 :         });
     369         [ +  - ]:           3 :         TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) {
     370   [ +  -  +  - ]:           2 :             BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash()));
     371   [ +  -  +  - ]:           2 :             BOOST_CHECK(!wallet->IsAddressPreviouslySpent(ScriptHash()));
     372                 :           1 :             auto requests = wallet->GetAddressReceiveRequests();
     373                 :           1 :             auto erequests = {"val_rr11"};
     374   [ +  -  +  -  :           2 :             BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests));
                   +  - ]
     375                 :           1 :         });
     376                 :           1 :     }
     377                 :           1 : }
     378                 :             : 
     379                 :             : class ListCoinsTestingSetup : public TestChain100Setup
     380                 :             : {
     381                 :             : public:
     382                 :           2 :     ListCoinsTestingSetup()
     383         [ +  - ]:           2 :     {
     384   [ +  -  +  -  :           4 :         CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
                   +  - ]
     385   [ +  -  +  -  :           6 :         wallet = CreateSyncedWallet(*m_node.chain, WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain()), coinbaseKey);
          +  -  -  +  -  
             +  +  -  +  
                      - ]
     386   [ +  -  -  - ]:           4 :     }
     387                 :             : 
     388                 :           2 :     ~ListCoinsTestingSetup()
     389                 :             :     {
     390         [ +  - ]:           2 :         wallet.reset();
     391         [ -  + ]:           2 :     }
     392                 :             : 
     393                 :           5 :     CWalletTx& AddTx(CRecipient recipient)
     394                 :             :     {
     395                 :           5 :         CTransactionRef tx;
     396         [ +  - ]:           5 :         CCoinControl dummy;
     397                 :           5 :         {
     398   [ +  -  +  -  :          15 :             auto res = CreateTransaction(*wallet, {recipient}, /*change_pos=*/std::nullopt, dummy);
             +  +  -  - ]
     399   [ +  -  +  - ]:          10 :             BOOST_CHECK(res);
     400                 :           5 :             tx = res->tx;
     401                 :           0 :         }
     402   [ +  -  +  - ]:          15 :         wallet->CommitTransaction(tx, {}, {});
     403         [ +  - ]:           5 :         CMutableTransaction blocktx;
     404                 :           5 :         {
     405         [ +  - ]:           5 :             LOCK(wallet->cs_wallet);
     406   [ +  -  +  -  :          10 :             blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).tx);
                   +  - ]
     407                 :           0 :         }
     408   [ +  -  +  -  :          20 :         CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
          +  -  +  -  +  
                +  -  - ]
     409                 :             : 
     410         [ +  - ]:           5 :         LOCK(wallet->cs_wallet);
     411   [ +  -  +  - ]:           5 :         LOCK(Assert(m_node.chainman)->GetMutex());
     412   [ +  -  +  -  :          10 :         wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
                   +  - ]
     413         [ +  - ]:           5 :         auto it = wallet->mapWallet.find(tx->GetHash());
     414   [ +  -  +  -  :          15 :         BOOST_CHECK(it != wallet->mapWallet.end());
             +  -  +  - ]
     415   [ +  -  +  -  :          10 :         it->second.m_state = TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/1};
                   +  - ]
     416         [ +  - ]:           5 :         return it->second;
     417   [ +  -  +  -  :          30 :     }
          +  -  +  -  +  
                      - ]
     418                 :             : 
     419                 :             :     std::unique_ptr<CWallet> wallet;
     420                 :             : };
     421                 :             : 
     422   [ +  -  +  -  :          10 : BOOST_FIXTURE_TEST_CASE(ListCoinsTest, ListCoinsTestingSetup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     423                 :             : {
     424                 :           1 :     std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString();
     425                 :             : 
     426                 :             :     // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey
     427                 :             :     // address.
     428         [ +  - ]:           1 :     std::map<CTxDestination, std::vector<COutput>> list;
     429                 :           1 :     {
     430         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     431   [ +  -  +  - ]:           2 :         list = ListCoins(*wallet);
     432                 :           0 :     }
     433   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(list.size(), 1U);
     434   [ +  -  -  +  :           1 :     BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
             +  -  +  - ]
     435   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U);
     436                 :             : 
     437                 :             :     // Check initial balance from one mature coinbase transaction.
     438   [ +  -  +  -  :           3 :     BOOST_CHECK_EQUAL(50 * COIN, WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet).GetTotalAmount()));
                   +  - ]
     439                 :             : 
     440                 :             :     // Add a transaction creating a change address, and confirm ListCoins still
     441                 :             :     // returns the coin associated with the change address underneath the
     442                 :             :     // coinbaseKey pubkey, even though the change address has a different
     443                 :             :     // pubkey.
     444         [ +  - ]:           1 :     AddTx(CRecipient{PubKeyDestination{{}}, 1 * COIN, /*subtract_fee=*/false});
     445                 :           1 :     {
     446         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     447   [ +  -  +  - ]:           2 :         list = ListCoins(*wallet);
     448                 :           0 :     }
     449   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(list.size(), 1U);
     450   [ +  -  -  +  :           1 :     BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
             +  -  +  - ]
     451   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
     452                 :             : 
     453                 :             :     // Lock both coins. Confirm number of available coins drops to 0.
     454                 :           1 :     {
     455         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     456   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(AvailableCoinsListUnspent(*wallet).Size(), 2U);
          +  -  +  -  +  
                      - ]
     457                 :           0 :     }
     458         [ +  + ]:           2 :     for (const auto& group : list) {
     459         [ +  + ]:           3 :         for (const auto& coin : group.second) {
     460         [ +  - ]:           2 :             LOCK(wallet->cs_wallet);
     461         [ +  - ]:           2 :             wallet->LockCoin(coin.outpoint);
     462                 :           2 :         }
     463                 :             :     }
     464                 :           1 :     {
     465         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     466   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(AvailableCoinsListUnspent(*wallet).Size(), 0U);
          +  -  +  -  +  
                      - ]
     467                 :           0 :     }
     468                 :             :     // Confirm ListCoins still returns same result as before, despite coins
     469                 :             :     // being locked.
     470                 :           1 :     {
     471         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     472   [ +  -  +  - ]:           2 :         list = ListCoins(*wallet);
     473                 :           0 :     }
     474   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(list.size(), 1U);
     475   [ +  -  -  +  :           1 :     BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress);
             +  -  +  - ]
     476   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U);
     477                 :           1 : }
     478                 :             : 
     479                 :           4 : void TestCoinsResult(ListCoinsTest& context, OutputType out_type, CAmount amount,
     480                 :             :                      std::map<OutputType, size_t>& expected_coins_sizes)
     481                 :             : {
     482                 :           4 :     LOCK(context.wallet->cs_wallet);
     483   [ +  -  +  -  :           4 :     util::Result<CTxDestination> dest = Assert(context.wallet->GetNewDestination(out_type, ""));
                   +  - ]
     484   [ +  -  +  - ]:           8 :     CWalletTx& wtx = context.AddTx(CRecipient{*dest, amount, /*fSubtractFeeFromAmount=*/true});
     485                 :           4 :     CoinFilterParams filter;
     486                 :           4 :     filter.skip_locked = false;
     487         [ +  - ]:           4 :     CoinsResult available_coins = AvailableCoins(*context.wallet, nullptr, std::nullopt, filter);
     488                 :             :     // Lock outputs so they are not spent in follow-up transactions
     489   [ +  -  +  + ]:          12 :     for (uint32_t i = 0; i < wtx.tx->vout.size(); i++) context.wallet->LockCoin({wtx.GetHash(), i});
     490   [ +  -  +  -  :          24 :     for (const auto& [type, size] : expected_coins_sizes) BOOST_CHECK_EQUAL(size, available_coins.coins[type].size());
             +  -  +  + ]
     491         [ +  - ]:           8 : }
     492                 :             : 
     493   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(BasicOutputTypesTest, ListCoinsTest)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     494                 :             : {
     495                 :           1 :     std::map<OutputType, size_t> expected_coins_sizes;
     496   [ +  -  +  + ]:           5 :     for (const auto& out_type : OUTPUT_TYPES) { expected_coins_sizes[out_type] = 0U; }
     497                 :             : 
     498                 :             :     // Verify our wallet has one usable coinbase UTXO before starting
     499                 :             :     // This UTXO is a P2PK, so it should show up in the Other bucket
     500         [ +  - ]:           1 :     expected_coins_sizes[OutputType::UNKNOWN] = 1U;
     501         [ +  - ]:           3 :     CoinsResult available_coins = WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet));
     502   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(available_coins.Size(), expected_coins_sizes[OutputType::UNKNOWN]);
             +  -  +  - ]
     503   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(available_coins.coins[OutputType::UNKNOWN].size(), expected_coins_sizes[OutputType::UNKNOWN]);
             +  -  +  - ]
     504                 :             : 
     505                 :             :     // We will create a self transfer for each of the OutputTypes and
     506                 :             :     // verify it is put in the correct bucket after running GetAvailablecoins
     507                 :             :     //
     508                 :             :     // For each OutputType, We expect 2 UTXOs in our wallet following the self transfer:
     509                 :             :     //   1. One UTXO as the recipient
     510                 :             :     //   2. One UTXO from the change, due to payment address matching logic
     511                 :             : 
     512         [ +  + ]:           5 :     for (const auto& out_type : OUTPUT_TYPES) {
     513         [ -  + ]:           4 :         if (out_type == OutputType::UNKNOWN) continue;
     514         [ +  - ]:           4 :         expected_coins_sizes[out_type] = 2U;
     515         [ +  - ]:           4 :         TestCoinsResult(*this, out_type, 1 * COIN, expected_coins_sizes);
     516                 :             :     }
     517                 :           1 : }
     518                 :             : 
     519   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(wallet_disableprivkeys, TestChain100Setup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     520                 :             : {
     521   [ +  -  +  - ]:           1 :     const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase());
     522         [ +  - ]:           1 :     LOCK(wallet->cs_wallet);
     523         [ +  - ]:           1 :     wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
     524         [ +  - ]:           1 :     wallet->SetMinVersion(FEATURE_LATEST);
     525         [ +  - ]:           1 :     wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
     526   [ +  -  +  -  :           2 :     BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, ""));
          +  -  +  -  +  
                      - ]
     527         [ +  - ]:           2 : }
     528                 :             : 
     529                 :             : // Explicit calculation which is used to test the wallet constant
     530                 :             : // We get the same virtual size due to rounding(weight/4) for both use_max_sig values
     531                 :           2 : static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
     532                 :             : {
     533                 :             :     // Generate ephemeral valid pubkey
     534                 :           2 :     CKey key = GenerateRandomKey();
     535         [ +  - ]:           2 :     CPubKey pubkey = key.GetPubKey();
     536                 :             : 
     537                 :             :     // Generate pubkey hash
     538         [ +  - ]:           2 :     uint160 key_hash(Hash160(pubkey));
     539                 :             : 
     540                 :             :     // Create inner-script to enter into keystore. Key hash can't be 0...
     541   [ +  -  +  - ]:           2 :     CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end());
     542                 :             : 
     543                 :             :     // Create outer P2SH script for the output
     544         [ +  - ]:           2 :     uint160 script_id(Hash160(inner_script));
     545   [ +  -  +  -  :           2 :     CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL;
                   +  - ]
     546                 :             : 
     547                 :             :     // Add inner-script to key store and key to watchonly
     548                 :           2 :     FillableSigningProvider keystore;
     549         [ +  - ]:           2 :     keystore.AddCScript(inner_script);
     550         [ +  - ]:           2 :     keystore.AddKeyPubKey(key, pubkey);
     551                 :             : 
     552                 :             :     // Fill in dummy signatures for fee calculation.
     553                 :           2 :     SignatureData sig_data;
     554                 :             : 
     555   [ +  +  +  -  :           2 :     if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) {
                   -  + ]
     556                 :             :         // We're hand-feeding it correct arguments; shouldn't happen
     557                 :           0 :         assert(false);
     558                 :             :     }
     559                 :             : 
     560                 :           2 :     CTxIn tx_in;
     561         [ +  - ]:           2 :     UpdateInput(tx_in, sig_data);
     562         [ +  - ]:           2 :     return (size_t)GetVirtualTransactionInputSize(tx_in);
     563                 :           2 : }
     564                 :             : 
     565   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(dummy_input_size_test, TestChain100Setup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     566                 :             : {
     567         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(CalculateNestedKeyhashInputSize(false), DUMMY_NESTED_P2WPKH_INPUT_SIZE);
     568         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(CalculateNestedKeyhashInputSize(true), DUMMY_NESTED_P2WPKH_INPUT_SIZE);
     569                 :           1 : }
     570                 :             : 
     571                 :           1 : bool malformed_descriptor(std::ios_base::failure e)
     572                 :             : {
     573                 :           1 :     std::string s(e.what());
     574                 :           1 :     return s.find("Missing checksum") != std::string::npos;
     575                 :           1 : }
     576                 :             : 
     577   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(wallet_descriptor_test, BasicTestingSetup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     578                 :             : {
     579                 :           1 :     std::vector<unsigned char> malformed_record;
     580         [ +  - ]:           1 :     VectorWriter vw{malformed_record, 0};
     581         [ +  - ]:           2 :     vw << std::string("notadescriptor");
     582         [ +  - ]:           1 :     vw << uint64_t{0};
     583         [ +  - ]:           1 :     vw << int32_t{0};
     584         [ +  - ]:           1 :     vw << int32_t{0};
     585         [ +  - ]:           1 :     vw << int32_t{1};
     586                 :             : 
     587                 :           1 :     SpanReader vr{malformed_record};
     588                 :           1 :     WalletDescriptor w_desc;
     589   [ +  -  -  +  :           2 :     BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure, malformed_descriptor);
          -  -  -  -  -  
          +  +  -  +  -  
                   +  - ]
     590                 :           1 : }
     591                 :             : 
     592                 :             : //! Test CWallet::Create() and its behavior handling potential race
     593                 :             : //! conditions if it's called the same time an incoming transaction shows up in
     594                 :             : //! the mempool or a new block.
     595                 :             : //!
     596                 :             : //! It isn't possible to verify there aren't race condition in every case, so
     597                 :             : //! this test just checks two specific cases and ensures that timing of
     598                 :             : //! notifications in these cases doesn't prevent the wallet from detecting
     599                 :             : //! transactions.
     600                 :             : //!
     601                 :             : //! In the first case, block and mempool transactions are created before the
     602                 :             : //! wallet is loaded, but notifications about these transactions are delayed
     603                 :             : //! until after it is loaded. The notifications are superfluous in this case, so
     604                 :             : //! the test verifies the transactions are detected before they arrive.
     605                 :             : //!
     606                 :             : //! In the second case, block and mempool transactions are created after the
     607                 :             : //! wallet rescan and notifications are immediately synced, to verify the wallet
     608                 :             : //! must already have a handler in place for them, and there's no gap after
     609                 :             : //! rescanning where new transactions in new blocks could be lost.
     610   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(CreateWallet, TestChain100Setup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     611                 :             : {
     612   [ +  -  +  - ]:           2 :     m_args.ForceSetArg("-unsafesqlitesync", "1");
     613                 :             :     // Create new wallet with known key and unload it.
     614                 :           1 :     WalletContext context;
     615                 :           1 :     context.args = &m_args;
     616         [ +  - ]:           1 :     context.chain = m_node.chain.get();
     617         [ +  - ]:           1 :     auto wallet = TestLoadWallet(context);
     618                 :           1 :     CKey key = GenerateRandomKey();
     619         [ +  - ]:           1 :     AddKey(*wallet, key);
     620         [ +  - ]:           1 :     TestUnloadWallet(std::move(wallet));
     621                 :             : 
     622                 :             : 
     623                 :             :     // Add log hook to detect AddToWallet events from rescans, blockConnected,
     624                 :             :     // and transactionAddedToMempool notifications
     625                 :           1 :     int addtx_count = 0;
     626         [ +  - ]:          11 :     DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) {
     627         [ +  + ]:          10 :         if (s) ++addtx_count;
     628                 :          10 :         return false;
     629   [ +  -  +  - ]:           2 :     });
     630                 :             : 
     631                 :             : 
     632                 :           1 :     bool rescan_completed = false;
     633         [ +  - ]:           3 :     DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) {
     634         [ +  + ]:           2 :         if (s) rescan_completed = true;
     635                 :           2 :         return false;
     636   [ +  -  +  - ]:           2 :     });
     637                 :             : 
     638                 :             : 
     639                 :             :     // Block the queue to prevent the wallet receiving blockConnected and
     640                 :             :     // transactionAddedToMempool notifications, and create block and mempool
     641                 :             :     // transactions paying to the wallet
     642         [ +  - ]:           1 :     std::promise<void> promise;
     643         [ +  - ]:           2 :     m_node.validation_signals->CallFunctionInValidationInterfaceQueue([&promise] {
     644         [ +  - ]:           1 :         promise.get_future().wait();
     645                 :           1 :     });
     646         [ +  - ]:           1 :     std::string error;
     647   [ +  -  +  -  :           2 :     m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
             +  -  +  - ]
     648   [ +  -  +  -  :           1 :     auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
                   +  - ]
     649   [ +  -  +  -  :           4 :     m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
          +  -  +  -  +  
             -  +  +  -  
                      - ]
     650   [ +  -  +  -  :           1 :     auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
                   +  - ]
     651   [ +  -  +  -  :           4 :     BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
          +  -  +  -  +  
                -  +  - ]
     652                 :             : 
     653                 :             : 
     654                 :             :     // Reload wallet and make sure new transactions are detected despite events
     655                 :             :     // being blocked
     656                 :             :     // Loading will also ask for current mempool transactions
     657   [ +  -  -  + ]:           2 :     wallet = TestLoadWallet(context);
     658   [ +  -  +  -  :           2 :     BOOST_CHECK(rescan_completed);
                   +  - ]
     659                 :             :     // AddToWallet events for block_tx and mempool_tx (x2)
     660   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(addtx_count, 3);
     661                 :           1 :     {
     662         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     663   [ +  -  +  -  :           2 :         BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
                   +  - ]
     664   [ +  -  +  -  :           2 :         BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
             +  -  +  - ]
     665                 :           0 :     }
     666                 :             : 
     667                 :             : 
     668                 :             :     // Unblock notification queue and make sure stale blockConnected and
     669                 :             :     // transactionAddedToMempool events are processed
     670         [ +  - ]:           1 :     promise.set_value();
     671         [ +  - ]:           1 :     m_node.validation_signals->SyncWithValidationInterfaceQueue();
     672                 :             :     // AddToWallet events for block_tx and mempool_tx events are counted a
     673                 :             :     // second time as the notification queue is processed
     674   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(addtx_count, 5);
     675                 :             : 
     676                 :             : 
     677         [ +  - ]:           1 :     TestUnloadWallet(std::move(wallet));
     678                 :             : 
     679                 :             : 
     680                 :             :     // Load wallet again, this time creating new block and mempool transactions
     681                 :             :     // paying to the wallet as the wallet finishes loading and syncing the
     682                 :             :     // queue so the events have to be handled immediately. Releasing the wallet
     683                 :             :     // lock during the sync is a little artificial but is needed to avoid a
     684                 :             :     // deadlock during the sync and simulates a new block notification happening
     685                 :             :     // as soon as possible.
     686                 :           1 :     addtx_count = 0;
     687         [ +  - ]:           2 :     auto handler = HandleLoadWallet(context, [&](std::unique_ptr<interfaces::Wallet> wallet) {
     688         [ +  - ]:           2 :             BOOST_CHECK(rescan_completed);
     689   [ +  -  +  - ]:           2 :             m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
     690         [ +  - ]:           2 :             block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
     691   [ +  -  +  -  :           4 :             m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
          +  -  +  +  -  
                      - ]
     692         [ +  - ]:           2 :             mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
     693   [ +  -  +  -  :           4 :             BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error));
             +  -  +  - ]
     694                 :           1 :             m_node.validation_signals->SyncWithValidationInterfaceQueue();
     695         [ +  - ]:           3 :         });
     696   [ +  -  -  + ]:           2 :     wallet = TestLoadWallet(context);
     697                 :             :     // Since mempool transactions are requested at the end of loading, there will
     698                 :             :     // be 2 additional AddToWallet calls, one from the previous test, and a duplicate for mempool_tx
     699   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(addtx_count, 2 + 2);
     700                 :           1 :     {
     701         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     702   [ +  -  +  -  :           2 :         BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U);
                   +  - ]
     703   [ +  -  +  -  :           2 :         BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U);
             +  -  +  - ]
     704                 :           0 :     }
     705                 :             : 
     706                 :             : 
     707         [ +  - ]:           1 :     TestUnloadWallet(std::move(wallet));
     708   [ +  -  -  + ]:           4 : }
     709                 :             : 
     710   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(CreateWalletWithoutChain, BasicTestingSetup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     711                 :             : {
     712                 :           1 :     WalletContext context;
     713                 :           1 :     context.args = &m_args;
     714         [ +  - ]:           1 :     auto wallet = TestLoadWallet(context);
     715   [ +  -  +  -  :           2 :     BOOST_CHECK(wallet);
                   +  - ]
     716         [ +  - ]:           1 :     WaitForDeleteWallet(std::move(wallet));
     717                 :           1 : }
     718                 :             : 
     719   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(RemoveTxs, TestChain100Setup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     720                 :             : {
     721   [ +  -  +  - ]:           2 :     m_args.ForceSetArg("-unsafesqlitesync", "1");
     722                 :           1 :     WalletContext context;
     723                 :           1 :     context.args = &m_args;
     724         [ +  - ]:           1 :     context.chain = m_node.chain.get();
     725         [ +  - ]:           1 :     auto wallet = TestLoadWallet(context);
     726                 :           1 :     CKey key = GenerateRandomKey();
     727         [ +  - ]:           1 :     AddKey(*wallet, key);
     728                 :             : 
     729         [ +  - ]:           1 :     std::string error;
     730   [ +  -  +  -  :           2 :     m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
             +  -  +  - ]
     731   [ +  -  +  -  :           1 :     auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey()));
                   +  - ]
     732   [ +  -  +  -  :           4 :     CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
          +  -  +  -  +  
                +  -  - ]
     733                 :             : 
     734         [ +  - ]:           1 :     m_node.validation_signals->SyncWithValidationInterfaceQueue();
     735                 :             : 
     736                 :           1 :     {
     737         [ +  - ]:           1 :         auto block_hash = block_tx.GetHash();
     738         [ +  - ]:           1 :         auto prev_tx = m_coinbase_txns[0];
     739                 :             : 
     740         [ +  - ]:           1 :         LOCK(wallet->cs_wallet);
     741   [ +  -  +  -  :           2 :         BOOST_CHECK(wallet->HasWalletSpend(prev_tx));
             +  -  +  - ]
     742   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 1u);
                   +  - ]
     743                 :             : 
     744         [ +  - ]:           1 :         std::vector<Txid> vHashIn{ block_hash };
     745   [ +  -  +  -  :           2 :         BOOST_CHECK(wallet->RemoveTxs(vHashIn));
             +  -  +  - ]
     746                 :             : 
     747   [ +  -  +  -  :           2 :         BOOST_CHECK(!wallet->HasWalletSpend(prev_tx));
             +  -  +  - ]
     748   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 0u);
                   +  - ]
     749   [ +  -  +  - ]:           2 :     }
     750                 :             : 
     751         [ +  - ]:           1 :     TestUnloadWallet(std::move(wallet));
     752   [ +  -  -  + ]:           2 : }
     753                 :             : 
     754                 :             : /**
     755                 :             :  * Checks a wallet invalid state where the inputs (prev-txs) of a new arriving transaction are not marked dirty,
     756                 :             :  * while the transaction that spends them exist inside the in-memory wallet tx map (not stored on db due a db write failure).
     757                 :             :  */
     758   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(wallet_sync_tx_invalid_state_test, TestingSetup)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     759                 :             : {
     760   [ +  -  +  -  :           2 :     CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase());
                   +  - ]
     761                 :           1 :     {
     762         [ +  - ]:           1 :         LOCK(wallet.cs_wallet);
     763         [ +  - ]:           1 :         wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
     764         [ +  - ]:           1 :         wallet.SetupDescriptorScriptPubKeyMans();
     765                 :           0 :     }
     766                 :             : 
     767                 :             :     // Add tx to wallet
     768   [ +  -  +  -  :           2 :     const auto op_dest{*Assert(wallet.GetNewDestination(OutputType::BECH32M, ""))};
             +  -  +  - ]
     769                 :             : 
     770         [ +  - ]:           1 :     CMutableTransaction mtx;
     771   [ +  -  +  - ]:           1 :     mtx.vout.emplace_back(COIN, GetScriptForDestination(op_dest));
     772         [ +  - ]:           1 :     mtx.vin.emplace_back(Txid::FromUint256(m_rng.rand256()), 0);
     773   [ +  -  +  -  :           3 :     const auto& tx_id_to_spend = wallet.AddToWallet(MakeTransactionRef(mtx), TxStateInMempool{})->GetHash();
                   +  - ]
     774                 :             : 
     775                 :           1 :     {
     776                 :             :         // Cache and verify available balance for the wtx
     777         [ +  - ]:           1 :         LOCK(wallet.cs_wallet);
     778         [ +  - ]:           1 :         const CWalletTx* wtx_to_spend = wallet.GetWalletTx(tx_id_to_spend);
     779   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(CachedTxGetAvailableCredit(wallet, *wtx_to_spend), 1 * COIN);
             +  -  +  - ]
     780                 :           0 :     }
     781                 :             : 
     782                 :             :     // Now the good case:
     783                 :             :     // 1) Add a transaction that spends the previously created transaction
     784                 :             :     // 2) Verify that the available balance of this new tx and the old one is updated (prev tx is marked dirty)
     785                 :             : 
     786                 :           1 :     mtx.vin.clear();
     787         [ +  - ]:           1 :     mtx.vin.emplace_back(tx_id_to_spend, 0);
     788   [ +  -  +  - ]:           2 :     wallet.transactionAddedToMempool(MakeTransactionRef(mtx));
     789         [ +  - ]:           1 :     const auto good_tx_id{mtx.GetHash()};
     790                 :             : 
     791                 :           1 :     {
     792                 :             :         // Verify balance update for the new tx and the old one
     793         [ +  - ]:           1 :         LOCK(wallet.cs_wallet);
     794         [ +  - ]:           1 :         const CWalletTx* new_wtx = wallet.GetWalletTx(good_tx_id);
     795   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(CachedTxGetAvailableCredit(wallet, *new_wtx), 1 * COIN);
                   +  - ]
     796                 :             : 
     797                 :             :         // Now the old wtx
     798         [ +  - ]:           1 :         const CWalletTx* wtx_to_spend = wallet.GetWalletTx(tx_id_to_spend);
     799   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(CachedTxGetAvailableCredit(wallet, *wtx_to_spend), 0 * COIN);
             +  -  +  - ]
     800                 :           0 :     }
     801                 :             : 
     802                 :             :     // Now the bad case:
     803                 :             :     // 1) Make db always fail
     804                 :             :     // 2) Try to add a transaction that spends the previously created transaction and
     805                 :             :     //    verify that we are not moving forward if the wallet cannot store it
     806         [ +  - ]:           1 :     GetMockableDatabase(wallet).m_pass = false;
     807                 :           1 :     mtx.vin.clear();
     808         [ +  - ]:           1 :     mtx.vin.emplace_back(good_tx_id, 0);
     809   [ +  -  +  -  :           4 :     BOOST_CHECK_EXCEPTION(wallet.transactionAddedToMempool(MakeTransactionRef(mtx)),
          -  +  -  -  -  
          -  -  +  +  -  
             +  -  +  - ]
     810                 :             :                           std::runtime_error,
     811                 :             :                           HasReason("DB error adding transaction to wallet, write failed"));
     812                 :           1 : }
     813                 :             : 
     814                 :             : BOOST_AUTO_TEST_SUITE_END()
     815                 :             : } // namespace wallet
        

Generated by: LCOV version 2.0-1