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