Skip to content

Commit 1ec6bbe

Browse files
committed
[validation] Cache merkle root and witness commitment checks
Slight performance improvement by avoiding duplicate work.
1 parent 5bf4f5b commit 1ec6bbe

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

src/primitives/block.h

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,10 @@ class CBlock : public CBlockHeader
7171
// network and disk
7272
std::vector<CTransactionRef> vtx;
7373

74-
// memory only
75-
mutable bool fChecked;
74+
// Memory-only flags for caching expensive checks
75+
mutable bool fChecked; // CheckBlock()
76+
mutable bool m_checked_witness_commitment{false}; // CheckWitnessCommitment()
77+
mutable bool m_checked_merkle_root{false}; // CheckMerkleRoot()
7678

7779
CBlock()
7880
{
@@ -95,6 +97,8 @@ class CBlock : public CBlockHeader
9597
CBlockHeader::SetNull();
9698
vtx.clear();
9799
fChecked = false;
100+
m_checked_witness_commitment = false;
101+
m_checked_merkle_root = false;
98102
}
99103

100104
CBlockHeader GetBlockHeader() const

src/validation.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3641,6 +3641,8 @@ static bool CheckBlockHeader(const CBlockHeader& block, BlockValidationState& st
36413641

36423642
static bool CheckMerkleRoot(const CBlock& block, BlockValidationState& state)
36433643
{
3644+
if (block.m_checked_merkle_root) return true;
3645+
36443646
bool mutated;
36453647
uint256 merkle_root = BlockMerkleRoot(block, &mutated);
36463648
if (block.hashMerkleRoot != merkle_root) {
@@ -3660,6 +3662,7 @@ static bool CheckMerkleRoot(const CBlock& block, BlockValidationState& state)
36603662
/*debug_message=*/"duplicate transaction");
36613663
}
36623664

3665+
block.m_checked_merkle_root = true;
36633666
return true;
36643667
}
36653668

@@ -3672,6 +3675,8 @@ static bool CheckMerkleRoot(const CBlock& block, BlockValidationState& state)
36723675
static bool CheckWitnessMalleation(const CBlock& block, bool expect_witness_commitment, BlockValidationState& state)
36733676
{
36743677
if (expect_witness_commitment) {
3678+
if (block.m_checked_witness_commitment) return true;
3679+
36753680
int commitpos = GetWitnessCommitmentIndex(block);
36763681
if (commitpos != NO_WITNESS_COMMITMENT) {
36773682
assert(!block.vtx.empty() && !block.vtx[0]->vin.empty());
@@ -3697,6 +3702,7 @@ static bool CheckWitnessMalleation(const CBlock& block, bool expect_witness_comm
36973702
/*debug_message=*/strprintf("%s : witness merkle commitment mismatch", __func__));
36983703
}
36993704

3705+
block.m_checked_witness_commitment = true;
37003706
return true;
37013707
}
37023708
}

0 commit comments

Comments
 (0)