From 203bf3345ce4b79a0d9e8b9eb33d642262e1a095 Mon Sep 17 00:00:00 2001
From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com>
Date: Mon, 29 Apr 2024 18:23:15 +0800
Subject: [PATCH] perf(state): Cache the block hash (backport #2924) (#2931)
Closes #2923
Caches the block hash to ensure we only compute it once in consensus
execution.
---
#### PR checklist
- [x] Tests written/updated - not sure what test I should write, any
suggestions?
- [x] Changelog entry added in `.changelog` (we use
[unclog](https://github.com/informalsystems/unclog) to manage our
changelog)
- [ ] Updated relevant documentation (`docs/` or `spec/`) and code
comments
- [x] Title follows the [Conventional
Commits](https://www.conventionalcommits.org/en/v1.0.0/) spec
This is an automatic backport of pull request #2924 done by
[Mergify](https://mergify.com).
Co-authored-by: Dev Ojha
---
.../2924-consensus-cache-block-hash.md | 2 ++
types/block.go | 16 +++++++++++-----
2 files changed, 13 insertions(+), 5 deletions(-)
create mode 100644 .changelog/unreleased/improvements/2924-consensus-cache-block-hash.md
diff --git a/.changelog/unreleased/improvements/2924-consensus-cache-block-hash.md b/.changelog/unreleased/improvements/2924-consensus-cache-block-hash.md
new file mode 100644
index 00000000000..4f9e5638c45
--- /dev/null
+++ b/.changelog/unreleased/improvements/2924-consensus-cache-block-hash.md
@@ -0,0 +1,2 @@
+- `[state/execution]` Cache the block hash computation inside of the Block Type, so we only compute it once.
+ ([\#2924](https://github.com/cometbft/cometbft/pull/2924))
\ No newline at end of file
diff --git a/types/block.go b/types/block.go
index 82d0fa4d989..4a504c64899 100644
--- a/types/block.go
+++ b/types/block.go
@@ -43,10 +43,11 @@ const (
type Block struct {
mtx cmtsync.Mutex
- Header `json:"header"`
- Data `json:"data"`
- Evidence EvidenceData `json:"evidence"`
- LastCommit *Commit `json:"last_commit"`
+ verifiedHash cmtbytes.HexBytes // Verified block hash (not included in the struct hash)
+ Header `json:"header"`
+ Data `json:"data"`
+ Evidence EvidenceData `json:"evidence"`
+ LastCommit *Commit `json:"last_commit"`
}
// ValidateBasic performs basic validation that doesn't involve state data.
@@ -130,8 +131,13 @@ func (b *Block) Hash() cmtbytes.HexBytes {
if b.LastCommit == nil {
return nil
}
+ if b.verifiedHash != nil {
+ return b.verifiedHash
+ }
b.fillHeader()
- return b.Header.Hash()
+ hash := b.Header.Hash()
+ b.verifiedHash = hash
+ return hash
}
// MakePartSet returns a PartSet containing parts of a serialized block.