rpc: fix getblock(header) returns target for tip

A target field was added to the getblock and getblockheader RPC calls in bitcoin#31583, but it mistakingly always used the tip value.

Because regtest does not have difficulty adjustment, a test is added for mainnet instead.

Github-Pull: #33446
Rebased-From: bf7996cbc3
This commit is contained in:
Sjors Provoost
2025-09-20 21:33:13 +02:00
committed by fanquake
parent 4ec30d53ec
commit 1e348bc55a
2 changed files with 13 additions and 1 deletions

View File

@@ -166,7 +166,7 @@ UniValue blockheaderToJSON(const CBlockIndex& tip, const CBlockIndex& blockindex
result.pushKV("mediantime", blockindex.GetMedianTimePast()); result.pushKV("mediantime", blockindex.GetMedianTimePast());
result.pushKV("nonce", blockindex.nNonce); result.pushKV("nonce", blockindex.nNonce);
result.pushKV("bits", strprintf("%08x", blockindex.nBits)); result.pushKV("bits", strprintf("%08x", blockindex.nBits));
result.pushKV("target", GetTarget(tip, pow_limit).GetHex()); result.pushKV("target", GetTarget(blockindex, pow_limit).GetHex());
result.pushKV("difficulty", GetDifficulty(blockindex)); result.pushKV("difficulty", GetDifficulty(blockindex));
result.pushKV("chainwork", blockindex.nChainWork.GetHex()); result.pushKV("chainwork", blockindex.nChainWork.GetHex());
result.pushKV("nTx", blockindex.nTx); result.pushKV("nTx", blockindex.nTx);

View File

@@ -109,5 +109,17 @@ class MiningMainnetTest(BitcoinTestFramework):
height = 2016 height = 2016
prev_hash = self.mine(height, prev_hash, blocks, node) prev_hash = self.mine(height, prev_hash, blocks, node)
assert_equal(node.getblockcount(), height) assert_equal(node.getblockcount(), height)
mining_info = node.getmininginfo()
assert_equal(mining_info['difficulty'], 4)
self.log.info("getblock RPC should show historical target")
block_info = node.getblock(node.getblockhash(1))
assert_equal(block_info['difficulty'], 1)
assert_equal(block_info['bits'], nbits_str(DIFF_1_N_BITS))
assert_equal(block_info['target'], target_str(DIFF_1_TARGET))
if __name__ == '__main__': if __name__ == '__main__':
MiningMainnetTest(__file__).main() MiningMainnetTest(__file__).main()