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