base.h raw

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