LCOV - code coverage report
Current view: top level - src/index - txindex.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 83.6 % 128 107
Test Date: 2026-11-25 06:45:13 Functions: 78.9 % 19 15
Branches: 52.3 % 174 91

             Branch data     Line data    Source code
       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 <index/txindex.h>
       6                 :             : 
       7                 :             : #include <chain.h>
       8                 :             : #include <common/args.h>
       9                 :             : #include <crypto/siphash.h>
      10                 :             : #include <dbwrapper.h>
      11                 :             : #include <flatfile.h>
      12                 :             : #include <index/base.h>
      13                 :             : #include <index/disktxpos.h>
      14                 :             : #include <index/txindex_key.h>
      15                 :             : #include <interfaces/chain.h>
      16                 :             : #include <node/blockstorage.h>
      17                 :             : #include <primitives/block.h>
      18                 :             : #include <primitives/transaction.h>
      19                 :             : #include <random.h>
      20                 :             : #include <serialize.h>
      21                 :             : #include <streams.h>
      22                 :             : #include <sync.h>
      23                 :             : #include <tinyformat.h>
      24                 :             : #include <uint256.h>
      25                 :             : #include <util/fs.h>
      26                 :             : #include <util/log.h>
      27                 :             : #include <util/string.h>
      28                 :             : #include <validation.h>
      29                 :             : 
      30                 :             : #include <algorithm>
      31                 :             : #include <array>
      32                 :             : #include <cassert>
      33                 :             : #include <cstdint>
      34                 :             : #include <cstdio>
      35                 :             : #include <exception>
      36                 :             : #include <functional>
      37                 :             : #include <memory>
      38                 :             : #include <optional>
      39                 :             : #include <stdexcept>
      40                 :             : #include <string>
      41                 :             : #include <utility>
      42                 :             : #include <vector>
      43                 :             : 
      44                 :             : namespace {
      45                 :          47 : SipHasher13UJ ReadOrCreateTxidHasher(CDBWrapper& db)
      46                 :             : {
      47                 :          47 :     std::pair<uint64_t, uint64_t> salt;
      48         [ +  + ]:          47 :     if (!db.Read(txindex::DB_TXID_HASH_SALT, salt)) {
      49                 :          23 :         FastRandomContext rng{};
      50         [ +  - ]:          23 :         salt = {rng.rand64(), rng.rand64()};
      51         [ +  - ]:          23 :         db.Write(txindex::DB_TXID_HASH_SALT, salt, /*fSync=*/true);
      52                 :          23 :     }
      53                 :          47 :     return SipHasher13UJ{salt.first, salt.second};
      54                 :             : }
      55                 :             : } // namespace
      56                 :             : 
      57                 :             : /** Access to the txindex database (indexes/txindex/) */
      58                 :             : class TxIndex::DB : public BaseIndex::DB
      59                 :             : {
      60                 :             : public:
      61                 :             :     explicit DB(size_t n_cache_size, bool f_memory = false, bool f_wipe = false);
      62                 :             : 
      63                 :             :     /// Write a block of transaction positions to the DB.
      64                 :             :     void WriteTxs(const interfaces::BlockInfo& block);
      65                 :             : 
      66                 :             :     /// Used to hash the txid to compute the prefix.
      67                 :             :     const SipHasher13UJ m_hasher;
      68                 :             : 
      69                 :             :     /// Whether the database contains any legacy ('t' + txid) entries.
      70                 :             :     const bool m_has_legacy;
      71                 :             : 
      72                 :             :     CBlockLocator ReadBestBlock() const override;
      73                 :             :     void WriteBestBlock(CDBBatch& batch, const CBlockLocator& locator) override;
      74                 :             : 
      75                 :             : private:
      76                 :             :     DB(size_t n_cache_size, bool f_memory, bool f_wipe, bool has_legacy);
      77                 :             : };
      78                 :             : 
      79   [ +  -  +  - ]:         470 : static fs::path TxIndexDBPath() { return gArgs.GetDataDirNet() / "indexes" / "txindex"; }
      80                 :             : 
      81                 :          50 : TxIndex::DB::DB(size_t n_cache_size, bool f_memory, bool f_wipe) :
      82                 :             :     // Bloom filters are built for every key but only consulted by point reads,
      83                 :             :     // which iterators bypass: the per-tx hashed ('x') lookups seek with an
      84                 :             :     // iterator, and the 's'/'h' point reads are at most one per block against a
      85                 :             :     // tiny keyspace. Only the legacy entries' per-tx point lookups benefit, so
      86                 :             :     // enable the filters only for databases still containing them.
      87                 :             :     DB(n_cache_size, f_memory, f_wipe,
      88   [ +  +  +  +  :         135 :        /*has_legacy=*/!f_memory && !f_wipe && CDBWrapper::HasKeyStartingWith(TxIndexDBPath(), txindex::DB_TXINDEX))
          +  +  +  -  +  
                +  -  - ]
      89                 :          47 : {}
      90                 :             : 
      91                 :          47 : TxIndex::DB::DB(size_t n_cache_size, bool f_memory, bool f_wipe, bool has_legacy) :
      92                 :           0 :     BaseIndex::DB(TxIndexDBPath(), n_cache_size, f_memory, f_wipe, /*f_obfuscate=*/false, /*f_bloom=*/has_legacy),
      93                 :          47 :     m_hasher{ReadOrCreateTxidHasher(*this)},
      94   [ +  -  +  - ]:          94 :     m_has_legacy{has_legacy}
      95                 :          47 : {}
      96                 :             : 
      97                 :          53 : CBlockLocator TxIndex::DB::ReadBestBlock() const
      98                 :             : {
      99                 :          53 :     CBlockLocator locator;
     100   [ +  -  +  + ]:          53 :     if (Read(txindex::DB_BEST_BLOCK_V2, locator)) {
     101                 :          26 :         return locator;
     102                 :             :     }
     103                 :             :     // If we don't have a locator yet, start from the legacy best block.
     104         [ +  - ]:          27 :     return BaseIndex::DB::ReadBestBlock();
     105                 :          53 : }
     106                 :             : 
     107                 :          60 : void TxIndex::DB::WriteBestBlock(CDBBatch& batch, const CBlockLocator& locator)
     108                 :             : {
     109                 :          60 :     batch.Write(txindex::DB_BEST_BLOCK_V2, locator);
     110                 :          60 : }
     111                 :             : 
     112                 :        4958 : void TxIndex::DB::WriteTxs(const interfaces::BlockInfo& block)
     113                 :             : {
     114                 :             :     // A block may be submitted again after it was already indexed, e.g. when it
     115                 :             :     // reconnects after a reorg or is re-processed after an unclean shutdown. It
     116                 :             :     // keeps its original sequence number, so skip it to avoid duplicate entries.
     117         [ +  + ]:        4958 :     if (Exists(txindex::BlockHashKey{block.hash})) return;
     118                 :             : 
     119                 :        4454 :     uint32_t block_seq{0};
     120                 :        4454 :     Read(txindex::DB_NEXT_BLOCK_SEQ, block_seq);
     121                 :             : 
     122                 :        4454 :     CDBBatch batch(*this);
     123         [ +  - ]:        4454 :     batch.Write(txindex::BlockHashKey{block.hash}, block_seq);
     124         [ +  - ]:        4454 :     batch.Write(txindex::BlockSeqKey{block_seq}, block.hash);
     125         [ +  - ]:        4454 :     batch.Write(txindex::DB_NEXT_BLOCK_SEQ, block_seq + 1);
     126   [ -  +  -  + ]:        4454 :     uint32_t tx_offset_in_block{txindex::BLOCK_HEADER_SIZE + GetSizeOfCompactSize(block.data->vtx.size())};
     127         [ +  + ]:        9062 :     for (const auto& tx : block.data->vtx) {
     128         [ +  - ]:        4608 :         const txindex::DBKey key{txindex::CreateKeyPrefix(m_hasher, tx->GetHash()),
     129                 :        4608 :                                  txindex::BlockTxPosition{block_seq, tx_offset_in_block}};
     130         [ +  - ]:        4608 :         batch.Write(key, txindex::EMPTY_VALUE);
     131         [ +  - ]:        4608 :         tx_offset_in_block += tx->ComputeTotalSize();
     132                 :             :     }
     133         [ +  - ]:        4454 :     WriteBatch(batch);
     134                 :        4454 : }
     135                 :             : 
     136                 :          50 : TxIndex::TxIndex(std::unique_ptr<interfaces::Chain> chain, size_t n_cache_size, bool f_memory, bool f_wipe)
     137   [ +  -  +  -  :          50 :     : BaseIndex(std::move(chain), "txindex", "txidx"), m_db(std::make_unique<TxIndex::DB>(n_cache_size, f_memory, f_wipe))
                   +  + ]
     138                 :             : {
     139         [ +  + ]:          47 :     if (m_db->m_has_legacy) {
     140   [ +  -  +  - ]:           6 :         LogInfo("txindex contains entries in the legacy format, which uses excessive disk space. "
     141                 :             :                 "To reclaim disk space, stop the node, delete %s and restart to rebuild the index.",
     142                 :             :                 fs::PathToString(TxIndexDBPath()));
     143                 :             :     }
     144                 :          50 : }
     145                 :             : 
     146                 :          89 : TxIndex::~TxIndex() = default;
     147                 :             : 
     148                 :        4980 : bool TxIndex::CustomAppend(const interfaces::BlockInfo& block)
     149                 :             : {
     150                 :             :     // Exclude genesis block transaction because outputs are not spendable.
     151         [ +  + ]:        4980 :     if (block.height == 0) return true;
     152                 :             : 
     153         [ -  + ]:        4958 :     assert(block.data);
     154                 :        4958 :     m_db->WriteTxs(block);
     155                 :        4958 :     return true;
     156                 :             : }
     157                 :             : 
     158                 :         235 : BaseIndex::DB& TxIndex::GetDB() const { return *m_db; }
     159                 :             : 
     160                 :             : template <typename... Args>
     161                 :           4 : [[noreturn]] static void WarnAndThrowErr(util::ConstevalFormatString<sizeof...(Args)> fmt, const Args&... args)
     162                 :             : {
     163                 :           4 :     const std::string err{tfm::format(fmt, args...)};
     164         [ +  - ]:           4 :     LogWarning("%s", err);
     165         [ +  - ]:           4 :     throw std::runtime_error{err};
     166                 :           4 : }
     167                 :             : 
     168                 :         266 : std::optional<TxIndexResult> TxIndex::FindTx(const Txid& tx_hash) const
     169                 :             : {
     170                 :         266 :     struct Candidate {
     171                 :             :         FlatFilePos tx_position;
     172                 :             :         uint256 block_hash;
     173                 :             :         uint32_t block_seq;
     174                 :             :         //! Whether this candidate's block is currently in the active chain.
     175                 :             :         //! Active chain candidates are attempted first, so duplicate entries
     176                 :             :         //! in both active and stale blocks will always return the active block hash.
     177                 :             :         bool in_active_chain;
     178                 :             :     };
     179                 :         266 :     std::vector<Candidate> candidates;
     180                 :         266 :     {
     181   [ +  -  +  - ]:         266 :         std::unique_ptr<CDBIterator> it{m_db->NewIterator()};
     182         [ +  - ]:         266 :         const txindex::TxHashKeyPrefix prefix{txindex::CreateKeyPrefix(m_db->m_hasher, tx_hash)};
     183                 :         266 :         txindex::DBKey key{prefix, {}};
     184   [ +  -  +  -  :         426 :         for (it->Seek(key); it->Valid() && it->GetKey(key) && key.hash_prefix == prefix; it->Next()) {
          +  -  +  +  +  
             -  +  -  +  
                      + ]
     185                 :         160 :             uint256 candidate_block_hash;
     186   [ -  +  +  - ]:         160 :             if (!m_db->Read(txindex::BlockSeqKey{key.pos.block_seq}, candidate_block_hash)) {
     187                 :             :                 // Read may throw dbwrapper_error.
     188                 :             :                 // Read returns false for internal deserialize errors or a
     189                 :             :                 // missing key. A missing key can only happen after corruption.
     190         [ #  # ]:           0 :                 WarnAndThrowErr("%s: Corrupt index: block sequence %u not found for txid %s",
     191                 :           0 :                                 GetName(), key.pos.block_seq, tx_hash.ToString());
     192                 :             :             }
     193         [ +  - ]:         160 :             LOCK(cs_main);
     194         [ +  - ]:         160 :             const CBlockIndex* block_index{m_chainstate->m_blockman.LookupBlockIndex(candidate_block_hash)};
     195                 :             :             // Stale entries can remain after an unclean shutdown. Unknown blocks
     196                 :             :             // cannot be in the active chain, so skip them.
     197         [ -  + ]:         160 :             if (!block_index) continue;
     198                 :         160 :             const bool in_active_chain{m_chainstate->m_chain.Contains(*block_index)};
     199         [ -  + ]:         160 :             if (!(block_index->nStatus & BLOCK_HAVE_DATA)) {
     200                 :             :                 // A stale entry may also refer to a known block without data.
     201                 :             :                 // Skip it if it is not in the active chain.
     202         [ #  # ]:           0 :                 if (!in_active_chain) continue;
     203         [ #  # ]:           0 :                 WarnAndThrowErr("%s: Block data %s unexpectedly unavailable for txid %s. Caused by data corruption?",
     204         [ #  # ]:           0 :                                 GetName(), candidate_block_hash.ToString(), tx_hash.ToString());
     205                 :             :             }
     206         [ +  - ]:         160 :             const FlatFilePos tx_position{block_index->nFile, block_index->nDataPos + key.pos.tx_offset_in_block};
     207         [ +  - ]:         160 :             candidates.emplace_back(tx_position, candidate_block_hash, key.pos.block_seq, in_active_chain);
     208                 :         160 :         }
     209                 :         266 :     }
     210                 :             : 
     211                 :             :     // Prefer active-chain matches, then later-connected blocks.
     212                 :         266 :     std::ranges::sort(candidates, std::greater{}, [](const Candidate& c) { return std::pair{c.in_active_chain, c.block_seq}; });
     213                 :             : 
     214         [ +  + ]:         267 :     for (const auto& candidate : candidates) {
     215         [ +  - ]:         158 :         AutoFile file{m_chainstate->m_blockman.OpenBlockFile(candidate.tx_position, /*fReadOnly=*/true)};
     216         [ +  + ]:         158 :         if (file.IsNull()) {
     217                 :           4 :             WarnAndThrowErr("%s: Failed to open block file for txid %s at %s in block %s",
     218   [ +  -  +  - ]:          20 :                             GetName(), tx_hash.ToString(), candidate.tx_position.ToString(), candidate.block_hash.ToString());
     219                 :             :         }
     220                 :         154 :         CTransactionRef tx;
     221                 :         154 :         try {
     222         [ +  - ]:         154 :             file >> TX_WITH_WITNESS(tx);
     223         [ -  - ]:           0 :         } catch (const std::exception& e) {
     224                 :           0 :             WarnAndThrowErr("%s: Deserialize or I/O error (%s). txid %s at %s in block %s",
     225   [ -  -  -  - ]:           0 :                             GetName(), e.what(), tx_hash.ToString(), candidate.tx_position.ToString(), candidate.block_hash.ToString());
     226                 :           0 :         }
     227   [ +  +  +  - ]:         154 :         if (tx->GetHash() == tx_hash) {
     228                 :         153 :             return TxIndexResult{candidate.block_hash, std::move(tx)};
     229                 :             :         }
     230                 :         158 :     }
     231                 :             :     // Fall back to legacy if no hashed entry matched. This makes misses pay an
     232                 :             :     // extra lookup, but keeps existing full-txid entries readable after upgrade.
     233   [ +  +  +  - ]:         109 :     return m_db->m_has_legacy ? FindLegacyTx(tx_hash) : std::nullopt;
     234                 :         262 : }
     235                 :             : 
     236                 :           3 : std::optional<TxIndexResult> TxIndex::FindLegacyTx(const Txid& tx_hash) const
     237                 :             : {
     238                 :           3 :     CDiskTxPos postx;
     239                 :           3 :     const auto read{m_db->TryRead(txindex::LegacyTxKey(tx_hash), postx)};
     240         [ -  + ]:           3 :     if (!read) {
     241                 :           0 :         WarnAndThrowErr("%s: Failed to read legacy entry for txid %s: %s",
     242         [ #  # ]:           0 :                         GetName(), tx_hash.ToString(), read.error().err_msg);
     243                 :             :     }
     244   [ +  -  -  + ]:           3 :     if (!read.value()) {
     245                 :           0 :         return std::nullopt;
     246                 :             :     }
     247                 :             : 
     248         [ +  - ]:           3 :     AutoFile file{m_chainstate->m_blockman.OpenBlockFile(postx, /*fReadOnly=*/true)};
     249         [ -  + ]:           3 :     if (file.IsNull()) {
     250                 :           0 :         WarnAndThrowErr("%s: Failed to open block file for txid %s at %s",
     251         [ #  # ]:           0 :                         GetName(), tx_hash.ToString(), postx.ToString());
     252                 :             :     }
     253                 :           3 :     CBlockHeader header;
     254                 :           3 :     CTransactionRef tx;
     255                 :           3 :     try {
     256         [ +  - ]:           3 :         file >> header;
     257         [ +  - ]:           3 :         file.seek(postx.nTxOffset, SEEK_CUR);
     258         [ +  - ]:           3 :         file >> TX_WITH_WITNESS(tx);
     259         [ -  - ]:           0 :     } catch (const std::exception& e) {
     260                 :           0 :         WarnAndThrowErr("%s: Deserialize or I/O error (%s). txid %s at %s",
     261         [ -  - ]:           0 :                         GetName(), e.what(), tx_hash.ToString(), postx.ToString());
     262                 :           0 :     }
     263         [ +  - ]:           3 :     if (tx->GetHash() != tx_hash) {
     264                 :           0 :         WarnAndThrowErr("%s: txid mismatch in legacy index. txid %s at %s",
     265         [ #  # ]:           0 :                         GetName(), tx_hash.ToString(), postx.ToString());
     266                 :             :     }
     267         [ +  - ]:           3 :     return TxIndexResult{header.GetHash(), std::move(tx)};
     268                 :           6 : }
        

Generated by: LCOV version 2.0-1