LCOV - code coverage report
Current view: top level - src/index - base.h (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 71.4 % 7 5
Test Date: 2024-08-28 04:44:32 Functions: 50.0 % 4 2
Branches: 37.5 % 8 3

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2017-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                 :             : #ifndef BITCOIN_INDEX_BASE_H
       6                 :             : #define BITCOIN_INDEX_BASE_H
       7                 :             : 
       8                 :             : #include <dbwrapper.h>
       9                 :             : #include <interfaces/chain.h>
      10                 :             : #include <util/threadinterrupt.h>
      11                 :             : #include <validationinterface.h>
      12                 :             : 
      13                 :             : #include <string>
      14                 :             : 
      15                 :             : class CBlock;
      16                 :             : class CBlockIndex;
      17                 :             : class Chainstate;
      18                 :             : class ChainstateManager;
      19                 :             : namespace interfaces {
      20                 :             : class Chain;
      21                 :             : } // namespace interfaces
      22                 :             : 
      23                 :           4 : struct IndexSummary {
      24                 :             :     std::string name;
      25                 :             :     bool synced{false};
      26                 :             :     int best_block_height{0};
      27                 :             :     uint256 best_block_hash;
      28                 :             : };
      29                 :             : 
      30                 :             : /**
      31                 :             :  * Base class for indices of blockchain data. This implements
      32                 :             :  * CValidationInterface and ensures blocks are indexed sequentially according
      33                 :             :  * to their position in the active chain.
      34                 :             :  *
      35                 :             :  * In the presence of multiple chainstates (i.e. if a UTXO snapshot is loaded),
      36                 :             :  * only the background "IBD" chainstate will be indexed to avoid building the
      37                 :             :  * index out of order. When the background chainstate completes validation, the
      38                 :             :  * index will be reinitialized and indexing will continue.
      39                 :             :  */
      40                 :             : class BaseIndex : public CValidationInterface
      41                 :             : {
      42                 :             : protected:
      43                 :             :     /**
      44                 :             :      * The database stores a block locator of the chain the database is synced to
      45                 :             :      * so that the index can efficiently determine the point it last stopped at.
      46                 :             :      * A locator is used instead of a simple hash of the chain tip because blocks
      47                 :             :      * and block index entries may not be flushed to disk until after this database
      48                 :             :      * is updated.
      49                 :             :     */
      50                 :           8 :     class DB : public CDBWrapper
      51                 :             :     {
      52                 :             :     public:
      53                 :             :         DB(const fs::path& path, size_t n_cache_size,
      54                 :             :            bool f_memory = false, bool f_wipe = false, bool f_obfuscate = false);
      55                 :             : 
      56                 :             :         /// Read block locator of the chain that the index is in sync with.
      57                 :             :         bool ReadBestBlock(CBlockLocator& locator) const;
      58                 :             : 
      59                 :             :         /// Write block locator of the chain that the index is in sync with.
      60                 :             :         void WriteBestBlock(CDBBatch& batch, const CBlockLocator& locator);
      61                 :             :     };
      62                 :             : 
      63                 :             : private:
      64                 :             :     /// Whether the index has been initialized or not.
      65                 :             :     std::atomic<bool> m_init{false};
      66                 :             :     /// Whether the index is in sync with the main chain. The flag is flipped
      67                 :             :     /// from false to true once, after which point this starts processing
      68                 :             :     /// ValidationInterface notifications to stay in sync.
      69                 :             :     ///
      70                 :             :     /// Note that this will latch to true *immediately* upon startup if
      71                 :             :     /// `m_chainstate->m_chain` is empty, which will be the case upon startup
      72                 :             :     /// with an empty datadir if, e.g., `-txindex=1` is specified.
      73                 :             :     std::atomic<bool> m_synced{false};
      74                 :             : 
      75                 :             :     /// The last block in the chain that the index is in sync with.
      76                 :             :     std::atomic<const CBlockIndex*> m_best_block_index{nullptr};
      77                 :             : 
      78                 :             :     std::thread m_thread_sync;
      79                 :             :     CThreadInterrupt m_interrupt;
      80                 :             : 
      81                 :             :     /// Write the current index state (eg. chain block locator and subclass-specific items) to disk.
      82                 :             :     ///
      83                 :             :     /// Recommendations for error handling:
      84                 :             :     /// If called on a successor of the previous committed best block in the index, the index can
      85                 :             :     /// continue processing without risk of corruption, though the index state will need to catch up
      86                 :             :     /// from further behind on reboot. If the new state is not a successor of the previous state (due
      87                 :             :     /// to a chain reorganization), the index must halt until Commit succeeds or else it could end up
      88                 :             :     /// getting corrupted.
      89                 :             :     bool Commit();
      90                 :             : 
      91                 :             :     /// Loop over disconnected blocks and call CustomRewind.
      92                 :             :     bool Rewind(const CBlockIndex* current_tip, const CBlockIndex* new_tip);
      93                 :             : 
      94                 :             :     virtual bool AllowPrune() const = 0;
      95                 :             : 
      96                 :             :     template <typename... Args>
      97                 :             :     void FatalErrorf(const char* fmt, const Args&... args);
      98                 :             : 
      99                 :             : protected:
     100                 :             :     std::unique_ptr<interfaces::Chain> m_chain;
     101                 :             :     Chainstate* m_chainstate{nullptr};
     102                 :             :     const std::string m_name;
     103                 :             : 
     104                 :             :     void BlockConnected(ChainstateRole role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override;
     105                 :             : 
     106                 :             :     void ChainStateFlushed(ChainstateRole role, const CBlockLocator& locator) override;
     107                 :             : 
     108                 :             :     /// Initialize internal state from the database and block index.
     109                 :           1 :     [[nodiscard]] virtual bool CustomInit(const std::optional<interfaces::BlockKey>& block) { return true; }
     110                 :             : 
     111                 :             :     /// Write update index entries for a newly connected block.
     112                 :           0 :     [[nodiscard]] virtual bool CustomAppend(const interfaces::BlockInfo& block) { return true; }
     113                 :             : 
     114                 :             :     /// Virtual method called internally by Commit that can be overridden to atomically
     115                 :             :     /// commit more index state.
     116                 :           2 :     virtual bool CustomCommit(CDBBatch& batch) { return true; }
     117                 :             : 
     118                 :             :     /// Rewind index to an earlier chain tip during a chain reorg. The tip must
     119                 :             :     /// be an ancestor of the current best block.
     120                 :           0 :     [[nodiscard]] virtual bool CustomRewind(const interfaces::BlockKey& current_tip, const interfaces::BlockKey& new_tip) { return true; }
     121                 :             : 
     122                 :             :     virtual DB& GetDB() const = 0;
     123                 :             : 
     124                 :             :     /// Update the internal best block index as well as the prune lock.
     125                 :             :     void SetBestBlockIndex(const CBlockIndex* block);
     126                 :             : 
     127                 :             : public:
     128                 :             :     BaseIndex(std::unique_ptr<interfaces::Chain> chain, std::string name);
     129                 :             :     /// Destructor interrupts sync thread if running and blocks until it exits.
     130                 :             :     virtual ~BaseIndex();
     131                 :             : 
     132                 :             :     /// Get the name of the index for display in logs.
     133   [ +  -  +  -  :          52 :     const std::string& GetName() const LIFETIMEBOUND { return m_name; }
             +  -  -  - ]
     134                 :             : 
     135                 :             :     /// Blocks the current thread until the index is caught up to the current
     136                 :             :     /// state of the block chain. This only blocks if the index has gotten in
     137                 :             :     /// sync once and only needs to process blocks in the ValidationInterface
     138                 :             :     /// queue. If the index is catching up from far behind, this method does
     139                 :             :     /// not block and immediately returns false.
     140                 :             :     bool BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(::cs_main);
     141                 :             : 
     142                 :             :     void Interrupt();
     143                 :             : 
     144                 :             :     /// Initializes the sync state and registers the instance to the
     145                 :             :     /// validation interface so that it stays in sync with blockchain updates.
     146                 :             :     [[nodiscard]] bool Init();
     147                 :             : 
     148                 :             :     /// Starts the initial sync process on a background thread.
     149                 :             :     [[nodiscard]] bool StartBackgroundSync();
     150                 :             : 
     151                 :             :     /// Sync the index with the block index starting from the current best block.
     152                 :             :     /// Intended to be run in its own thread, m_thread_sync, and can be
     153                 :             :     /// interrupted with m_interrupt. Once the index gets in sync, the m_synced
     154                 :             :     /// flag is set and the BlockConnected ValidationInterface callback takes
     155                 :             :     /// over and the sync thread exits.
     156                 :             :     void Sync();
     157                 :             : 
     158                 :             :     /// Stops the instance from staying in sync with blockchain updates.
     159                 :             :     void Stop();
     160                 :             : 
     161                 :             :     /// Get a summary of the index and its state.
     162                 :             :     IndexSummary GetSummary() const;
     163                 :             : };
     164                 :             : 
     165                 :             : #endif // BITCOIN_INDEX_BASE_H
        

Generated by: LCOV version 2.0-1