LCOV - code coverage report
Current view: top level - src/wallet/test - wallet_tests.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 0 608 0.0 %
Date: 2023-10-05 12:38:51 Functions: 0 126 0.0 %
Branches: 0 0 -

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

Generated by: LCOV version 1.14