fix: better conversion error handling in block_hash_ref (#5870)

Co-authored-by: DaniPopes <57450786+DaniPopes@users.noreply.github.com>
Co-authored-by: Matthias Seitz <matthias.seitz@outlook.de>
This commit is contained in:
Thomas Coratger
2023-12-28 17:39:16 +01:00
committed by GitHub
parent b1b059fe9b
commit 365acf08dd
2 changed files with 19 additions and 6 deletions

View File

@@ -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;
@@ -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 {

View File

@@ -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())
}
}
@@ -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())
}
}