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