/Users/brunogarcia/projects/bitcoin-core-dev/src/index/base.h
Line | Count | Source |
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 <threadsafety.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); |
69 | | |
70 | | /// Read block locator of the chain that the index is in sync with. |
71 | | bool ReadBestBlock(CBlockLocator& locator) const; |
72 | | |
73 | | /// Write block locator of the chain that the index is in sync with. |
74 | | void WriteBestBlock(CDBBatch& batch, const CBlockLocator& locator); |
75 | | }; |
76 | | |
77 | | private: |
78 | | /// Whether the index has been initialized or not. |
79 | | std::atomic<bool> m_init{false}; |
80 | | /// Whether the index is in sync with the main chain. The flag is flipped |
81 | | /// from false to true once, after which point this starts processing |
82 | | /// ValidationInterface notifications to stay in sync. |
83 | | /// |
84 | | /// Note that this will latch to true *immediately* upon startup if |
85 | | /// `m_chainstate->m_chain` is empty, which will be the case upon startup |
86 | | /// with an empty datadir if, e.g., `-txindex=1` is specified. |
87 | | std::atomic<bool> m_synced{false}; |
88 | | |
89 | | /// The last block in the chain that the index is in sync with. |
90 | | std::atomic<const CBlockIndex*> m_best_block_index{nullptr}; |
91 | | |
92 | | std::thread m_thread_sync; |
93 | | CThreadInterrupt m_interrupt; |
94 | | |
95 | | /// Write the current index state (eg. chain block locator and subclass-specific items) to disk. |
96 | | /// |
97 | | /// Recommendations for error handling: |
98 | | /// If called on a successor of the previous committed best block in the index, the index can |
99 | | /// continue processing without risk of corruption, though the index state will need to catch up |
100 | | /// from further behind on reboot. If the new state is not a successor of the previous state (due |
101 | | /// to a chain reorganization), the index must halt until Commit succeeds or else it could end up |
102 | | /// getting corrupted. |
103 | | bool Commit(); |
104 | | |
105 | | /// Loop over disconnected blocks and call CustomRemove. |
106 | | bool Rewind(const CBlockIndex* current_tip, const CBlockIndex* new_tip); |
107 | | |
108 | | bool ProcessBlock(const CBlockIndex* pindex, const CBlock* block_data = nullptr); |
109 | | |
110 | | virtual bool AllowPrune() const = 0; |
111 | | |
112 | | template <typename... Args> |
113 | | void FatalErrorf(util::ConstevalFormatString<sizeof...(Args)> fmt, const Args&... args); |
114 | | |
115 | | protected: |
116 | | std::unique_ptr<interfaces::Chain> m_chain; |
117 | | Chainstate* m_chainstate{nullptr}; |
118 | | const std::string m_name; |
119 | | |
120 | | void BlockConnected(ChainstateRole role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override; |
121 | | |
122 | | void ChainStateFlushed(ChainstateRole role, const CBlockLocator& locator) override; |
123 | | |
124 | | /// Return custom notification options for index. |
125 | 0 | [[nodiscard]] virtual interfaces::Chain::NotifyOptions CustomOptions() { return {}; } |
126 | | |
127 | | /// Initialize internal state from the database and block index. |
128 | 0 | [[nodiscard]] virtual bool CustomInit(const std::optional<interfaces::BlockRef>& block) { return true; } |
129 | | |
130 | | /// Write update index entries for a newly connected block. |
131 | 0 | [[nodiscard]] virtual bool CustomAppend(const interfaces::BlockInfo& block) { return true; } |
132 | | |
133 | | /// Virtual method called internally by Commit that can be overridden to atomically |
134 | | /// commit more index state. |
135 | 0 | virtual bool CustomCommit(CDBBatch& batch) { return true; } |
136 | | |
137 | | /// Rewind index by one block during a chain reorg. |
138 | 0 | [[nodiscard]] virtual bool CustomRemove(const interfaces::BlockInfo& block) { return true; } |
139 | | |
140 | | virtual DB& GetDB() const = 0; |
141 | | |
142 | | /// Update the internal best block index as well as the prune lock. |
143 | | void SetBestBlockIndex(const CBlockIndex* block); |
144 | | |
145 | | public: |
146 | | BaseIndex(std::unique_ptr<interfaces::Chain> chain, std::string name); |
147 | | /// Destructor interrupts sync thread if running and blocks until it exits. |
148 | | virtual ~BaseIndex(); |
149 | | |
150 | | /// Get the name of the index for display in logs. |
151 | 0 | const std::string& GetName() const LIFETIMEBOUND { return m_name; } |
152 | | |
153 | | /// Blocks the current thread until the index is caught up to the current |
154 | | /// state of the block chain. This only blocks if the index has gotten in |
155 | | /// sync once and only needs to process blocks in the ValidationInterface |
156 | | /// queue. If the index is catching up from far behind, this method does |
157 | | /// not block and immediately returns false. |
158 | | bool BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(::cs_main); |
159 | | |
160 | | void Interrupt(); |
161 | | |
162 | | /// Initializes the sync state and registers the instance to the |
163 | | /// validation interface so that it stays in sync with blockchain updates. |
164 | | [[nodiscard]] bool Init(); |
165 | | |
166 | | /// Starts the initial sync process on a background thread. |
167 | | [[nodiscard]] bool StartBackgroundSync(); |
168 | | |
169 | | /// Sync the index with the block index starting from the current best block. |
170 | | /// Intended to be run in its own thread, m_thread_sync, and can be |
171 | | /// interrupted with m_interrupt. Once the index gets in sync, the m_synced |
172 | | /// flag is set and the BlockConnected ValidationInterface callback takes |
173 | | /// over and the sync thread exits. |
174 | | void Sync(); |
175 | | |
176 | | /// Stops the instance from staying in sync with blockchain updates. |
177 | | void Stop(); |
178 | | |
179 | | /// Get a summary of the index and its state. |
180 | | IndexSummary GetSummary() const; |
181 | | }; |
182 | | |
183 | | #endif // BITCOIN_INDEX_BASE_H |