Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
15 changes: 9 additions & 6 deletions crates/database/src/states/block_hash_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ use primitives::{alloy_primitives::B256, BLOCK_HASH_HISTORY};
use std::boxed::Box;

const BLOCK_HASH_HISTORY_USIZE: usize = BLOCK_HASH_HISTORY as usize;

/// A fixed-size cache for the 256 most recent block hashes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlockHashCache {
/// A fixed-size array holding the block hashes.
/// Since we only store the most recent 256 block hashes, this array has a length of 256.
/// The reason we store block number alongside its hash is to handle the case where it wraps around, so we can verify the block number.
hashes: Box<[(u64, B256); BLOCK_HASH_HISTORY_USIZE]>,
/// The reason we store block number alongside its hash is to handle the case where it wraps around,
/// so we can verify the block number. Uses `Option<u64>` to distinguish between "not cached"
/// (`None`) and "cached with value" (`Some(block_number)`).
hashes: Box<[(Option<u64>, B256); BLOCK_HASH_HISTORY_USIZE]>,
}

impl Default for BlockHashCache {
Expand All @@ -22,23 +25,23 @@ impl BlockHashCache {
#[inline]
pub fn new() -> Self {
Self {
hashes: Box::new([(0, B256::ZERO); BLOCK_HASH_HISTORY_USIZE]),
hashes: Box::new([(None, B256::ZERO); BLOCK_HASH_HISTORY_USIZE]),
}
}

/// Inserts a block hash for the given block number.
#[inline]
pub const fn insert(&mut self, block_number: u64, block_hash: B256) {
let index = (block_number % BLOCK_HASH_HISTORY) as usize;
self.hashes[index] = (block_number, block_hash);
self.hashes[index] = (Some(block_number), block_hash);
}

/// Retrieves the block hash for the given block number, if it exists in the cache.
#[inline]
pub const fn get(&self, block_number: u64) -> Option<B256> {
pub fn get(&self, block_number: u64) -> Option<B256> {
let index = (block_number % BLOCK_HASH_HISTORY) as usize;
let (stored_block_number, stored_hash) = self.hashes[index];
if stored_block_number == block_number {
if Some(block_number) == stored_block_number {
Some(stored_hash)
} else {
None
Expand Down
28 changes: 25 additions & 3 deletions crates/database/src/states/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use database_interface::{
bal::{BalState, EvmDatabaseError},
Database, DatabaseCommit, DatabaseRef, EmptyDB,
};
use primitives::{hash_map, Address, FixedBytes, HashMap, StorageKey, StorageValue, B256};
use primitives::{hash_map, Address, HashMap, StorageKey, StorageValue, B256};
use state::{
bal::{alloy::AlloyBal, Bal},
Account, AccountInfo,
Expand Down Expand Up @@ -486,8 +486,8 @@ impl<DB: DatabaseRef> DatabaseRef for State<DB> {
}

fn block_hash_ref(&self, number: u64) -> Result<B256, Self::Error> {
if let Some(entry) = self.block_hashes.get(number) {
return Ok(FixedBytes(*entry));
if let Some(hash) = self.block_hashes.get(number) {
return Ok(hash);
}
// If not found, load it from database
self.database
Expand Down Expand Up @@ -529,6 +529,28 @@ mod tests {
assert_eq!(state.block_hashes.get(2), None);
assert_eq!(state.block_hashes.get(test_number), Some(block_test_hash));
}

/// Test that block 0 can be correctly fetched and cached.
/// This is a regression test for a bug where the cache was initialized with
/// `(0, B256::ZERO)` entries, causing block 0 lookups to incorrectly match
/// the default entry instead of fetching from the database.
#[test]
fn block_hash_cache_block_zero() {
let mut state = State::builder().build();

// Block 0 should not be in cache initially
assert_eq!(state.block_hashes.get(0), None);

// Fetch block 0 - this should go to database and cache the result
let block0_hash = state.block_hash(0u64).unwrap();

// EmptyDB returns keccak256("0") for block 0
let expected_hash = keccak256(U256::from(0).to_string().as_bytes());
assert_eq!(block0_hash, expected_hash);

// Block 0 should now be in cache with correct value
assert_eq!(state.block_hashes.get(0), Some(expected_hash));
}
/// Checks that if accounts is touched multiple times in the same block,
/// then the old values from the first change are preserved and not overwritten.
///
Expand Down
Loading