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