allow negative index to getblockhash

This commit is contained in:
Alfredo Garcia 2019-12-31 09:35:37 -03:00
parent 3ac6dd5f5d
commit fce6000f76
2 changed files with 12 additions and 2 deletions

View File

@ -101,10 +101,15 @@ class MerkleBlockTest(BitcoinTestFramework):
assert_equal(self.nodes[0].getblock("0")["height"], 0)
assert_raises(JSONRPCException, self.nodes[0].getblock, ["108"])
assert_equal(self.nodes[0].getblock("107")["height"], 107)
assert_equal(self.nodes[0].getblock("106")["height"], 106)
assert_equal(self.nodes[0].getblock("-1")["height"], 106)
assert_equal(self.nodes[0].getblock("-2")["height"], 105)
assert_equal(self.nodes[0].getblock("-20")["height"], 87)
assert_equal(self.nodes[0].getblock("-107")["height"], 0)
assert_raises(JSONRPCException, self.nodes[0].getblock, ["-108"])
# Test getblockhash negative heights
hash = self.nodes[0].getblockhash(106)
assert_equal(self.nodes[0].getblockhash(-1), hash)
if __name__ == '__main__':
MerkleBlockTest().main()

View File

@ -576,7 +576,7 @@ UniValue getblockhash(const UniValue& params, bool fHelp)
"getblockhash index\n"
"\nReturns hash of block in best-block-chain at index provided.\n"
"\nArguments:\n"
"1. index (numeric, required) The block index\n"
"1. index (numeric, required) The block index. If negative then the index will be relative to the head.\n"
"\nResult:\n"
"\"hash\" (string) The block hash\n"
"\nExamples:\n"
@ -587,6 +587,11 @@ UniValue getblockhash(const UniValue& params, bool fHelp)
LOCK(cs_main);
int nHeight = params[0].get_int();
if(nHeight < 0) {
nHeight += chainActive.Height();
}
if (nHeight < 0 || nHeight > chainActive.Height())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");