Bitcoin ABC 0.32.4
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 int64_t SYNC_LOG_INTERVAL = 30; // secon
31constexpr int64_t SYNC_LOCATOR_WRITE_INTERVAL = 30; // seconds
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 int64_t last_log_time = 0;
159 int64_t last_locator_write_time = 0;
160 while (true) {
161 if (m_interrupt) {
162 LogPrintf("%s: m_interrupt set; exiting ThreadSync\n",
163 GetName());
164
165 SetBestBlockIndex(pindex);
166 // No need to handle errors in Commit. If it fails, the error
167 // will be already be logged. The best way to recover is to
168 // continue, as index cannot be corrupted by a missed commit to
169 // disk for an advanced index state.
170 Commit();
171 return;
172 }
173
174 {
175 LOCK(cs_main);
176 const CBlockIndex *pindex_next =
178 if (!pindex_next) {
179 SetBestBlockIndex(pindex);
180 m_synced = true;
181 // No need to handle errors in Commit. See rationale above.
182 Commit();
183 break;
184 }
185 if (pindex_next->pprev != pindex &&
186 !Rewind(pindex, pindex_next->pprev)) {
188 "%s: Failed to rewind index %s to a previous chain tip",
189 __func__, GetName());
190 return;
191 }
192 pindex = pindex_next;
193 }
194
195 CBlock block;
196 if (!m_chainstate->m_blockman.ReadBlockFromDisk(block, *pindex)) {
197 FatalErrorf("%s: Failed to read block %s from disk", __func__,
198 pindex->GetBlockHash().ToString());
199 return;
200 }
201 if (!WriteBlock(block, pindex)) {
202 FatalErrorf("%s: Failed to write block %s to index database",
203 __func__, pindex->GetBlockHash().ToString());
204 return;
205 }
206
207 int64_t current_time = GetTime();
208 if (last_log_time + SYNC_LOG_INTERVAL < current_time) {
209 LogPrintf("Syncing %s with block chain from height %d\n",
210 GetName(), pindex->nHeight);
211 last_log_time = current_time;
212 }
213
214 if (last_locator_write_time + SYNC_LOCATOR_WRITE_INTERVAL <
215 current_time) {
216 SetBestBlockIndex(pindex->pprev);
217 last_locator_write_time = current_time;
218 // No need to handle errors in Commit. See rationale above.
219 Commit();
220 }
221 }
222 }
223
224 if (pindex) {
225 LogPrintf("%s is enabled at height %d\n", GetName(), pindex->nHeight);
226 } else {
227 LogPrintf("%s is enabled\n", GetName());
228 }
229}
230
232 // Don't commit anything if we haven't indexed any block yet
233 // (this could happen if init is interrupted).
234 bool ok = m_best_block_index != nullptr;
235 if (ok) {
236 CDBBatch batch(GetDB());
237 ok = CustomCommit(batch);
238 if (ok) {
240 batch, GetLocator(*m_chain,
241 m_best_block_index.load()->GetBlockHash()));
242 ok = GetDB().WriteBatch(batch);
243 }
244 }
245 if (!ok) {
246 LogError("%s: Failed to commit latest %s state\n", __func__, GetName());
247 return false;
248 }
249 return true;
250}
251
252bool BaseIndex::Rewind(const CBlockIndex *current_tip,
253 const CBlockIndex *new_tip) {
254 assert(current_tip == m_best_block_index);
255 assert(current_tip->GetAncestor(new_tip->nHeight) == new_tip);
256
257 // Don't commit here - the committed index state must never be ahead of the
258 // flushed chainstate, otherwise unclean restarts would lead to index
259 // corruption.
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 return true;
266}
267
269 const std::shared_ptr<const CBlock> &block,
270 const CBlockIndex *pindex) {
271 // Ignore events from the assumed-valid chain; we will process its blocks
272 // (sequentially) after it is fully verified by the background chainstate.
273 // This is to avoid any out-of-order indexing.
274 //
275 // TODO at some point we could parameterize whether a particular index can
276 // be built out of order, but for now just do the conservative simple thing.
277 if (role == ChainstateRole::ASSUMEDVALID) {
278 return;
279 }
280
281 // Ignore BlockConnected signals until we have fully indexed the chain.
282 if (!m_synced) {
283 return;
284 }
285
286 const CBlockIndex *best_block_index = m_best_block_index.load();
287 if (!best_block_index) {
288 if (pindex->nHeight != 0) {
289 FatalErrorf("%s: First block connected is not the genesis block "
290 "(height=%d)",
291 __func__, pindex->nHeight);
292 return;
293 }
294 } else {
295 // Ensure block connects to an ancestor of the current best block. This
296 // should be the case most of the time, but may not be immediately after
297 // the the sync thread catches up and sets m_synced. Consider the case
298 // where there is a reorg and the blocks on the stale branch are in the
299 // ValidationInterface queue backlog even after the sync thread has
300 // caught up to the new chain tip. In this unlikely event, log a warning
301 // and let the queue clear.
302 if (best_block_index->GetAncestor(pindex->nHeight - 1) !=
303 pindex->pprev) {
304 LogPrintf("%s: WARNING: Block %s does not connect to an ancestor "
305 "of known best chain (tip=%s); not updating index\n",
306 __func__, pindex->GetBlockHash().ToString(),
307 best_block_index->GetBlockHash().ToString());
308 return;
309 }
310 if (best_block_index != pindex->pprev &&
311 !Rewind(best_block_index, pindex->pprev)) {
312 FatalErrorf("%s: Failed to rewind index %s to a previous chain tip",
313 __func__, GetName());
314 return;
315 }
316 }
317
318 if (WriteBlock(*block, pindex)) {
319 // Setting the best block index is intentionally the last step of this
320 // function, so BlockUntilSyncedToCurrentChain callers waiting for the
321 // best block index to be updated can rely on the block being fully
322 // processed, and the index object being safe to delete.
323 SetBestBlockIndex(pindex);
324 } else {
325 FatalErrorf("%s: Failed to write block %s to index", __func__,
326 pindex->GetBlockHash().ToString());
327 return;
328 }
329}
330
332 const CBlockLocator &locator) {
333 // Ignore events from the assumed-valid chain; we will process its blocks
334 // (sequentially) after it is fully verified by the background chainstate.
335 if (role == ChainstateRole::ASSUMEDVALID) {
336 return;
337 }
338
339 if (!m_synced) {
340 return;
341 }
342
343 const BlockHash &locator_tip_hash = locator.vHave.front();
344 const CBlockIndex *locator_tip_index;
345 {
346 LOCK(cs_main);
347 locator_tip_index =
348 m_chainstate->m_blockman.LookupBlockIndex(locator_tip_hash);
349 }
350
351 if (!locator_tip_index) {
352 FatalErrorf("%s: First block (hash=%s) in locator was not found",
353 __func__, locator_tip_hash.ToString());
354 return;
355 }
356
357 // This checks that ChainStateFlushed callbacks are received after
358 // BlockConnected. The check may fail immediately after the the sync thread
359 // catches up and sets m_synced. Consider the case where there is a reorg
360 // and the blocks on the stale branch are in the ValidationInterface queue
361 // backlog even after the sync thread has caught up to the new chain tip. In
362 // this unlikely event, log a warning and let the queue clear.
363 const CBlockIndex *best_block_index = m_best_block_index.load();
364 if (best_block_index->GetAncestor(locator_tip_index->nHeight) !=
365 locator_tip_index) {
366 LogPrintf("%s: WARNING: Locator contains block (hash=%s) not on known "
367 "best chain (tip=%s); not writing index locator\n",
368 __func__, locator_tip_hash.ToString(),
369 best_block_index->GetBlockHash().ToString());
370 return;
371 }
372
373 // No need to handle errors in Commit. If it fails, the error will be
374 // already be logged. The best way to recover is to continue, as index
375 // cannot be corrupted by a missed commit to disk for an advanced index
376 // state.
377 Commit();
378}
379
380bool BaseIndex::BlockUntilSyncedToCurrentChain() const {
382
383 if (!m_synced) {
384 return false;
385 }
386
387 {
388 // Skip the queue-draining stuff if we know we're caught up with
389 // m_chain.Tip().
390 LOCK(cs_main);
391 const CBlockIndex *chain_tip = m_chainstate->m_chain.Tip();
392 const CBlockIndex *best_block_index = m_best_block_index.load();
393 if (best_block_index->GetAncestor(chain_tip->nHeight) == chain_tip) {
394 return true;
395 }
396 }
397
398 LogPrintf("%s: %s is catching up on block notifications\n", __func__,
399 GetName());
401 return true;
402}
403
405 m_interrupt();
406}
407
409 if (!m_init) {
410 throw std::logic_error("Error: Cannot start a non-initialized index");
411 }
412
414 std::thread(&util::TraceThread, GetName(), [this] { ThreadSync(); });
415 return true;
416}
417
420
421 if (m_thread_sync.joinable()) {
422 m_thread_sync.join();
423 }
424}
425
427 IndexSummary summary{};
428 summary.name = GetName();
429 summary.synced = m_synced;
430 if (const auto &pindex = m_best_block_index.load()) {
431 summary.best_block_height = pindex->nHeight;
432 summary.best_block_hash = pindex->GetBlockHash();
433 } else {
434 summary.best_block_height = 0;
435 summary.best_block_hash = m_chain->getBlockHash(0);
436 }
437 return summary;
438}
439
442
443 if (AllowPrune() && block) {
444 node::PruneLockInfo prune_lock;
445 prune_lock.height_first = block->nHeight;
446 WITH_LOCK(::cs_main, m_chainstate->m_blockman.UpdatePruneLock(
447 GetName(), prune_lock));
448 }
449
450 // Intentionally set m_best_block_index as the last step in this function,
451 // after updating prune locks above, and after making any other references
452 // to *this, so the BlockUntilSyncedToCurrentChain function (which checks
453 // m_best_block_index as an optimization) can be used to wait for the last
454 // BlockConnected notification and safely assume that prune locks are
455 // updated and that the index object is safe to delete.
456 m_best_block_index = block;
457}
ArgsManager gArgs
Definition: args.cpp:40
constexpr int64_t SYNC_LOG_INTERVAL
Definition: base.cpp:30
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
CBlockLocator GetLocator(interfaces::Chain &chain, const BlockHash &block_hash)
Definition: base.cpp:39
constexpr int64_t SYNC_LOCATOR_WRITE_INTERVAL
Definition: base.cpp:31
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:418
void SetBestBlockIndex(const CBlockIndex *block)
Update the internal best block index as well as the prune lock.
Definition: base.cpp:440
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:404
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:268
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:426
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:231
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:252
bool StartBackgroundSync()
Starts the initial sync process.
Definition: base.cpp:408
void ChainStateFlushed(ChainstateRole role, const CBlockLocator &locator) override
Notifies listeners of the new active block chain on-disk.
Definition: base.cpp:331
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: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:833
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Definition: validation.h:791
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:359
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: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:69
#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:105
#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...