1

Bitcoin Core stores blocks in files in local disk. And it uses LevelDb to form an index on top of block storage to make it faster to retrieve a block (basically a simple key-value pair db). See this for more details.

Also Bitcoin Core stores all the blocks that are not that are not in the main chain in case a fork happens and one of them becomes part of the main chain.

How does Bitcoin Core scan the local storage to find the chaintip of the main chain which have most number of blocks? Does is keep a list of heads in memory? It would be extremely nice if you guys can redirect me to the location in the Bitcoin Core source code that handles that process.

bumped to the homepage by Community yesterday

This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.

0

You're looking for validation.h and its corresponding .cpp source file.

You should start at CChainState::ActivateBestChain. This subroutine calls CChainState::ActivateBestChainStep which runs the logic you're interested in - stepping one by one of the blocks, cleaning up and reorg'ing from lowest to highest PoW.

First, ActivateBestChainStep walks the chain in a while loop: while (m_chain.Tip() && m_chain.Tip() != pindexFork) cleaning up blocks which are not in the best chain using DisconnectTip(state, chainparams, &disconnectpool). This partly answers your question - all the blocks which aren't in the best chain are weeded out here.

It then walks through the current CBlockIndex organizing blocks using the next while loop: while (fContinue && nHeight != pindexMostWork->nHeight). pindexMostWork is a CBlockIndex that contains the blocks with most work. Inside there is a loop which selects the blocks it should connect to the best chain: while (pindexIter && pindexIter->nHeight != nHeight). It pushes the candidate blocks onto a locally allocated vector std::vector<CBlockIndex*> vpindexToConnect;.

Next it iterates this new vector in reverse, pushing the blocks with lowest work first: for (CBlockIndex *pindexConnect : reverse_iterate(vpindexToConnect)) connecting each to the tip. The last connected block will be the block with the highest work index. This builds a chain sorted from lowest to highest work.

Several places in the code call ActivateBestChain, among them:

  • invalidateblock and reconsiderblock in rpc/blockchain.cpp
  • ThreadImport in init.cpp
  • ProcessGetBlockData and Processmessage in net_processing.cpp
  • Several subroutines in validation.cpp itself

You can use any of the above to trace how and when a new best chain is activated. I think the most interesting ones are in net_processing.cpp as those are the ones triggered by messages received from the network.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.