/Users/brunogarcia/projects/bitcoin-core-dev/src/index/base.cpp
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 | | #include <index/base.h> |
6 | | |
7 | | #include <chain.h> |
8 | | #include <common/args.h> |
9 | | #include <dbwrapper.h> |
10 | | #include <interfaces/chain.h> |
11 | | #include <interfaces/types.h> |
12 | | #include <kernel/chain.h> |
13 | | #include <logging.h> |
14 | | #include <node/abort.h> |
15 | | #include <node/blockstorage.h> |
16 | | #include <node/context.h> |
17 | | #include <node/database_args.h> |
18 | | #include <node/interface_ui.h> |
19 | | #include <primitives/block.h> |
20 | | #include <sync.h> |
21 | | #include <tinyformat.h> |
22 | | #include <uint256.h> |
23 | | #include <undo.h> |
24 | | #include <util/fs.h> |
25 | | #include <util/string.h> |
26 | | #include <util/thread.h> |
27 | | #include <util/threadinterrupt.h> |
28 | | #include <util/time.h> |
29 | | #include <util/translation.h> |
30 | | #include <validation.h> |
31 | | #include <validationinterface.h> |
32 | | |
33 | | #include <cassert> |
34 | | #include <compare> |
35 | | #include <cstdint> |
36 | | #include <memory> |
37 | | #include <optional> |
38 | | #include <span> |
39 | | #include <stdexcept> |
40 | | #include <string> |
41 | | #include <thread> |
42 | | #include <utility> |
43 | | #include <vector> |
44 | | |
45 | | constexpr uint8_t DB_BEST_BLOCK{'B'}; |
46 | | |
47 | | constexpr auto SYNC_LOG_INTERVAL{30s}; |
48 | | constexpr auto SYNC_LOCATOR_WRITE_INTERVAL{30s}; |
49 | | |
50 | | template <typename... Args> |
51 | | void BaseIndex::FatalErrorf(util::ConstevalFormatString<sizeof...(Args)> fmt, const Args&... args) |
52 | 0 | { |
53 | 0 | auto message = tfm::format(fmt, args...); |
54 | 0 | node::AbortNode(m_chain->context()->shutdown_request, m_chain->context()->exit_status, Untranslated(message), m_chain->context()->warnings.get()); |
55 | 0 | } Unexecuted instantiation: void BaseIndex::FatalErrorf<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>(util::ConstevalFormatString<sizeof...(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>)>, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>> const&) Unexecuted instantiation: void BaseIndex::FatalErrorf<int>(util::ConstevalFormatString<sizeof...(int)>, int const&) |
56 | | |
57 | | CBlockLocator GetLocator(interfaces::Chain& chain, const uint256& block_hash) |
58 | 0 | { |
59 | 0 | CBlockLocator locator; |
60 | 0 | bool found = chain.findBlock(block_hash, interfaces::FoundBlock().locator(locator)); |
61 | 0 | assert(found); |
62 | 0 | assert(!locator.IsNull()); |
63 | 0 | return locator; |
64 | 0 | } |
65 | | |
66 | | BaseIndex::DB::DB(const fs::path& path, size_t n_cache_size, bool f_memory, bool f_wipe, bool f_obfuscate) : |
67 | 0 | CDBWrapper{DBParams{ |
68 | 0 | .path = path, |
69 | 0 | .cache_bytes = n_cache_size, |
70 | 0 | .memory_only = f_memory, |
71 | 0 | .wipe_data = f_wipe, |
72 | 0 | .obfuscate = f_obfuscate, |
73 | 0 | .options = [] { DBOptions options; node::ReadDatabaseArgs(gArgs, options); return options; }()}} |
74 | 0 | {} |
75 | | |
76 | | bool BaseIndex::DB::ReadBestBlock(CBlockLocator& locator) const |
77 | 0 | { |
78 | 0 | bool success = Read(DB_BEST_BLOCK, locator); |
79 | 0 | if (!success) { |
80 | 0 | locator.SetNull(); |
81 | 0 | } |
82 | 0 | return success; |
83 | 0 | } |
84 | | |
85 | | void BaseIndex::DB::WriteBestBlock(CDBBatch& batch, const CBlockLocator& locator) |
86 | 0 | { |
87 | 0 | batch.Write(DB_BEST_BLOCK, locator); |
88 | 0 | } |
89 | | |
90 | | BaseIndex::BaseIndex(std::unique_ptr<interfaces::Chain> chain, std::string name) |
91 | 0 | : m_chain{std::move(chain)}, m_name{std::move(name)} {} |
92 | | |
93 | | BaseIndex::~BaseIndex() |
94 | 0 | { |
95 | 0 | Interrupt(); |
96 | 0 | Stop(); |
97 | 0 | } |
98 | | |
99 | | bool BaseIndex::Init() |
100 | 0 | { |
101 | 0 | AssertLockNotHeld(cs_main); Line | Count | Source | 142 | 0 | #define AssertLockNotHeld(cs) AssertLockNotHeldInline(#cs, __FILE__, __LINE__, &cs) |
|
102 | | |
103 | | // May need reset if index is being restarted. |
104 | 0 | m_interrupt.reset(); |
105 | | |
106 | | // m_chainstate member gives indexing code access to node internals. It is |
107 | | // removed in followup https://github.com/bitcoin/bitcoin/pull/24230 |
108 | 0 | m_chainstate = WITH_LOCK(::cs_main, Line | Count | Source | 290 | 0 | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
109 | 0 | return &m_chain->context()->chainman->GetChainstateForIndexing()); |
110 | | // Register to validation interface before setting the 'm_synced' flag, so that |
111 | | // callbacks are not missed once m_synced is true. |
112 | 0 | m_chain->context()->validation_signals->RegisterValidationInterface(this); |
113 | |
|
114 | 0 | CBlockLocator locator; |
115 | 0 | if (!GetDB().ReadBestBlock(locator)) { |
116 | 0 | locator.SetNull(); |
117 | 0 | } |
118 | |
|
119 | 0 | LOCK(cs_main); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
120 | 0 | CChain& index_chain = m_chainstate->m_chain; |
121 | |
|
122 | 0 | if (locator.IsNull()) { |
123 | 0 | SetBestBlockIndex(nullptr); |
124 | 0 | } else { |
125 | | // Setting the best block to the locator's top block. If it is not part of the |
126 | | // best chain, we will rewind to the fork point during index sync |
127 | 0 | const CBlockIndex* locator_index{m_chainstate->m_blockman.LookupBlockIndex(locator.vHave.at(0))}; |
128 | 0 | if (!locator_index) { |
129 | 0 | return InitError(Untranslated(strprintf("best block of %s not found. Please rebuild the index.", GetName())));Line | Count | Source | 1172 | 0 | #define strprintf tfm::format |
|
130 | 0 | } |
131 | 0 | SetBestBlockIndex(locator_index); |
132 | 0 | } |
133 | | |
134 | | // Child init |
135 | 0 | const CBlockIndex* start_block = m_best_block_index.load(); |
136 | 0 | if (!CustomInit(start_block ? std::make_optional(interfaces::BlockRef{start_block->GetBlockHash(), start_block->nHeight}) : std::nullopt)) { |
137 | 0 | return false; |
138 | 0 | } |
139 | | |
140 | | // Note: this will latch to true immediately if the user starts up with an empty |
141 | | // datadir and an index enabled. If this is the case, indexation will happen solely |
142 | | // via `BlockConnected` signals until, possibly, the next restart. |
143 | 0 | m_synced = start_block == index_chain.Tip(); |
144 | 0 | m_init = true; |
145 | 0 | return true; |
146 | 0 | } |
147 | | |
148 | | static const CBlockIndex* NextSyncBlock(const CBlockIndex* pindex_prev, CChain& chain) EXCLUSIVE_LOCKS_REQUIRED(cs_main) |
149 | 0 | { |
150 | 0 | AssertLockHeld(cs_main); Line | Count | Source | 137 | 0 | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) |
|
151 | |
|
152 | 0 | if (!pindex_prev) { |
153 | 0 | return chain.Genesis(); |
154 | 0 | } |
155 | | |
156 | 0 | const CBlockIndex* pindex = chain.Next(pindex_prev); |
157 | 0 | if (pindex) { |
158 | 0 | return pindex; |
159 | 0 | } |
160 | | |
161 | | // Since block is not in the chain, return the next block in the chain AFTER the last common ancestor. |
162 | | // Caller will be responsible for rewinding back to the common ancestor. |
163 | 0 | return chain.Next(chain.FindFork(pindex_prev)); |
164 | 0 | } |
165 | | |
166 | | bool BaseIndex::ProcessBlock(const CBlockIndex* pindex, const CBlock* block_data) |
167 | 0 | { |
168 | 0 | interfaces::BlockInfo block_info = kernel::MakeBlockInfo(pindex, block_data); |
169 | |
|
170 | 0 | CBlock block; |
171 | 0 | if (!block_data) { // disk lookup if block data wasn't provided |
172 | 0 | if (!m_chainstate->m_blockman.ReadBlock(block, *pindex)) { |
173 | 0 | FatalErrorf("Failed to read block %s from disk", |
174 | 0 | pindex->GetBlockHash().ToString()); |
175 | 0 | return false; |
176 | 0 | } |
177 | 0 | block_info.data = █ |
178 | 0 | } |
179 | | |
180 | 0 | CBlockUndo block_undo; |
181 | 0 | if (CustomOptions().connect_undo_data) { |
182 | 0 | if (pindex->nHeight > 0 && !m_chainstate->m_blockman.ReadBlockUndo(block_undo, *pindex)) { |
183 | 0 | FatalErrorf("Failed to read undo block data %s from disk", |
184 | 0 | pindex->GetBlockHash().ToString()); |
185 | 0 | return false; |
186 | 0 | } |
187 | 0 | block_info.undo_data = &block_undo; |
188 | 0 | } |
189 | | |
190 | 0 | if (!CustomAppend(block_info)) { |
191 | 0 | FatalErrorf("Failed to write block %s to index database", |
192 | 0 | pindex->GetBlockHash().ToString()); |
193 | 0 | return false; |
194 | 0 | } |
195 | | |
196 | 0 | return true; |
197 | 0 | } |
198 | | |
199 | | void BaseIndex::Sync() |
200 | 0 | { |
201 | 0 | const CBlockIndex* pindex = m_best_block_index.load(); |
202 | 0 | if (!m_synced) { |
203 | 0 | auto last_log_time{NodeClock::now()}; |
204 | 0 | auto last_locator_write_time{last_log_time}; |
205 | 0 | while (true) { |
206 | 0 | if (m_interrupt) { |
207 | 0 | LogInfo("%s: m_interrupt set; exiting ThreadSync", GetName());Line | Count | Source | 368 | 0 | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 362 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
208 | |
|
209 | 0 | SetBestBlockIndex(pindex); |
210 | | // No need to handle errors in Commit. If it fails, the error will be already be |
211 | | // logged. The best way to recover is to continue, as index cannot be corrupted by |
212 | | // a missed commit to disk for an advanced index state. |
213 | 0 | Commit(); |
214 | 0 | return; |
215 | 0 | } |
216 | | |
217 | 0 | const CBlockIndex* pindex_next = WITH_LOCK(cs_main, return NextSyncBlock(pindex, m_chainstate->m_chain)); Line | Count | Source | 290 | 0 | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
218 | | // If pindex_next is null, it means pindex is the chain tip, so |
219 | | // commit data indexed so far. |
220 | 0 | if (!pindex_next) { |
221 | 0 | SetBestBlockIndex(pindex); |
222 | | // No need to handle errors in Commit. See rationale above. |
223 | 0 | Commit(); |
224 | | |
225 | | // If pindex is still the chain tip after committing, exit the |
226 | | // sync loop. It is important for cs_main to be locked while |
227 | | // setting m_synced = true, otherwise a new block could be |
228 | | // attached while m_synced is still false, and it would not be |
229 | | // indexed. |
230 | 0 | LOCK(::cs_main); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
231 | 0 | pindex_next = NextSyncBlock(pindex, m_chainstate->m_chain); |
232 | 0 | if (!pindex_next) { |
233 | 0 | m_synced = true; |
234 | 0 | break; |
235 | 0 | } |
236 | 0 | } |
237 | 0 | if (pindex_next->pprev != pindex && !Rewind(pindex, pindex_next->pprev)) { |
238 | 0 | FatalErrorf("Failed to rewind %s to a previous chain tip", GetName()); |
239 | 0 | return; |
240 | 0 | } |
241 | 0 | pindex = pindex_next; |
242 | | |
243 | |
|
244 | 0 | if (!ProcessBlock(pindex)) return; // error logged internally |
245 | | |
246 | 0 | auto current_time{NodeClock::now()}; |
247 | 0 | if (current_time - last_log_time >= SYNC_LOG_INTERVAL) { |
248 | 0 | LogInfo("Syncing %s with block chain from height %d", GetName(), pindex->nHeight);Line | Count | Source | 368 | 0 | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 362 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
249 | 0 | last_log_time = current_time; |
250 | 0 | } |
251 | |
|
252 | 0 | if (current_time - last_locator_write_time >= SYNC_LOCATOR_WRITE_INTERVAL) { |
253 | 0 | SetBestBlockIndex(pindex); |
254 | 0 | last_locator_write_time = current_time; |
255 | | // No need to handle errors in Commit. See rationale above. |
256 | 0 | Commit(); |
257 | 0 | } |
258 | 0 | } |
259 | 0 | } |
260 | | |
261 | 0 | if (pindex) { |
262 | 0 | LogInfo("%s is enabled at height %d", GetName(), pindex->nHeight);Line | Count | Source | 368 | 0 | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 362 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
263 | 0 | } else { |
264 | 0 | LogInfo("%s is enabled", GetName());Line | Count | Source | 368 | 0 | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 362 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
265 | 0 | } |
266 | 0 | } |
267 | | |
268 | | bool BaseIndex::Commit() |
269 | 0 | { |
270 | | // Don't commit anything if we haven't indexed any block yet |
271 | | // (this could happen if init is interrupted). |
272 | 0 | bool ok = m_best_block_index != nullptr; |
273 | 0 | if (ok) { |
274 | 0 | CDBBatch batch(GetDB()); |
275 | 0 | ok = CustomCommit(batch); |
276 | 0 | if (ok) { |
277 | 0 | GetDB().WriteBestBlock(batch, GetLocator(*m_chain, m_best_block_index.load()->GetBlockHash())); |
278 | 0 | GetDB().WriteBatch(batch); |
279 | 0 | } |
280 | 0 | } |
281 | 0 | if (!ok) { |
282 | 0 | LogError("Failed to commit latest %s state", GetName());Line | Count | Source | 370 | 0 | #define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 362 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
283 | 0 | return false; |
284 | 0 | } |
285 | 0 | return true; |
286 | 0 | } |
287 | | |
288 | | bool BaseIndex::Rewind(const CBlockIndex* current_tip, const CBlockIndex* new_tip) |
289 | 0 | { |
290 | 0 | assert(current_tip->GetAncestor(new_tip->nHeight) == new_tip); |
291 | | |
292 | 0 | CBlock block; |
293 | 0 | CBlockUndo block_undo; |
294 | |
|
295 | 0 | for (const CBlockIndex* iter_tip = current_tip; iter_tip != new_tip; iter_tip = iter_tip->pprev) { |
296 | 0 | interfaces::BlockInfo block_info = kernel::MakeBlockInfo(iter_tip); |
297 | 0 | if (CustomOptions().disconnect_data) { |
298 | 0 | if (!m_chainstate->m_blockman.ReadBlock(block, *iter_tip)) { |
299 | 0 | LogError("Failed to read block %s from disk",Line | Count | Source | 370 | 0 | #define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 362 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
300 | 0 | iter_tip->GetBlockHash().ToString()); |
301 | 0 | return false; |
302 | 0 | } |
303 | 0 | block_info.data = █ |
304 | 0 | } |
305 | 0 | if (CustomOptions().disconnect_undo_data && iter_tip->nHeight > 0) { |
306 | 0 | if (!m_chainstate->m_blockman.ReadBlockUndo(block_undo, *iter_tip)) { |
307 | 0 | return false; |
308 | 0 | } |
309 | 0 | block_info.undo_data = &block_undo; |
310 | 0 | } |
311 | 0 | if (!CustomRemove(block_info)) { |
312 | 0 | return false; |
313 | 0 | } |
314 | 0 | } |
315 | | |
316 | | // Don't commit here - the committed index state must never be ahead of the |
317 | | // flushed chainstate, otherwise unclean restarts would lead to index corruption. |
318 | | // Pruning has a minimum of 288 blocks-to-keep and getting the index |
319 | | // out of sync may be possible but a users fault. |
320 | | // In case we reorg beyond the pruned depth, ReadBlock would |
321 | | // throw and lead to a graceful shutdown |
322 | 0 | SetBestBlockIndex(new_tip); |
323 | 0 | return true; |
324 | 0 | } |
325 | | |
326 | | void BaseIndex::BlockConnected(ChainstateRole role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) |
327 | 0 | { |
328 | | // Ignore events from the assumed-valid chain; we will process its blocks |
329 | | // (sequentially) after it is fully verified by the background chainstate. This |
330 | | // is to avoid any out-of-order indexing. |
331 | | // |
332 | | // TODO at some point we could parameterize whether a particular index can be |
333 | | // built out of order, but for now just do the conservative simple thing. |
334 | 0 | if (role == ChainstateRole::ASSUMEDVALID) { |
335 | 0 | return; |
336 | 0 | } |
337 | | |
338 | | // Ignore BlockConnected signals until we have fully indexed the chain. |
339 | 0 | if (!m_synced) { |
340 | 0 | return; |
341 | 0 | } |
342 | | |
343 | 0 | const CBlockIndex* best_block_index = m_best_block_index.load(); |
344 | 0 | if (!best_block_index) { |
345 | 0 | if (pindex->nHeight != 0) { |
346 | 0 | FatalErrorf("First block connected is not the genesis block (height=%d)", |
347 | 0 | pindex->nHeight); |
348 | 0 | return; |
349 | 0 | } |
350 | 0 | } else { |
351 | | // Ensure block connects to an ancestor of the current best block. This should be the case |
352 | | // most of the time, but may not be immediately after the sync thread catches up and sets |
353 | | // m_synced. Consider the case where there is a reorg and the blocks on the stale branch are |
354 | | // in the ValidationInterface queue backlog even after the sync thread has caught up to the |
355 | | // new chain tip. In this unlikely event, log a warning and let the queue clear. |
356 | 0 | if (best_block_index->GetAncestor(pindex->nHeight - 1) != pindex->pprev) { |
357 | 0 | LogWarning("Block %s does not connect to an ancestor of "Line | Count | Source | 369 | 0 | #define LogWarning(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 362 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
358 | 0 | "known best chain (tip=%s); not updating index", |
359 | 0 | pindex->GetBlockHash().ToString(), |
360 | 0 | best_block_index->GetBlockHash().ToString()); |
361 | 0 | return; |
362 | 0 | } |
363 | 0 | if (best_block_index != pindex->pprev && !Rewind(best_block_index, pindex->pprev)) { |
364 | 0 | FatalErrorf("Failed to rewind %s to a previous chain tip", |
365 | 0 | GetName()); |
366 | 0 | return; |
367 | 0 | } |
368 | 0 | } |
369 | | |
370 | | // Dispatch block to child class; errors are logged internally and abort the node. |
371 | 0 | if (ProcessBlock(pindex, block.get())) { |
372 | | // Setting the best block index is intentionally the last step of this |
373 | | // function, so BlockUntilSyncedToCurrentChain callers waiting for the |
374 | | // best block index to be updated can rely on the block being fully |
375 | | // processed, and the index object being safe to delete. |
376 | 0 | SetBestBlockIndex(pindex); |
377 | 0 | } |
378 | 0 | } |
379 | | |
380 | | void BaseIndex::ChainStateFlushed(ChainstateRole role, const CBlockLocator& locator) |
381 | 0 | { |
382 | | // Ignore events from the assumed-valid chain; we will process its blocks |
383 | | // (sequentially) after it is fully verified by the background chainstate. |
384 | 0 | if (role == ChainstateRole::ASSUMEDVALID) { |
385 | 0 | return; |
386 | 0 | } |
387 | | |
388 | 0 | if (!m_synced) { |
389 | 0 | return; |
390 | 0 | } |
391 | | |
392 | 0 | const uint256& locator_tip_hash = locator.vHave.front(); |
393 | 0 | const CBlockIndex* locator_tip_index; |
394 | 0 | { |
395 | 0 | LOCK(cs_main); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
396 | 0 | locator_tip_index = m_chainstate->m_blockman.LookupBlockIndex(locator_tip_hash); |
397 | 0 | } |
398 | |
|
399 | 0 | if (!locator_tip_index) { |
400 | 0 | FatalErrorf("First block (hash=%s) in locator was not found", |
401 | 0 | locator_tip_hash.ToString()); |
402 | 0 | return; |
403 | 0 | } |
404 | | |
405 | | // This checks that ChainStateFlushed callbacks are received after BlockConnected. The check may fail |
406 | | // immediately after the sync thread catches up and sets m_synced. Consider the case where |
407 | | // there is a reorg and the blocks on the stale branch are in the ValidationInterface queue |
408 | | // backlog even after the sync thread has caught up to the new chain tip. In this unlikely |
409 | | // event, log a warning and let the queue clear. |
410 | 0 | const CBlockIndex* best_block_index = m_best_block_index.load(); |
411 | 0 | if (best_block_index->GetAncestor(locator_tip_index->nHeight) != locator_tip_index) { |
412 | 0 | LogWarning("Locator contains block (hash=%s) not on known best "Line | Count | Source | 369 | 0 | #define LogWarning(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 362 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
413 | 0 | "chain (tip=%s); not writing index locator", |
414 | 0 | locator_tip_hash.ToString(), |
415 | 0 | best_block_index->GetBlockHash().ToString()); |
416 | 0 | return; |
417 | 0 | } |
418 | | |
419 | | // No need to handle errors in Commit. If it fails, the error will be already be logged. The |
420 | | // best way to recover is to continue, as index cannot be corrupted by a missed commit to disk |
421 | | // for an advanced index state. |
422 | 0 | Commit(); |
423 | 0 | } |
424 | | |
425 | | bool BaseIndex::BlockUntilSyncedToCurrentChain() const |
426 | 0 | { |
427 | 0 | AssertLockNotHeld(cs_main); Line | Count | Source | 142 | 0 | #define AssertLockNotHeld(cs) AssertLockNotHeldInline(#cs, __FILE__, __LINE__, &cs) |
|
428 | |
|
429 | 0 | if (!m_synced) { |
430 | 0 | return false; |
431 | 0 | } |
432 | | |
433 | 0 | { |
434 | | // Skip the queue-draining stuff if we know we're caught up with |
435 | | // m_chain.Tip(). |
436 | 0 | LOCK(cs_main); Line | Count | Source | 259 | 0 | #define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__) Line | Count | Source | 11 | 0 | #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) Line | Count | Source | 9 | 0 | #define PASTE2(x, y) PASTE(x, y) Line | Count | Source | 8 | 0 | #define PASTE(x, y) x ## y |
|
|
|
|
437 | 0 | const CBlockIndex* chain_tip = m_chainstate->m_chain.Tip(); |
438 | 0 | const CBlockIndex* best_block_index = m_best_block_index.load(); |
439 | 0 | if (best_block_index->GetAncestor(chain_tip->nHeight) == chain_tip) { |
440 | 0 | return true; |
441 | 0 | } |
442 | 0 | } |
443 | | |
444 | 0 | LogInfo("%s is catching up on block notifications", GetName());Line | Count | Source | 368 | 0 | #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__) Line | Count | Source | 362 | 0 | #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__) |
|
|
445 | 0 | m_chain->context()->validation_signals->SyncWithValidationInterfaceQueue(); |
446 | 0 | return true; |
447 | 0 | } |
448 | | |
449 | | void BaseIndex::Interrupt() |
450 | 0 | { |
451 | 0 | m_interrupt(); |
452 | 0 | } |
453 | | |
454 | | bool BaseIndex::StartBackgroundSync() |
455 | 0 | { |
456 | 0 | if (!m_init) throw std::logic_error("Error: Cannot start a non-initialized index"); |
457 | | |
458 | 0 | m_thread_sync = std::thread(&util::TraceThread, GetName(), [this] { Sync(); }); |
459 | 0 | return true; |
460 | 0 | } |
461 | | |
462 | | void BaseIndex::Stop() |
463 | 0 | { |
464 | 0 | if (m_chain->context()->validation_signals) { |
465 | 0 | m_chain->context()->validation_signals->UnregisterValidationInterface(this); |
466 | 0 | } |
467 | |
|
468 | 0 | if (m_thread_sync.joinable()) { |
469 | 0 | m_thread_sync.join(); |
470 | 0 | } |
471 | 0 | } |
472 | | |
473 | | IndexSummary BaseIndex::GetSummary() const |
474 | 0 | { |
475 | 0 | IndexSummary summary{}; |
476 | 0 | summary.name = GetName(); |
477 | 0 | summary.synced = m_synced; |
478 | 0 | if (const auto& pindex = m_best_block_index.load()) { |
479 | 0 | summary.best_block_height = pindex->nHeight; |
480 | 0 | summary.best_block_hash = pindex->GetBlockHash(); |
481 | 0 | } else { |
482 | 0 | summary.best_block_height = 0; |
483 | 0 | summary.best_block_hash = m_chain->getBlockHash(0); |
484 | 0 | } |
485 | 0 | return summary; |
486 | 0 | } |
487 | | |
488 | | void BaseIndex::SetBestBlockIndex(const CBlockIndex* block) |
489 | 0 | { |
490 | 0 | assert(!m_chainstate->m_blockman.IsPruneMode() || AllowPrune()); |
491 | | |
492 | 0 | if (AllowPrune() && block) { |
493 | 0 | node::PruneLockInfo prune_lock; |
494 | 0 | prune_lock.height_first = block->nHeight; |
495 | 0 | WITH_LOCK(::cs_main, m_chainstate->m_blockman.UpdatePruneLock(GetName(), prune_lock)); Line | Count | Source | 290 | 0 | #define WITH_LOCK(cs, code) (MaybeCheckNotHeld(cs), [&]() -> decltype(auto) { LOCK(cs); code; }()) |
|
496 | 0 | } |
497 | | |
498 | | // Intentionally set m_best_block_index as the last step in this function, |
499 | | // after updating prune locks above, and after making any other references |
500 | | // to *this, so the BlockUntilSyncedToCurrentChain function (which checks |
501 | | // m_best_block_index as an optimization) can be used to wait for the last |
502 | | // BlockConnected notification and safely assume that prune locks are |
503 | | // updated and that the index object is safe to delete. |
504 | 0 | m_best_block_index = block; |
505 | 0 | } |