Imagine I executed ReadBlockFromDisk and now I have valid instance of CBlock.
How do I read height of this block?
CBlock block = ...;
CBlockIndex index(block);
assert (index.nHeight != 0); // fails, nHeight is default initialized
Bitcoin Stack Exchange is a question and answer site for Bitcoin crypto-currency enthusiasts. It only takes a minute to sign up.
Sign up to join this communityImagine I executed ReadBlockFromDisk and now I have valid instance of CBlock.
How do I read height of this block?
CBlock block = ...;
CBlockIndex index(block);
assert (index.nHeight != 0); // fails, nHeight is default initialized
It looks like this function from validation.h
does the job:
CBlockIndex* LookupBlockIndex(const uint256& hash)
You'd need to get a full node started up by calling AppInitMain
in init.cpp
in order to get the index subsystem running.
Otherwise it can't query the index database to get the block height.
The node subsystem must be warmed up and running in order to run queries linked from C++ directly. You'd also need to synchronize the calls and respect locks - not easy.
Running AppInitMain is basically the same as running bitcoind
, so you're probably better off calling into the RPC interface from C++ and passing the getblock <hash> 1
command to it. The process the resulting JSON.
getblock <hash> 1
returns something like this
{
"hash": "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048",
"confirmations": 600340,
"strippedsize": 215,
"size": 215,
"weight": 860,
"height": 1,
"version": 1,
"versionHex": "00000001",
"merkleroot": "0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098",
"tx": [
"0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098"
],
"time": 1231469665,
"mediantime": 1231469665,
"nonce": 2573394689,
"bits": "1d00ffff",
"difficulty": 1,
"chainwork": "0000000000000000000000000000000000000000000000000000000200020002",
"nTx": 1,
"previousblockhash": "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",
"nextblockhash": "000000006a625f06636b8bb6ac7b960a8d03705d1ace08b1a19da3fdcc99ddbd"
}
Which includes the height and other data.