Sunday 9 July 2017

Bitcoin core tutorial & code walk through (Part 3) - getblock

1) The bitcoin-cli command can be used to get blockhash and get block information. For testing purpose, the regtest network is used.

bitcoin-cli -regtest getblockhash 0
(it returns the block hash)
bitcoin-cli -regtest getblock 0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206
(it takes block hash as parameter)

2) In this analysis, the source code that handles getblockhash and getblock RPC will be walked through.


For getblockhash rpc
rpc/blockchain.cpp
define RegisterBlockchainRPCCommands(CRPCTable &t)

UniValue getblockhash(const JSONRPCRequest& request)

This function checks the block height, make sure it is not out of range. Then it calls CBlockIndex class GetBlockHash() function

chain.h

GetBlockHash() simply returns the pointer to hash block. 

For getblock rpc
rpc/blockchain.cpp
UniValue getblock(const JSONRPCRequest& request)
This function firstly check the verbosity. It checks mapBlockIndex is not out of range. The it calls ReadBlockFromDisk() and blockToJSON() to print out the block data in JSON format.

UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails)

It builds the JSON value pair using the CBlock and CBlockIndex.

validation.cpp

bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
This function builds a CAutoFile object which contains a FILE *. The OpenBlockFile() is used to return the FILE *. Then, the FILE * is copied to CBlock.

FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly)

It is a misc function that calls OpenDiskFile().

static FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)

It uses fsbridge::fopen() to build FILE *, and returns FILE *. The fsbridge is Bitcoin core namespace.

mapBlockIndex is defined in validation.cpp as

BlockMap mapBlockIndex;
and extern BlockMap mapBlockIndex; in validation.h.

typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;

It is unordered_map in C++ std namespace .


No comments:

Post a Comment