From 0716382c20a6f9297f5bceb88120905fb4857c02 Mon Sep 17 00:00:00 2001 From: Sebastian Falbesoner Date: Thu, 12 Jun 2025 12:51:20 +0200 Subject: [PATCH] test: remove header hash caching in CBlockHeader class Rather than block hashes (represented by the fields `.sha256` and `.hash`) being stateful, simply compute them on-the-fly. This ensures that the correct values are always returned and takes the burden of rehashing from test writers, making the code shorter overall. In a first step, the fields are kept at the same name with @property functions as drop-in replacements, for a minimal diff. In later commits, the names are changed to be more descriptive and indicating the return type of the block hash. --- test/functional/test_framework/messages.py | 31 +++++++++++----------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/test/functional/test_framework/messages.py b/test/functional/test_framework/messages.py index ef2e4eedae..876ba7126d 100755 --- a/test/functional/test_framework/messages.py +++ b/test/functional/test_framework/messages.py @@ -704,8 +704,8 @@ class CTransaction: class CBlockHeader: - __slots__ = ("hash", "hashMerkleRoot", "hashPrevBlock", "nBits", "nNonce", - "nTime", "nVersion", "sha256") + __slots__ = ("hashMerkleRoot", "hashPrevBlock", "nBits", "nNonce", + "nTime", "nVersion") def __init__(self, header=None): if header is None: @@ -717,8 +717,6 @@ class CBlockHeader: self.nTime = header.nTime self.nBits = header.nBits self.nNonce = header.nNonce - self.sha256 = header.sha256 - self.hash = header.hash self.calc_sha256() def set_null(self): @@ -728,8 +726,6 @@ class CBlockHeader: self.nTime = 0 self.nBits = 0 self.nNonce = 0 - self.sha256 = None - self.hash = None def deserialize(self, f): self.nVersion = int.from_bytes(f.read(4), "little", signed=True) @@ -738,8 +734,6 @@ class CBlockHeader: self.nTime = int.from_bytes(f.read(4), "little") self.nBits = int.from_bytes(f.read(4), "little") self.nNonce = int.from_bytes(f.read(4), "little") - self.sha256 = None - self.hash = None def serialize(self): return self._serialize_header() @@ -754,15 +748,22 @@ class CBlockHeader: r += self.nNonce.to_bytes(4, "little") return r - def calc_sha256(self): - if self.sha256 is None: - r = self._serialize_header() - self.sha256 = uint256_from_str(hash256(r)) - self.hash = hash256(r)[::-1].hex() + @property + def hash(self): + """Return block header hash as hex string.""" + return hash256(self._serialize_header())[::-1].hex() + @property + def sha256(self): + """Return block header hash as integer.""" + return uint256_from_str(hash256(self._serialize_header())) + + # TODO: get rid of this method, remove call-sites + def calc_sha256(self): + pass + + # TODO: get rid of this method, replace call-sites by .sha256 access (if return value is used) def rehash(self): - self.sha256 = None - self.calc_sha256() return self.sha256 def __repr__(self):