[validation] Cache merkle root and witness commitment checks

Slight performance improvement by avoiding duplicate work.

Github-Pull: #29412
Rebased-From: 1ec6bbeb8d
This commit is contained in:
dergoegge 2024-02-06 10:07:18 +00:00 committed by glozow
parent 0c5c5962cb
commit 8141498f3a
2 changed files with 12 additions and 2 deletions

View file

@ -71,8 +71,10 @@ public:
// network and disk // network and disk
std::vector<CTransactionRef> vtx; std::vector<CTransactionRef> vtx;
// memory only // Memory-only flags for caching expensive checks
mutable bool fChecked; mutable bool fChecked; // CheckBlock()
mutable bool m_checked_witness_commitment{false}; // CheckWitnessCommitment()
mutable bool m_checked_merkle_root{false}; // CheckMerkleRoot()
CBlock() CBlock()
{ {
@ -95,6 +97,8 @@ public:
CBlockHeader::SetNull(); CBlockHeader::SetNull();
vtx.clear(); vtx.clear();
fChecked = false; fChecked = false;
m_checked_witness_commitment = false;
m_checked_merkle_root = false;
} }
CBlockHeader GetBlockHeader() const CBlockHeader GetBlockHeader() const

View file

@ -3623,6 +3623,8 @@ static bool CheckBlockHeader(const CBlockHeader& block, BlockValidationState& st
static bool CheckMerkleRoot(const CBlock& block, BlockValidationState& state) static bool CheckMerkleRoot(const CBlock& block, BlockValidationState& state)
{ {
if (block.m_checked_merkle_root) return true;
bool mutated; bool mutated;
uint256 merkle_root = BlockMerkleRoot(block, &mutated); uint256 merkle_root = BlockMerkleRoot(block, &mutated);
if (block.hashMerkleRoot != merkle_root) { if (block.hashMerkleRoot != merkle_root) {
@ -3642,6 +3644,7 @@ static bool CheckMerkleRoot(const CBlock& block, BlockValidationState& state)
/*debug_message=*/"duplicate transaction"); /*debug_message=*/"duplicate transaction");
} }
block.m_checked_merkle_root = true;
return true; return true;
} }
@ -3654,6 +3657,8 @@ static bool CheckMerkleRoot(const CBlock& block, BlockValidationState& state)
static bool CheckWitnessMalleation(const CBlock& block, bool expect_witness_commitment, BlockValidationState& state) static bool CheckWitnessMalleation(const CBlock& block, bool expect_witness_commitment, BlockValidationState& state)
{ {
if (expect_witness_commitment) { if (expect_witness_commitment) {
if (block.m_checked_witness_commitment) return true;
int commitpos = GetWitnessCommitmentIndex(block); int commitpos = GetWitnessCommitmentIndex(block);
if (commitpos != NO_WITNESS_COMMITMENT) { if (commitpos != NO_WITNESS_COMMITMENT) {
assert(!block.vtx.empty() && !block.vtx[0]->vin.empty()); assert(!block.vtx.empty() && !block.vtx[0]->vin.empty());
@ -3679,6 +3684,7 @@ static bool CheckWitnessMalleation(const CBlock& block, bool expect_witness_comm
/*debug_message=*/strprintf("%s : witness merkle commitment mismatch", __func__)); /*debug_message=*/strprintf("%s : witness merkle commitment mismatch", __func__));
} }
block.m_checked_witness_commitment = true;
return true; return true;
} }
} }