Skip to content

Commit

Permalink
fix: better conversion error handling in block_hash_ref (#5870)
Browse files Browse the repository at this point in the history
Co-authored-by: DaniPopes <57450786+DaniPopes@users.noreply.github.com>
Co-authored-by: Matthias Seitz <matthias.seitz@outlook.de>
  • Loading branch information
3 people authored Dec 28, 2023
1 parent b1b059f commit 365acf0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
5 changes: 4 additions & 1 deletion crates/interfaces/src/provider.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use reth_primitives::{
Address, BlockHash, BlockHashOrNumber, BlockNumber, GotExpected, SnapshotSegment,
TxHashOrNumber, TxNumber, B256,
TxHashOrNumber, TxNumber, B256, U256,
};
use std::path::PathBuf;
use thiserror::Error;
Expand Down Expand Up @@ -122,6 +122,9 @@ pub enum ProviderError {
/// Snapshot file is not found for requested transaction.
#[error("not able to find {0} snapshot file for transaction id {1}")]
MissingSnapshotTx(SnapshotSegment, TxNumber),
/// Error encountered when the block number conversion from U256 to u64 causes an overflow.
#[error("failed to convert block number U256 to u64: {0}")]
BlockNumberOverflow(U256),
}

impl From<reth_nippy_jar::NippyJarError> for ProviderError {
Expand Down
20 changes: 15 additions & 5 deletions crates/revm/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,13 @@ impl<DB: StateProvider> Database for StateProviderDatabase<DB> {
/// Returns `Ok` with the block hash if found, or the default hash otherwise.
/// Note: It safely casts the `number` to `u64`.
fn block_hash(&mut self, number: U256) -> Result<B256, Self::Error> {
// The `number` represents the block number, so it is safe to cast it to u64.
Ok(self.0.block_hash(number.try_into().unwrap())?.unwrap_or_default())
// Attempt to convert U256 to u64
let block_number = match number.try_into() {
Ok(value) => value,
Err(_) => return Err(Self::Error::BlockNumberOverflow(number)),
};

Ok(self.0.block_hash(block_number)?.unwrap_or_default())
}
}

Expand Down Expand Up @@ -112,9 +117,14 @@ impl<DB: StateProvider> DatabaseRef for StateProviderDatabase<DB> {
/// Retrieves the block hash for a given block number.
///
/// Returns `Ok` with the block hash if found, or the default hash otherwise.
/// Note: This operation may potentially be unsafe due to the unwrap operation.
fn block_hash_ref(&self, number: U256) -> Result<B256, Self::Error> {
// Note: this unwrap is potentially unsafe
Ok(self.0.block_hash(number.try_into().unwrap())?.unwrap_or_default())
// Attempt to convert U256 to u64
let block_number = match number.try_into() {
Ok(value) => value,
Err(_) => return Err(Self::Error::BlockNumberOverflow(number)),
};

// Get the block hash or default hash
Ok(self.0.block_hash(block_number)?.unwrap_or_default())
}
}

0 comments on commit 365acf0

Please sign in to comment.