## GetBlockChecked always returning genesis block?

0

currently I'm exploring Bitcoin source code and I tried to add custom function getblockvalue inside of blockchain.cpp.
Purpose of function is to return sum of all transaction outputs inside of a block based on given height as an argument.

static UniValue getblockvalue(const JSONRPCRequest& request)
{
int blockHeight = request.params[0].get_int();
if (blockHeight < 0 || blockHeight > ::ChainActive().Height())
{
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
}

CBlockIndex* pBlockIndex = ::ChainActive()[blockHeight];
if(pBlockIndex == nullptr)
{
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block index is NULL");

}
const CBlock block = GetBlockChecked(pBlockIndex);
UniValue resultObject(UniValue::VOBJ);
double blockValue = 0;
int numberOfTransactions = 0;

for(const auto &transaction : block.vtx)
{
for (unsigned int i = 0; i < transaction->vout.size(); ++i)
{
blockValue+= transaction->vout[i].nValue;
}
++numberOfTransactions;
}

resultObject.pushKV("blockHeight",          (int)blockHeight);
resultObject.pushKV("numberOfTransactions", (int)numberOfTransactions);
resultObject.pushKV("blockValue",           ValueFromAmount(blockValue));

return resultObject;
}


I did all necessary changes: I added argument to vRPCConvertParams[] and extended CRPCCommand commands[].
So, I tried calling bitcoin-cli -testnet getblockvalue 25; result is:

{
"blockHeight" : 25,
"numberOfTransactions" : 1,
"blockValue" : 50.00000000
}


The result is the same for every given block height. It always gives me information about genesis block. Can you help me what did I do wrong here?

1What makes you think it is always returning the genesis block? Did you try a recent block? – Andrew Chow – 2020-07-11T15:01:23.637

I tried a lot of random numbers. I'm not sure it does, but its odd to me that every block has the same result of a function? To be honest I tried number "999999" as block height and it gave me result: numberOfTransactions 2, and blockValue: 3.1264. And i thought that is a part of an error, because seeing only 2 transactions inside of a block, is to small... is it? – ddavi031 – 2020-07-11T15:11:25.253

@AndrewChow you were right, code is ok. Thank you a lot. Since you are moderator, should i just delete my question since has no point? – ddavi031 – 2020-07-11T15:30:35.533

Misconceptions should be addressed in the answer to a question, and self-answers are welcome. You could therefore submit an answer to explain what you found out, if you think it would be interesting to future readers. – Murch – 2020-07-12T07:02:03.717