Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions src/primitives/block.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@

uint256 CBlockHeader::GetHash() const
{
std::vector<unsigned char> vch(80);
CVectorWriter ss(SER_GETHASH, PROTOCOL_VERSION, vch, 0);
ss << *this;
return HashX11((const char *)vch.data(), (const char *)vch.data() + vch.size());
if (cached_hash.IsNull()) {
std::vector<unsigned char> vch(80);
CVectorWriter ss(SER_GETHASH, PROTOCOL_VERSION, vch, 0);
ss << *this;
cached_hash = HashX11((const char *)vch.data(), (const char *)vch.data() + vch.size());
}
return cached_hash;
}

std::string CBlock::ToString() const
Expand Down
10 changes: 9 additions & 1 deletion src/primitives/block.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,18 @@ class CBlockHeader
uint32_t nBits;
uint32_t nNonce;

// Memory only cached hash as x11 is more expensive than sha256
mutable uint256 cached_hash;

CBlockHeader()
{
SetNull();
}

SERIALIZE_METHODS(CBlockHeader, obj) { READWRITE(obj.nVersion, obj.hashPrevBlock, obj.hashMerkleRoot, obj.nTime, obj.nBits, obj.nNonce); }
SERIALIZE_METHODS(CBlockHeader, obj) {
READWRITE(obj.nVersion, obj.hashPrevBlock, obj.hashMerkleRoot, obj.nTime, obj.nBits, obj.nNonce);
obj.cached_hash.SetNull();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it may reset only in case of read event

}

void SetNull()
{
Expand All @@ -46,6 +52,7 @@ class CBlockHeader
nTime = 0;
nBits = 0;
nNonce = 0;
cached_hash.SetNull();
}

bool IsNull() const
Expand Down Expand Up @@ -225,6 +232,7 @@ class CBlock : public CBlockHeader
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
block.cached_hash = cached_hash;
return block;
}

Expand Down
2 changes: 2 additions & 0 deletions src/validation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4973,6 +4973,8 @@ void CChainState::LoadExternalBlockFile(
blkdat.SetPos(nBlockPos);
std::shared_ptr<CBlock> pblock{std::make_shared<CBlock>()};
blkdat >> *pblock;
// We calculated the hash of the header earlier, no need to recalculate it.
pblock->cached_hash = hash;
nRewind = blkdat.GetPos();

BlockValidationState state;
Expand Down
Loading