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