6#include <chainparams.h>
18#include <validation.h>
28template <
typename... Args>
29static void FatalError(
const char *fmt,
const Args &...args) {
33 AbortError(
_(
"A fatal internal error occurred, see debug.log for details"));
38 bool f_wipe,
bool f_obfuscate)
40 .cache_bytes = n_cache_size,
41 .memory_only = f_memory,
43 .obfuscate = f_obfuscate,
70 if (!
GetDB().ReadBestBlock(locator)) {
83 bool prune_violation =
false;
89 *active_chain.
Tip()) != active_chain.
Genesis();
95 if (!active_chain.
Contains(block_to_test)) {
98 block_to_test = active_chain.
FindFork(block_to_test);
101 prune_violation =
true;
104 while (block_to_test && block && block->nStatus.hasData()) {
105 if (block_to_test == block) {
106 prune_violation =
false;
113 block = block->
pprev;
116 if (prune_violation) {
118 Untranslated(
"%s best block of the index goes beyond pruned "
119 "data. Please disable the index or reindex (which "
120 "will download the whole blockchain again)"),
133 return chain.Genesis();
136 const CBlockIndex *pindex = chain.Next(pindex_prev);
141 return chain.Next(chain.FindFork(pindex_prev));
147 int64_t last_log_time = 0;
148 int64_t last_locator_write_time = 0;
171 if (pindex_next->
pprev != pindex &&
174 "%s: Failed to rewind index %s to a previous chain tip",
178 pindex = pindex_next;
181 int64_t current_time =
GetTime();
183 LogPrintf(
"Syncing %s with block chain from height %d\n",
185 last_log_time = current_time;
191 last_locator_write_time = current_time;
198 FatalError(
"%s: Failed to read block %s from disk", __func__,
203 FatalError(
"%s: Failed to write block %s to index database",
220 return error(
"%s: Failed to commit latest %s state", __func__,
264 if (!best_block_index) {
266 FatalError(
"%s: First block connected is not the genesis block "
281 LogPrintf(
"%s: WARNING: Block %s does not connect to an ancestor "
282 "of known best chain (tip=%s); not updating index\n",
287 if (best_block_index != pindex->
pprev &&
289 FatalError(
"%s: Failed to rewind index %s to a previous chain tip",
302 FatalError(
"%s: Failed to write block %s to index", __func__,
321 if (!locator_tip_index) {
322 FatalError(
"%s: First block (hash=%s) in locator was not found",
323 __func__, locator_tip_hash.
ToString());
336 LogPrintf(
"%s: WARNING: Locator contains block (hash=%s) not on known "
337 "best chain (tip=%s); not writing index locator\n",
338 __func__, locator_tip_hash.
ToString(),
350bool BaseIndex::BlockUntilSyncedToCurrentChain()
const {
368 LogPrintf(
"%s: %s is catching up on block notifications\n", __func__,
404 summary.best_block_height =
constexpr int64_t SYNC_LOG_INTERVAL
static const CBlockIndex * NextSyncBlock(const CBlockIndex *pindex_prev, CChain &chain) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
constexpr uint8_t DB_BEST_BLOCK
static void FatalError(const char *fmt, const Args &...args)
constexpr int64_t SYNC_LOCATOR_WRITE_INTERVAL
CBlockLocator GetLocator(const CBlockIndex *index)
Get a locator for a block index entry.
void WriteBestBlock(CDBBatch &batch, const CBlockLocator &locator)
Write block locator of the chain that the index is in sync with.
DB(const fs::path &path, size_t n_cache_size, bool f_memory=false, bool f_wipe=false, bool f_obfuscate=false)
bool ReadBestBlock(CBlockLocator &locator) const
Read block locator of the chain that the index is in sync with.
void Stop()
Stops the instance from staying in sync with blockchain updates.
void SetBestBlockIndex(const CBlockIndex *block)
Update the internal best block index as well as the prune lock.
virtual bool Init()
Initialize internal state from the database and block index.
void BlockConnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex) override
Notifies listeners of a block being connected.
virtual const char * GetName() const =0
Get the name of the index for display in logs.
bool Start(Chainstate &active_chainstate)
Start initializes the sync state and registers the instance as a ValidationInterface so that it stays...
virtual ~BaseIndex()
Destructor interrupts sync thread if running and blocks until it exits.
std::atomic< const CBlockIndex * > m_best_block_index
The last block in the chain that the index is in sync with.
virtual bool CommitInternal(CDBBatch &batch)
Virtual method called internally by Commit that can be overridden to atomically commit more index sta...
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.
virtual bool AllowPrune() const =0
std::atomic< bool > m_synced
Whether the index is in sync with the main chain.
CThreadInterrupt m_interrupt
IndexSummary GetSummary() const
Get a summary of the index and its state.
virtual DB & GetDB() const =0
void ChainStateFlushed(const CBlockLocator &locator) override
Notifies listeners of the new active block chain on-disk.
std::thread m_thread_sync
bool Commit()
Write the current index state (eg.
virtual bool WriteBlock(const CBlock &block, const CBlockIndex *pindex)
Write update index entries for a newly connected block.
void ThreadSync()
Sync the index with the block index starting from the current best block.
Chainstate * m_chainstate
virtual bool Rewind(const CBlockIndex *current_tip, const CBlockIndex *new_tip)
Rewind index to an earlier chain tip during a chain reorg.
The block chain is a tree shaped structure starting with the genesis block at the root,...
CBlockIndex * pprev
pointer to the index of the predecessor of this block
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
BlockHash GetBlockHash() const
int nHeight
height of the entry in the chain. The genesis block has height 0
An in-memory indexed chain of blocks.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Batch of changes queued to be written to a CDBWrapper.
void Write(const K &key, const V &value)
leveldb::Options options
database options used
Chainstate stores and provides an API to update our local knowledge of the current best chain.
CChain m_chain
The current chain of blockheaders we consult and build on.
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
const CBlockIndex * FindForkInGlobalIndex(const CBlockLocator &locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the last common block of this chain and a locator.
std::string ToString() const
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
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.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
bool error(const char *fmt, const Args &...args)
void ReadDatabaseArgs(const ArgsManager &args, DBOptions &options)
void TraceThread(const char *thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
void StartShutdown()
Request shutdown of the application.
A BlockHash is a unqiue identifier for a block.
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
std::vector< BlockHash > vHave
User-controlled performance and debug options.
Application-specific storage settings.
int height_first
Height of earliest block that should be kept and not pruned.
#define AssertLockNotHeld(cs)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
bilingual_str _(const char *psz)
Translation function.
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
bool InitError(const bilingual_str &str)
Show error message.
constexpr auto AbortError
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)