Bitcoin Core 22.99.0
P2P Digital Currency
base.cpp
Go to the documentation of this file.
1// Copyright (c) 2017-2020 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 <index/base.h>
7#include <node/blockstorage.h>
8#include <node/ui_interface.h>
9#include <shutdown.h>
10#include <tinyformat.h>
12#include <util/thread.h>
13#include <util/translation.h>
14#include <validation.h> // For g_chainman
15#include <warnings.h>
16
17constexpr uint8_t DB_BEST_BLOCK{'B'};
18
19constexpr int64_t SYNC_LOG_INTERVAL = 30; // seconds
20constexpr int64_t SYNC_LOCATOR_WRITE_INTERVAL = 30; // seconds
21
22template <typename... Args>
23static void FatalError(const char* fmt, const Args&... args)
24{
25 std::string strMessage = tfm::format(fmt, args...);
26 SetMiscWarning(Untranslated(strMessage));
27 LogPrintf("*** %s\n", strMessage);
28 AbortError(_("A fatal internal error occurred, see debug.log for details"));
30}
31
32BaseIndex::DB::DB(const fs::path& path, size_t n_cache_size, bool f_memory, bool f_wipe, bool f_obfuscate) :
33 CDBWrapper(path, n_cache_size, f_memory, f_wipe, f_obfuscate)
34{}
35
37{
38 bool success = Read(DB_BEST_BLOCK, locator);
39 if (!success) {
40 locator.SetNull();
41 }
42 return success;
43}
44
46{
47 batch.Write(DB_BEST_BLOCK, locator);
48}
49
51{
52 Interrupt();
53 Stop();
54}
55
57{
58 CBlockLocator locator;
59 if (!GetDB().ReadBestBlock(locator)) {
60 locator.SetNull();
61 }
62
64 CChain& active_chain = m_chainstate->m_chain;
65 if (locator.IsNull()) {
66 m_best_block_index = nullptr;
67 } else {
69 }
70 m_synced = m_best_block_index.load() == active_chain.Tip();
71 if (!m_synced) {
72 bool prune_violation = false;
73 if (!m_best_block_index) {
74 // index is not built yet
75 // make sure we have all block data back to the genesis
76 const CBlockIndex* block = active_chain.Tip();
77 while (block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) {
78 block = block->pprev;
79 }
80 prune_violation = block != active_chain.Genesis();
81 }
82 // in case the index has a best block set and is not fully synced
83 // check if we have the required blocks to continue building the index
84 else {
85 const CBlockIndex* block_to_test = m_best_block_index.load();
86 if (!active_chain.Contains(block_to_test)) {
87 // if the bestblock is not part of the mainchain, find the fork
88 // and make sure we have all data down to the fork
89 block_to_test = active_chain.FindFork(block_to_test);
90 }
91 const CBlockIndex* block = active_chain.Tip();
92 prune_violation = true;
93 // check backwards from the tip if we have all block data until we reach the indexes bestblock
94 while (block_to_test && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) {
95 if (block_to_test == block) {
96 prune_violation = false;
97 break;
98 }
99 block = block->pprev;
100 }
101 }
102 if (prune_violation) {
103 return InitError(strprintf(Untranslated("%s best block of the index goes beyond pruned data. Please disable the index or reindex (which will download the whole blockchain again)"), GetName()));
104 }
105 }
106 return true;
107}
108
110{
112
113 if (!pindex_prev) {
114 return chain.Genesis();
115 }
116
117 const CBlockIndex* pindex = chain.Next(pindex_prev);
118 if (pindex) {
119 return pindex;
120 }
121
122 return chain.Next(chain.FindFork(pindex_prev));
123}
124
126{
128 const CBlockIndex* pindex = m_best_block_index.load();
129 if (!m_synced) {
130 auto& consensus_params = Params().GetConsensus();
131
132 int64_t last_log_time = 0;
133 int64_t last_locator_write_time = 0;
134 while (true) {
135 if (m_interrupt) {
136 m_best_block_index = pindex;
137 // No need to handle errors in Commit. If it fails, the error will be already be
138 // logged. The best way to recover is to continue, as index cannot be corrupted by
139 // a missed commit to disk for an advanced index state.
140 Commit();
141 return;
142 }
143
144 {
145 LOCK(cs_main);
146 const CBlockIndex* pindex_next = NextSyncBlock(pindex, m_chainstate->m_chain);
147 if (!pindex_next) {
148 m_best_block_index = pindex;
149 m_synced = true;
150 // No need to handle errors in Commit. See rationale above.
151 Commit();
152 break;
153 }
154 if (pindex_next->pprev != pindex && !Rewind(pindex, pindex_next->pprev)) {
155 FatalError("%s: Failed to rewind index %s to a previous chain tip",
156 __func__, GetName());
157 return;
158 }
159 pindex = pindex_next;
160 }
161
162 int64_t current_time = GetTime();
163 if (last_log_time + SYNC_LOG_INTERVAL < current_time) {
164 LogPrintf("Syncing %s with block chain from height %d\n",
165 GetName(), pindex->nHeight);
166 last_log_time = current_time;
167 }
168
169 if (last_locator_write_time + SYNC_LOCATOR_WRITE_INTERVAL < current_time) {
170 m_best_block_index = pindex;
171 last_locator_write_time = current_time;
172 // No need to handle errors in Commit. See rationale above.
173 Commit();
174 }
175
176 CBlock block;
177 if (!ReadBlockFromDisk(block, pindex, consensus_params)) {
178 FatalError("%s: Failed to read block %s from disk",
179 __func__, pindex->GetBlockHash().ToString());
180 return;
181 }
182 if (!WriteBlock(block, pindex)) {
183 FatalError("%s: Failed to write block %s to index database",
184 __func__, pindex->GetBlockHash().ToString());
185 return;
186 }
187 }
188 }
189
190 if (pindex) {
191 LogPrintf("%s is enabled at height %d\n", GetName(), pindex->nHeight);
192 } else {
193 LogPrintf("%s is enabled\n", GetName());
194 }
195}
196
198{
199 CDBBatch batch(GetDB());
200 if (!CommitInternal(batch) || !GetDB().WriteBatch(batch)) {
201 return error("%s: Failed to commit latest %s state", __func__, GetName());
202 }
203 return true;
204}
205
207{
208 LOCK(cs_main);
210 return true;
211}
212
213bool BaseIndex::Rewind(const CBlockIndex* current_tip, const CBlockIndex* new_tip)
214{
215 assert(current_tip == m_best_block_index);
216 assert(current_tip->GetAncestor(new_tip->nHeight) == new_tip);
217
218 // In the case of a reorg, ensure persisted block locator is not stale.
219 // Pruning has a minimum of 288 blocks-to-keep and getting the index
220 // out of sync may be possible but a users fault.
221 // In case we reorg beyond the pruned depth, ReadBlockFromDisk would
222 // throw and lead to a graceful shutdown
223 m_best_block_index = new_tip;
224 if (!Commit()) {
225 // If commit fails, revert the best block index to avoid corruption.
226 m_best_block_index = current_tip;
227 return false;
228 }
229
230 return true;
231}
232
233void BaseIndex::BlockConnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex)
234{
235 if (!m_synced) {
236 return;
237 }
238
239 const CBlockIndex* best_block_index = m_best_block_index.load();
240 if (!best_block_index) {
241 if (pindex->nHeight != 0) {
242 FatalError("%s: First block connected is not the genesis block (height=%d)",
243 __func__, pindex->nHeight);
244 return;
245 }
246 } else {
247 // Ensure block connects to an ancestor of the current best block. This should be the case
248 // most of the time, but may not be immediately after the sync thread catches up and sets
249 // m_synced. Consider the case where there is a reorg and the blocks on the stale branch are
250 // in the ValidationInterface queue backlog even after the sync thread has caught up to the
251 // new chain tip. In this unlikely event, log a warning and let the queue clear.
252 if (best_block_index->GetAncestor(pindex->nHeight - 1) != pindex->pprev) {
253 LogPrintf("%s: WARNING: Block %s does not connect to an ancestor of " /* Continued */
254 "known best chain (tip=%s); not updating index\n",
255 __func__, pindex->GetBlockHash().ToString(),
256 best_block_index->GetBlockHash().ToString());
257 return;
258 }
259 if (best_block_index != pindex->pprev && !Rewind(best_block_index, pindex->pprev)) {
260 FatalError("%s: Failed to rewind index %s to a previous chain tip",
261 __func__, GetName());
262 return;
263 }
264 }
265
266 if (WriteBlock(*block, pindex)) {
267 m_best_block_index = pindex;
268 } else {
269 FatalError("%s: Failed to write block %s to index",
270 __func__, pindex->GetBlockHash().ToString());
271 return;
272 }
273}
274
276{
277 if (!m_synced) {
278 return;
279 }
280
281 const uint256& locator_tip_hash = locator.vHave.front();
282 const CBlockIndex* locator_tip_index;
283 {
284 LOCK(cs_main);
285 locator_tip_index = m_chainstate->m_blockman.LookupBlockIndex(locator_tip_hash);
286 }
287
288 if (!locator_tip_index) {
289 FatalError("%s: First block (hash=%s) in locator was not found",
290 __func__, locator_tip_hash.ToString());
291 return;
292 }
293
294 // This checks that ChainStateFlushed callbacks are received after BlockConnected. The check may fail
295 // immediately after the sync thread catches up and sets m_synced. Consider the case where
296 // there is a reorg and the blocks on the stale branch are in the ValidationInterface queue
297 // backlog even after the sync thread has caught up to the new chain tip. In this unlikely
298 // event, log a warning and let the queue clear.
299 const CBlockIndex* best_block_index = m_best_block_index.load();
300 if (best_block_index->GetAncestor(locator_tip_index->nHeight) != locator_tip_index) {
301 LogPrintf("%s: WARNING: Locator contains block (hash=%s) not on known best " /* Continued */
302 "chain (tip=%s); not writing index locator\n",
303 __func__, locator_tip_hash.ToString(),
304 best_block_index->GetBlockHash().ToString());
305 return;
306 }
307
308 // No need to handle errors in Commit. If it fails, the error will be already be logged. The
309 // best way to recover is to continue, as index cannot be corrupted by a missed commit to disk
310 // for an advanced index state.
311 Commit();
312}
313
314bool BaseIndex::BlockUntilSyncedToCurrentChain() const
315{
317
318 if (!m_synced) {
319 return false;
320 }
321
322 {
323 // Skip the queue-draining stuff if we know we're caught up with
324 // m_chain.Tip().
325 LOCK(cs_main);
326 const CBlockIndex* chain_tip = m_chainstate->m_chain.Tip();
327 const CBlockIndex* best_block_index = m_best_block_index.load();
328 if (best_block_index->GetAncestor(chain_tip->nHeight) == chain_tip) {
329 return true;
330 }
331 }
332
333 LogPrintf("%s: %s is catching up on block notifications\n", __func__, GetName());
335 return true;
336}
337
339{
340 m_interrupt();
341}
342
343bool BaseIndex::Start(CChainState& active_chainstate)
344{
345 m_chainstate = &active_chainstate;
346 // Need to register this ValidationInterface before running Init(), so that
347 // callbacks are not missed if Init sets m_synced to true.
349 if (!Init()) {
350 return false;
351 }
352
353 m_thread_sync = std::thread(&util::TraceThread, GetName(), [this] { ThreadSync(); });
354 return true;
355}
356
358{
360
361 if (m_thread_sync.joinable()) {
362 m_thread_sync.join();
363 }
364}
365
367{
368 IndexSummary summary{};
369 summary.name = GetName();
370 summary.synced = m_synced;
371 summary.best_block_height = m_best_block_index ? m_best_block_index.load()->nHeight : 0;
372 return summary;
373}
constexpr int64_t SYNC_LOG_INTERVAL
Definition: base.cpp:19
static void FatalError(const char *fmt, const Args &... args)
Definition: base.cpp:23
static const CBlockIndex * NextSyncBlock(const CBlockIndex *pindex_prev, CChain &chain) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: base.cpp:109
constexpr uint8_t DB_BEST_BLOCK
Definition: base.cpp:17
constexpr int64_t SYNC_LOCATOR_WRITE_INTERVAL
Definition: base.cpp:20
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:118
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
@ BLOCK_HAVE_DATA
full block available in blk*.dat
Definition: chain.h:121
const CChainParams & Params()
Return the currently selected parameters.
void WriteBestBlock(CDBBatch &batch, const CBlockLocator &locator)
Write block locator of the chain that the txindex is in sync with.
Definition: base.cpp:45
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:32
bool ReadBestBlock(CBlockLocator &locator) const
Read block locator of the chain that the txindex is in sync with.
Definition: base.cpp:36
void Stop()
Stops the instance from staying in sync with blockchain updates.
Definition: base.cpp:357
virtual bool Init()
Initialize internal state from the database and block index.
Definition: base.cpp:56
void BlockConnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex) override
Notifies listeners of a block being connected.
Definition: base.cpp:233
virtual const char * GetName() const =0
Get the name of the index for display in logs.
CChainState * m_chainstate
Definition: base.h:79
virtual ~BaseIndex()
Destructor interrupts sync thread if running and blocks until it exits.
Definition: base.cpp:50
virtual bool CommitInternal(CDBBatch &batch)
Virtual method called internally by Commit that can be overridden to atomically commit more index sta...
Definition: base.cpp:206
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:338
std::atomic< bool > m_synced
Whether the index is in sync with the main chain.
Definition: base.h:54
CThreadInterrupt m_interrupt
Definition: base.h:60
IndexSummary GetSummary() const
Get a summary of the index and its state.
Definition: base.cpp:366
virtual DB & GetDB() const =0
void ChainStateFlushed(const CBlockLocator &locator) override
Notifies listeners of the new active block chain on-disk.
Definition: base.cpp:275
std::thread m_thread_sync
Definition: base.h:59
bool Commit()
Write the current index state (eg.
Definition: base.cpp:197
virtual bool WriteBlock(const CBlock &block, const CBlockIndex *pindex)
Write update index entries for a newly connected block.
Definition: base.h:91
void ThreadSync()
Sync the index with the block index starting from the current best block.
Definition: base.cpp:125
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:213
std::atomic< const CBlockIndex * > m_best_block_index
The last block in the chain that the index is in sync with.
Definition: base.h:57
bool Start(CChainState &active_chainstate)
Start initializes the sync state and registers the instance as a ValidationInterface so that it stays...
Definition: base.cpp:343
CBlockIndex * LookupBlockIndex(const uint256 &hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:150
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the last common block between the parameter chain and a locator.
Definition: validation.cpp:157
Definition: block.h:63
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:146
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:152
uint256 GetBlockHash() const
Definition: chain.h:254
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:111
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:158
uint32_t nStatus
Verification status of this block.
Definition: chain.h:195
An in-memory indexed chain of blocks.
Definition: chain.h:410
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:421
CBlockLocator GetLocator(const CBlockIndex *pindex=nullptr) const
Return a CBlockLocator that refers to a block in this chain (by default the tip).
Definition: chain.cpp:23
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:416
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:51
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:433
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:82
CChainState stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:544
BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances.
Definition: validation.h:583
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:620
Batch of changes queued to be written to a CDBWrapper.
Definition: dbwrapper.h:48
void Write(const K &key, const V &value)
Definition: dbwrapper.h:73
std::string ToString() const
Definition: uint256.cpp:64
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
Definition: fs.h:34
256-bit opaque blob.
Definition: uint256.h:124
#define LogPrintf(...)
Definition: logging.h:187
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:1062
void TraceThread(const char *thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
Definition: thread.cpp:13
void StartShutdown()
Request shutdown of the application.
Definition: shutdown.cpp:56
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:115
std::vector< uint256 > vHave
Definition: block.h:116
bool IsNull() const
Definition: block.h:135
void SetNull()
Definition: block.h:130
std::string name
Definition: base.h:17
#define AssertLockNotHeld(cs)
Definition: sync.h:84
#define LOCK(cs)
Definition: sync.h:226
void SetSyscallSandboxPolicy(SyscallSandboxPolicy syscall_policy)
Force the current thread (and threads created from the current thread) into a restricted-service oper...
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
int64_t GetTime()
DEPRECATED Use either GetTimeSeconds (not mockable) or GetTime<T> (mockable)
Definition: time.cpp:26
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:63
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:46
bool InitError(const bilingual_str &str)
Show error message.
constexpr auto AbortError
Definition: ui_interface.h:117
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:19