Bitcoin ABC 0.33.10
P2P Digital Currency
base.cpp
Go to the documentation of this file.
1// Copyright (c) 2017-2018 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 <chain.h>
6#include <chainparams.h>
7#include <common/args.h>
8#include <config.h>
9#include <index/base.h>
10#include <interfaces/chain.h>
11#include <logging.h>
12#include <node/abort.h>
13#include <node/blockstorage.h>
14#include <node/context.h>
15#include <node/database_args.h>
16#include <node/ui_interface.h>
17#include <shutdown.h>
18#include <tinyformat.h>
19#include <util/thread.h>
20#include <util/translation.h>
21#include <validation.h> // For Chainstate
22#include <warnings.h>
23
24#include <functional>
25#include <string>
26#include <utility>
27
28constexpr uint8_t DB_BEST_BLOCK{'B'};
29
30constexpr auto SYNC_LOG_INTERVAL{30s};
31constexpr auto SYNC_LOCATOR_WRITE_INTERVAL{30s};
32
33template <typename... Args>
34void BaseIndex::FatalErrorf(const char *fmt, const Args &...args) {
35 auto message = tfm::format(fmt, args...);
36 node::AbortNode(m_chain->context()->exit_status, message);
37}
38
40 const BlockHash &block_hash) {
41 CBlockLocator locator;
42 bool found =
43 chain.findBlock(block_hash, interfaces::FoundBlock().locator(locator));
44 assert(found);
45 assert(!locator.IsNull());
46 return locator;
47}
48
49BaseIndex::DB::DB(const fs::path &path, size_t n_cache_size, bool f_memory,
50 bool f_wipe, bool f_obfuscate)
51 : CDBWrapper{DBParams{.path = path,
52 .cache_bytes = n_cache_size,
53 .memory_only = f_memory,
54 .wipe_data = f_wipe,
55 .obfuscate = f_obfuscate,
56 .options = [] {
59 return options;
60 }()}} {}
61
63 bool success = Read(DB_BEST_BLOCK, locator);
64 if (!success) {
65 locator.SetNull();
66 }
67 return success;
68}
69
71 const CBlockLocator &locator) {
72 batch.Write(DB_BEST_BLOCK, locator);
73}
74
75BaseIndex::BaseIndex(std::unique_ptr<interfaces::Chain> chain, std::string name)
76 : m_chain{std::move(chain)}, m_name{std::move(name)} {}
77
79 Interrupt();
80 Stop();
81}
82
85
86 // May need reset if index is being restarted.
88
89 // Register to validation interface before setting the 'm_synced' flag, so
90 // that callbacks are not missed once m_synced is true.
92
93 CBlockLocator locator;
94 if (!GetDB().ReadBestBlock(locator)) {
95 locator.SetNull();
96 }
97
99 // m_chainstate member gives indexing code access to node internals. It is
100 // removed in followup https://github.com/bitcoin/bitcoin/pull/24230
101 m_chainstate = &m_chain->context()->chainman->GetChainstateForIndexing();
102 CChain &index_chain = m_chainstate->m_chain;
103
104 if (locator.IsNull()) {
105 SetBestBlockIndex(nullptr);
106 } else {
107 // Setting the best block to the locator's top block. If it is not part
108 // of the best chain, we will rewind to the fork point during index sync
109 const CBlockIndex *locator_index{
111 if (!locator_index) {
112 return InitError(
113 strprintf(Untranslated("%s: best block of the index not found. "
114 "Please rebuild the index."),
115 GetName()));
116 }
117 SetBestBlockIndex(locator_index);
118 }
119
120 // Child init
121 const CBlockIndex *start_block = m_best_block_index.load();
122 if (!CustomInit(start_block ? std::make_optional(interfaces::BlockKey{
123 start_block->GetBlockHash(),
124 start_block->nHeight})
125 : std::nullopt)) {
126 return false;
127 }
128
129 // Note: this will latch to true immediately if the user starts up with an
130 // empty datadir and an index enabled. If this is the case, indexation will
131 // happen solely via `BlockConnected` signals until, possibly, the next
132 // restart.
133 m_synced = start_block == index_chain.Tip();
134 m_init = true;
135 return true;
136}
137
138static const CBlockIndex *NextSyncBlock(const CBlockIndex *pindex_prev,
139 CChain &chain)
142
143 if (!pindex_prev) {
144 return chain.Genesis();
145 }
146
147 const CBlockIndex *pindex = chain.Next(pindex_prev);
148 if (pindex) {
149 return pindex;
150 }
151
152 return chain.Next(chain.FindFork(pindex_prev));
153}
154
156 const CBlockIndex *pindex = m_best_block_index.load();
157 if (!m_synced) {
158 std::chrono::steady_clock::time_point last_log_time{0s};
159 std::chrono::steady_clock::time_point last_locator_write_time{0s};
160
161 while (true) {
162 if (m_interrupt) {
163 LogPrintf("%s: m_interrupt set; exiting ThreadSync\n",
164 GetName());
165
166 SetBestBlockIndex(pindex);
167 // No need to handle errors in Commit. If it fails, the error
168 // will be already be logged. The best way to recover is to
169 // continue, as index cannot be corrupted by a missed commit to
170 // disk for an advanced index state.
171 Commit();
172 return;
173 }
174
175 {
176 LOCK(cs_main);
177 const CBlockIndex *pindex_next =
179 if (!pindex_next) {
180 SetBestBlockIndex(pindex);
181 m_synced = true;
182 // No need to handle errors in Commit. See rationale above.
183 Commit();
184 break;
185 }
186 if (pindex_next->pprev != pindex &&
187 !Rewind(pindex, pindex_next->pprev)) {
189 "%s: Failed to rewind index %s to a previous chain tip",
190 __func__, GetName());
191 return;
192 }
193 pindex = pindex_next;
194 }
195
196 CBlock block;
197 if (!m_chainstate->m_blockman.ReadBlock(block, *pindex)) {
198 FatalErrorf("%s: Failed to read block %s from disk", __func__,
199 pindex->GetBlockHash().ToString());
200 return;
201 }
202 if (!WriteBlock(block, pindex)) {
203 FatalErrorf("%s: Failed to write block %s to index database",
204 __func__, pindex->GetBlockHash().ToString());
205 return;
206 }
207
208 auto current_time{std::chrono::steady_clock::now()};
209 if (last_log_time + SYNC_LOG_INTERVAL < current_time) {
210 LogPrintf("Syncing %s with block chain from height %d\n",
211 GetName(), pindex->nHeight);
212 last_log_time = current_time;
213 }
214
215 if (last_locator_write_time + SYNC_LOCATOR_WRITE_INTERVAL <
216 current_time) {
217 SetBestBlockIndex(pindex->pprev);
218 last_locator_write_time = current_time;
219 // No need to handle errors in Commit. See rationale above.
220 Commit();
221 }
222 }
223 }
224
225 if (pindex) {
226 LogPrintf("%s is enabled at height %d\n", GetName(), pindex->nHeight);
227 } else {
228 LogPrintf("%s is enabled\n", GetName());
229 }
230}
231
233 // Don't commit anything if we haven't indexed any block yet
234 // (this could happen if init is interrupted).
235 bool ok = m_best_block_index != nullptr;
236 if (ok) {
237 CDBBatch batch(GetDB());
238 ok = CustomCommit(batch);
239 if (ok) {
241 batch, GetLocator(*m_chain,
242 m_best_block_index.load()->GetBlockHash()));
243 GetDB().WriteBatch(batch);
244 }
245 }
246 if (!ok) {
247 LogError("%s: Failed to commit latest %s state\n", __func__, GetName());
248 return false;
249 }
250 return true;
251}
252
253bool BaseIndex::Rewind(const CBlockIndex *current_tip,
254 const CBlockIndex *new_tip) {
255 assert(current_tip == m_best_block_index);
256 assert(current_tip->GetAncestor(new_tip->nHeight) == new_tip);
257
258 // Don't commit here - the committed index state must never be ahead of the
259 // flushed chainstate, otherwise unclean restarts would lead to index
260 // corruption.
261 // Pruning has a minimum of 288 blocks-to-keep and getting the index
262 // out of sync may be possible but a users fault.
263 // In case we reorg beyond the pruned depth, ReadBlock would
264 // throw and lead to a graceful shutdown
265 SetBestBlockIndex(new_tip);
266 return true;
267}
268
270 const std::shared_ptr<const CBlock> &block,
271 const CBlockIndex *pindex) {
272 // Ignore events from the assumed-valid chain; we will process its blocks
273 // (sequentially) after it is fully verified by the background chainstate.
274 // This is to avoid any out-of-order indexing.
275 //
276 // TODO at some point we could parameterize whether a particular index can
277 // be built out of order, but for now just do the conservative simple thing.
278 if (role == ChainstateRole::ASSUMEDVALID) {
279 return;
280 }
281
282 // Ignore BlockConnected signals until we have fully indexed the chain.
283 if (!m_synced) {
284 return;
285 }
286
287 const CBlockIndex *best_block_index = m_best_block_index.load();
288 if (!best_block_index) {
289 if (pindex->nHeight != 0) {
290 FatalErrorf("%s: First block connected is not the genesis block "
291 "(height=%d)",
292 __func__, pindex->nHeight);
293 return;
294 }
295 } else {
296 // Ensure block connects to an ancestor of the current best block. This
297 // should be the case most of the time, but may not be immediately after
298 // the the sync thread catches up and sets m_synced. Consider the case
299 // where there is a reorg and the blocks on the stale branch are in the
300 // ValidationInterface queue backlog even after the sync thread has
301 // caught up to the new chain tip. In this unlikely event, log a warning
302 // and let the queue clear.
303 if (best_block_index->GetAncestor(pindex->nHeight - 1) !=
304 pindex->pprev) {
305 LogPrintf("%s: WARNING: Block %s does not connect to an ancestor "
306 "of known best chain (tip=%s); not updating index\n",
307 __func__, pindex->GetBlockHash().ToString(),
308 best_block_index->GetBlockHash().ToString());
309 return;
310 }
311 if (best_block_index != pindex->pprev &&
312 !Rewind(best_block_index, pindex->pprev)) {
313 FatalErrorf("%s: Failed to rewind index %s to a previous chain tip",
314 __func__, GetName());
315 return;
316 }
317 }
318
319 if (WriteBlock(*block, pindex)) {
320 // Setting the best block index is intentionally the last step of this
321 // function, so BlockUntilSyncedToCurrentChain callers waiting for the
322 // best block index to be updated can rely on the block being fully
323 // processed, and the index object being safe to delete.
324 SetBestBlockIndex(pindex);
325 } else {
326 FatalErrorf("%s: Failed to write block %s to index", __func__,
327 pindex->GetBlockHash().ToString());
328 return;
329 }
330}
331
333 const CBlockLocator &locator) {
334 // Ignore events from the assumed-valid chain; we will process its blocks
335 // (sequentially) after it is fully verified by the background chainstate.
336 if (role == ChainstateRole::ASSUMEDVALID) {
337 return;
338 }
339
340 if (!m_synced) {
341 return;
342 }
343
344 const BlockHash &locator_tip_hash = locator.vHave.front();
345 const CBlockIndex *locator_tip_index;
346 {
347 LOCK(cs_main);
348 locator_tip_index =
349 m_chainstate->m_blockman.LookupBlockIndex(locator_tip_hash);
350 }
351
352 if (!locator_tip_index) {
353 FatalErrorf("%s: First block (hash=%s) in locator was not found",
354 __func__, locator_tip_hash.ToString());
355 return;
356 }
357
358 // This checks that ChainStateFlushed callbacks are received after
359 // BlockConnected. The check may fail immediately after the the sync thread
360 // catches up and sets m_synced. Consider the case where there is a reorg
361 // and the blocks on the stale branch are in the ValidationInterface queue
362 // backlog even after the sync thread has caught up to the new chain tip. In
363 // this unlikely event, log a warning and let the queue clear.
364 const CBlockIndex *best_block_index = m_best_block_index.load();
365 if (best_block_index->GetAncestor(locator_tip_index->nHeight) !=
366 locator_tip_index) {
367 LogPrintf("%s: WARNING: Locator contains block (hash=%s) not on known "
368 "best chain (tip=%s); not writing index locator\n",
369 __func__, locator_tip_hash.ToString(),
370 best_block_index->GetBlockHash().ToString());
371 return;
372 }
373
374 // No need to handle errors in Commit. If it fails, the error will be
375 // already be logged. The best way to recover is to continue, as index
376 // cannot be corrupted by a missed commit to disk for an advanced index
377 // state.
378 Commit();
379}
380
381bool BaseIndex::BlockUntilSyncedToCurrentChain() const {
383
384 if (!m_synced) {
385 return false;
386 }
387
388 {
389 // Skip the queue-draining stuff if we know we're caught up with
390 // m_chain.Tip().
391 LOCK(cs_main);
392 const CBlockIndex *chain_tip = m_chainstate->m_chain.Tip();
393 const CBlockIndex *best_block_index = m_best_block_index.load();
394 if (best_block_index->GetAncestor(chain_tip->nHeight) == chain_tip) {
395 return true;
396 }
397 }
398
399 LogPrintf("%s: %s is catching up on block notifications\n", __func__,
400 GetName());
402 return true;
403}
404
406 m_interrupt();
407}
408
410 if (!m_init) {
411 throw std::logic_error("Error: Cannot start a non-initialized index");
412 }
413
415 std::thread(&util::TraceThread, GetName(), [this] { ThreadSync(); });
416 return true;
417}
418
421
422 if (m_thread_sync.joinable()) {
423 m_thread_sync.join();
424 }
425}
426
428 IndexSummary summary{};
429 summary.name = GetName();
430 summary.synced = m_synced;
431 if (const auto &pindex = m_best_block_index.load()) {
432 summary.best_block_height = pindex->nHeight;
433 summary.best_block_hash = pindex->GetBlockHash();
434 } else {
435 summary.best_block_height = 0;
436 summary.best_block_hash = m_chain->getBlockHash(0);
437 }
438 return summary;
439}
440
443
444 if (AllowPrune() && block) {
445 node::PruneLockInfo prune_lock;
446 prune_lock.height_first = block->nHeight;
447 WITH_LOCK(::cs_main, m_chainstate->m_blockman.UpdatePruneLock(
448 GetName(), prune_lock));
449 }
450
451 // Intentionally set m_best_block_index as the last step in this function,
452 // after updating prune locks above, and after making any other references
453 // to *this, so the BlockUntilSyncedToCurrentChain function (which checks
454 // m_best_block_index as an optimization) can be used to wait for the last
455 // BlockConnected notification and safely assume that prune locks are
456 // updated and that the index object is safe to delete.
457 m_best_block_index = block;
458}
ArgsManager gArgs
Definition: args.cpp:39
static const CBlockIndex * NextSyncBlock(const CBlockIndex *pindex_prev, CChain &chain) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: base.cpp:138
constexpr uint8_t DB_BEST_BLOCK
Definition: base.cpp:28
constexpr auto SYNC_LOCATOR_WRITE_INTERVAL
Definition: base.cpp:31
constexpr auto SYNC_LOG_INTERVAL
Definition: base.cpp:30
CBlockLocator GetLocator(interfaces::Chain &chain, const BlockHash &block_hash)
Definition: base.cpp:39
void WriteBestBlock(CDBBatch &batch, const CBlockLocator &locator)
Write block locator of the chain that the index is in sync with.
Definition: base.cpp:70
DB(const fs::path &path, size_t n_cache_size, bool f_memory=false, bool f_wipe=false, bool f_obfuscate=false)
Definition: base.cpp:49
bool ReadBestBlock(CBlockLocator &locator) const
Read block locator of the chain that the index is in sync with.
Definition: base.cpp:62
void Stop()
Stops the instance from staying in sync with blockchain updates.
Definition: base.cpp:419
void SetBestBlockIndex(const CBlockIndex *block)
Update the internal best block index as well as the prune lock.
Definition: base.cpp:441
bool Init()
Initializes the sync state and registers the instance to the validation interface so that it stays in...
Definition: base.cpp:83
virtual ~BaseIndex()
Destructor interrupts sync thread if running and blocks until it exits.
Definition: base.cpp:78
std::atomic< const CBlockIndex * > m_best_block_index
The last block in the chain that the index is in sync with.
Definition: base.h:71
virtual bool CustomCommit(CDBBatch &batch)
Virtual method called internally by Commit that can be overridden to atomically commit more index sta...
Definition: base.h:125
const std::string & GetName() const LIFETIMEBOUND
Get the name of the index for display in logs.
Definition: base.h:143
bool BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(void Interrupt()
Blocks the current thread until the index is caught up to the current state of the block chain.
Definition: base.cpp:405
virtual bool AllowPrune() const =0
void BlockConnected(ChainstateRole role, const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex) override
Notifies listeners of a block being connected.
Definition: base.cpp:269
std::atomic< bool > m_synced
Whether the index is in sync with the main chain.
Definition: base.h:68
CThreadInterrupt m_interrupt
Definition: base.h:74
BaseIndex(std::unique_ptr< interfaces::Chain > chain, std::string name)
Definition: base.cpp:75
IndexSummary GetSummary() const
Get a summary of the index and its state.
Definition: base.cpp:427
const std::string m_name
Definition: base.h:103
virtual DB & GetDB() const =0
std::thread m_thread_sync
Definition: base.h:73
bool Commit()
Write the current index state (eg.
Definition: base.cpp:232
virtual bool WriteBlock(const CBlock &block, const CBlockIndex *pindex)
Write update index entries for a newly connected block.
Definition: base.h:119
virtual bool CustomInit(const std::optional< interfaces::BlockKey > &block)
Initialize internal state from the database and block index.
Definition: base.h:114
void ThreadSync()
Sync the index with the block index starting from the current best block.
Definition: base.cpp:155
void FatalErrorf(const char *fmt, const Args &...args)
Definition: base.cpp:34
Chainstate * m_chainstate
Definition: base.h:102
virtual bool Rewind(const CBlockIndex *current_tip, const CBlockIndex *new_tip)
Rewind index to an earlier chain tip during a chain reorg.
Definition: base.cpp:253
bool StartBackgroundSync()
Starts the initial sync process.
Definition: base.cpp:409
void ChainStateFlushed(ChainstateRole role, const CBlockLocator &locator) override
Notifies listeners of the new active block chain on-disk.
Definition: base.cpp:332
std::unique_ptr< interfaces::Chain > m_chain
Definition: base.h:101
std::atomic< bool > m_init
Whether the index has been initialized or not.
Definition: base.h:60
Definition: block.h:60
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: blockindex.h:32
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: blockindex.cpp:62
BlockHash GetBlockHash() const
Definition: blockindex.h:130
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:38
An in-memory indexed chain of blocks.
Definition: chain.h:138
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:154
Batch of changes queued to be written to a CDBWrapper.
Definition: dbwrapper.h:78
void Write(const K &key, const V &value)
Definition: dbwrapper.h:101
leveldb::Options options
database options used
Definition: dbwrapper.h:207
void WriteBatch(CDBBatch &batch, bool fSync=false)
Definition: dbwrapper.cpp:198
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:820
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Definition: validation.h:778
std::string ToString() const
Definition: uint256.h:80
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:136
virtual bool findBlock(const BlockHash &hash, const FoundBlock &block={})=0
Return whether node has the block and optionally return block metadata or contents.
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:55
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool IsPruneMode() const
Whether running in -prune mode.
Definition: blockstorage.h:350
bool ReadBlock(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
ChainstateRole
This enum describes the various roles a specific Chainstate instance can take.
Definition: chain.h:14
#define LogError(...)
Definition: logging.h:419
#define LogPrintf(...)
Definition: logging.h:424
void AbortNode(std::atomic< int > &exit_status, const std::string &debug_message, const bilingual_str &user_message, bool shutdown)
Definition: abort.cpp:19
void ReadDatabaseArgs(const ArgsManager &args, DBOptions &options)
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:259
void format(std::ostream &out, const char *fmt, const Args &...args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1112
void TraceThread(std::string_view thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
Definition: thread.cpp:14
const char * name
Definition: rest.cpp:47
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:108
std::vector< BlockHash > vHave
Definition: block.h:120
bool IsNull() const
Definition: block.h:135
void SetNull()
Definition: block.h:133
User-controlled performance and debug options.
Definition: dbwrapper.h:26
Application-specific storage settings.
Definition: dbwrapper.h:32
std::string name
Definition: base.h:21
Hash/height pair to help track and identify blocks.
Definition: chain.h:49
int height_first
Height of earliest block that should be kept and not pruned.
Definition: blockstorage.h:78
#define AssertLockNotHeld(cs)
Definition: sync.h:163
#define LOCK(cs)
Definition: sync.h:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:36
bool InitError(const bilingual_str &str)
Show error message.
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())
void UnregisterValidationInterface(CValidationInterface *callbacks)
Unregister subscriber.
void RegisterValidationInterface(CValidationInterface *callbacks)
Register subscriber.
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...