diff --git a/qa/rpc-tests/merkle_blocks.py b/qa/rpc-tests/merkle_blocks.py index 53acfe6ed..bf333ab1f 100755 --- a/qa/rpc-tests/merkle_blocks.py +++ b/qa/rpc-tests/merkle_blocks.py @@ -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() diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index 387f58153..7bcd66203 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -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");