admin07@admin-MS:~/job/github_source/bitcoin$ bitcoin-cli -regtest getblockhash 0
0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206
通过变量chainActive来获得相应高度的区块hash
src/rpc/blockchain.cpp
static UniValue getblockhash(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"getblockhash height\n"
"\nReturns hash of block in best-block-chain at height provided.\n"
"\nArguments:\n"
"1. height (numeric, required) The height index\n"
"\nResult:\n"
"\"hash\" (string) The block hash\n"
"\nExamples:\n"
+ HelpExampleCli("getblockhash", "1000")
+ HelpExampleRpc("getblockhash", "1000")
);
LOCK(cs_main);
int nHeight = request.params[0].get_int(); //获得参数:高度
if (nHeight < 0 || nHeight > chainActive.Height()) //小于零/大于最大高度
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
//访问CChain的operator[]
CBlockIndex* pblockindex = chainActive[nHeight]; //CChain:chainActive
return pblockindex->GetBlockHash().GetHex();
}
class CChain {
private:
std::vector<CBlockIndex*> vChain; //vector是一个能够存放任意类型的动态数组,能够增加和压缩数据
//特定高度的CBlockIndex
/** Returns the index entry at a particular height in this chain, or nullptr if no such height exists. */
CBlockIndex *operator[](int nHeight) const {//覆写operator[]
if (nHeight < 0 || nHeight >= (int)vChain.size())
return nullptr;
return vChain[nHeight];
}
}
网友评论