/ src / test / txindex_tests.cpp
txindex_tests.cpp
 1  // Copyright (c) 2017-present The Bitcoin Core developers
 2  // Distributed under the MIT software license, see the accompanying
 3  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
 4  
 5  #include <addresstype.h>
 6  #include <chainparams.h>
 7  #include <index/txindex.h>
 8  #include <interfaces/chain.h>
 9  #include <test/util/setup_common.h>
10  #include <util/byte_units.h>
11  #include <validation.h>
12  
13  #include <boost/test/unit_test.hpp>
14  
15  BOOST_AUTO_TEST_SUITE(txindex_tests)
16  
17  BOOST_FIXTURE_TEST_CASE(txindex_initial_sync, TestChain100Setup)
18  {
19      TxIndex txindex(interfaces::MakeChain(m_node), 1_MiB, true);
20      BOOST_REQUIRE(txindex.Init());
21  
22      CTransactionRef tx_disk;
23      uint256 block_hash;
24  
25      // Transaction should not be found in the index before it is started.
26      for (const auto& txn : m_coinbase_txns) {
27          BOOST_CHECK(!txindex.FindTx(txn->GetHash(), block_hash, tx_disk));
28      }
29  
30      // BlockUntilSyncedToCurrentChain should return false before txindex is started.
31      BOOST_CHECK(!txindex.BlockUntilSyncedToCurrentChain());
32  
33      txindex.Sync();
34  
35      // Check that txindex excludes genesis block transactions.
36      const CBlock& genesis_block = Params().GenesisBlock();
37      for (const auto& txn : genesis_block.vtx) {
38          BOOST_CHECK(!txindex.FindTx(txn->GetHash(), block_hash, tx_disk));
39      }
40  
41      // Check that txindex has all txs that were in the chain before it started.
42      for (const auto& txn : m_coinbase_txns) {
43          if (!txindex.FindTx(txn->GetHash(), block_hash, tx_disk)) {
44              BOOST_ERROR("FindTx failed");
45          } else if (tx_disk->GetHash() != txn->GetHash()) {
46              BOOST_ERROR("Read incorrect tx");
47          }
48      }
49  
50      // Check that new transactions in new blocks make it into the index.
51      for (int i = 0; i < 10; i++) {
52          CScript coinbase_script_pub_key = GetScriptForDestination(PKHash(coinbaseKey.GetPubKey()));
53          std::vector<CMutableTransaction> no_txns;
54          const CBlock& block = CreateAndProcessBlock(no_txns, coinbase_script_pub_key);
55          const CTransaction& txn = *block.vtx[0];
56  
57          BOOST_CHECK(txindex.BlockUntilSyncedToCurrentChain());
58          if (!txindex.FindTx(txn.GetHash(), block_hash, tx_disk)) {
59              BOOST_ERROR("FindTx failed");
60          } else if (tx_disk->GetHash() != txn.GetHash()) {
61              BOOST_ERROR("Read incorrect tx");
62          }
63      }
64  
65      // shutdown sequence (c.f. Shutdown() in init.cpp)
66      txindex.Stop();
67  }
68  
69  BOOST_AUTO_TEST_SUITE_END()