From f7606bf8256f666688cfd249029b0ce1b590b23f Mon Sep 17 00:00:00 2001 From: pellekrab <78560773+PelleKrab@users.noreply.github.com> Date: Thu, 12 Dec 2024 14:27:16 -0700 Subject: [PATCH] implemented thiserror --- crates/blockchain-tree-api/src/error.rs | 77 ++------- crates/optimism/chainspec/Cargo.toml | 1 + crates/optimism/chainspec/src/lib.rs | 15 +- crates/optimism/evm/Cargo.toml | 1 + crates/optimism/evm/src/error.rs | 20 ++- crates/primitives-traits/Cargo.toml | 1 + crates/primitives-traits/src/error.rs | 33 +--- .../src/transaction/error.rs | 42 +++-- crates/rpc/rpc-eth-types/src/error/mod.rs | 4 +- crates/storage/errors/Cargo.toml | 1 + crates/storage/errors/src/db.rs | 57 +++---- crates/storage/errors/src/lockfile.rs | 10 +- crates/storage/errors/src/provider.rs | 151 ++++++++++-------- 13 files changed, 159 insertions(+), 254 deletions(-) diff --git a/crates/blockchain-tree-api/src/error.rs b/crates/blockchain-tree-api/src/error.rs index 92866b4d4dad..05e714517eab 100644 --- a/crates/blockchain-tree-api/src/error.rs +++ b/crates/blockchain-tree-api/src/error.rs @@ -7,7 +7,7 @@ use reth_execution_errors::{ BlockExecutionError, BlockValidationError, InternalBlockExecutionError, }; use reth_primitives::{SealedBlock, SealedBlockFor}; -use reth_primitives_traits::{Block, BlockBody}; +use reth_primitives_traits::Block; pub use reth_storage_errors::provider::ProviderError; /// Various error cases that can occur when a block violates tree assumptions. @@ -166,40 +166,15 @@ impl std::fmt::Debug for InsertBlockError { } } -struct InsertBlockErrorData { - block: SealedBlock, - kind: InsertBlockErrorKind, -} - -impl std::fmt::Display for InsertBlockErrorData { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "Failed to insert block (hash={}, number={}, parent_hash={}): {}", +#[derive(thiserror::Error, Debug)] +#[error("Failed to insert block (hash={}, number={}, parent_hash={}): {}", self.block.hash(), self.block.number, self.block.parent_hash, - self.kind - ) - } -} - -impl std::fmt::Debug for InsertBlockErrorData { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("InsertBlockError") - .field("error", &self.kind) - .field("hash", &self.block.hash()) - .field("number", &self.block.number) - .field("parent_hash", &self.block.parent_hash) - .field("num_txs", &self.block.body.transactions.len()) - .finish_non_exhaustive() - } -} - -impl core::error::Error for InsertBlockErrorData { - fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { - Some(&self.kind) - } + self.kind)] +struct InsertBlockErrorData { + block: SealedBlock, + kind: InsertBlockErrorKind, } impl InsertBlockErrorData { @@ -212,42 +187,18 @@ impl InsertBlockErrorData { } } +#[derive(thiserror::Error, Debug)] +#[error("Failed to insert block (hash={}, number={}, parent_hash={}): {}", + .block.hash(), + .block.number(), + .block.parent_hash(), + .kind)] struct InsertBlockErrorDataTwo { block: SealedBlockFor, + #[source] kind: InsertBlockErrorKindTwo, } -impl std::fmt::Display for InsertBlockErrorDataTwo { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "Failed to insert block (hash={}, number={}, parent_hash={}): {}", - self.block.hash(), - self.block.number(), - self.block.parent_hash(), - self.kind - ) - } -} - -impl std::fmt::Debug for InsertBlockErrorDataTwo { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("InsertBlockError") - .field("error", &self.kind) - .field("hash", &self.block.hash()) - .field("number", &self.block.number()) - .field("parent_hash", &self.block.parent_hash()) - .field("num_txs", &self.block.body.transactions().len()) - .finish_non_exhaustive() - } -} - -impl core::error::Error for InsertBlockErrorDataTwo { - fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { - Some(&self.kind) - } -} - impl InsertBlockErrorDataTwo { const fn new(block: SealedBlockFor, kind: InsertBlockErrorKindTwo) -> Self { Self { block, kind } diff --git a/crates/optimism/chainspec/Cargo.toml b/crates/optimism/chainspec/Cargo.toml index 5ccf26607094..8d6f6e0edac9 100644 --- a/crates/optimism/chainspec/Cargo.toml +++ b/crates/optimism/chainspec/Cargo.toml @@ -35,6 +35,7 @@ op-alloy-rpc-types.workspace = true serde_json.workspace = true # misc +thiserror.workspace = true derive_more.workspace = true once_cell.workspace = true diff --git a/crates/optimism/chainspec/src/lib.rs b/crates/optimism/chainspec/src/lib.rs index 907599fe2a29..d211540cc0f3 100644 --- a/crates/optimism/chainspec/src/lib.rs +++ b/crates/optimism/chainspec/src/lib.rs @@ -244,27 +244,20 @@ impl OpChainSpec { } } -#[derive(Clone, Debug, Display, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] /// Error type for decoding Holocene 1559 parameters pub enum DecodeError { - #[display("Insufficient data to decode")] + #[error("Insufficient data to decode")] /// Insufficient data to decode InsufficientData, - #[display("Invalid denominator parameter")] + #[error("Invalid denominator parameter")] /// Invalid denominator parameter InvalidDenominator, - #[display("Invalid elasticity parameter")] + #[error("Invalid elasticity parameter")] /// Invalid elasticity parameter InvalidElasticity, } -impl core::error::Error for DecodeError { - fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { - // None of the errors have sub-errors - None - } -} - /// Extracts the Holcene 1599 parameters from the encoded form: /// pub fn decode_holocene_1559_params(extra_data: &[u8]) -> Result<(u32, u32), DecodeError> { diff --git a/crates/optimism/evm/Cargo.toml b/crates/optimism/evm/Cargo.toml index 7afb3b50e676..f8e2eec0cdcf 100644 --- a/crates/optimism/evm/Cargo.toml +++ b/crates/optimism/evm/Cargo.toml @@ -43,6 +43,7 @@ revm-primitives.workspace = true # misc derive_more.workspace = true tracing.workspace = true +thiserror.workspace = true [dev-dependencies] reth-evm = { workspace = true, features = ["test-utils"] } diff --git a/crates/optimism/evm/src/error.rs b/crates/optimism/evm/src/error.rs index db042950674a..42c4bd30cfc4 100644 --- a/crates/optimism/evm/src/error.rs +++ b/crates/optimism/evm/src/error.rs @@ -4,29 +4,27 @@ use alloc::string::String; use reth_evm::execute::BlockExecutionError; /// Optimism Block Executor Errors -#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)] +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum OpBlockExecutionError { /// Error when trying to parse L1 block info - #[display("could not get L1 block info from L2 block: {message}")] + #[error("could not get L1 block info from L2 block: {message}")] L1BlockInfoError { /// The inner error message message: String, }, /// Thrown when force deploy of create2deployer code fails. - #[display("failed to force create2deployer account code")] + #[error("failed to force create2deployer account code")] ForceCreate2DeployerFail, /// Thrown when a blob transaction is included in a sequencer's block. - #[display("blob transaction included in sequencer block")] + #[error("blob transaction included in sequencer block")] BlobTransactionRejected, /// Thrown when a database account could not be loaded. - #[display("failed to load account {_0}")] + #[error("failed to load account {_0}")] AccountLoadFailed(alloy_primitives::Address), } -impl core::error::Error for OpBlockExecutionError {} - -impl From for BlockExecutionError { - fn from(err: OpBlockExecutionError) -> Self { - Self::other(err) - } +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum BlockExecutionError { + #[error("other error: {0}")] + Other(#[from] OpBlockExecutionError), } diff --git a/crates/primitives-traits/Cargo.toml b/crates/primitives-traits/Cargo.toml index 459fdbde1a70..a45e6a7a8a0a 100644 --- a/crates/primitives-traits/Cargo.toml +++ b/crates/primitives-traits/Cargo.toml @@ -32,6 +32,7 @@ bytes.workspace = true derive_more.workspace = true serde_with = { workspace = true, optional = true } auto_impl.workspace = true +thiserror.workspace = true # required by reth-codecs modular-bitfield = { workspace = true, optional = true } diff --git a/crates/primitives-traits/src/error.rs b/crates/primitives-traits/src/error.rs index 97b33bd618ae..0e67ec460128 100644 --- a/crates/primitives-traits/src/error.rs +++ b/crates/primitives-traits/src/error.rs @@ -1,11 +1,9 @@ use alloc::boxed::Box; -use core::{ - fmt, - ops::{Deref, DerefMut}, -}; +use core::ops::{Deref, DerefMut}; /// A pair of values, one of which is expected and one of which is actual. -#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, thiserror::Error)] +#[error("got {got}, expected {expected}")] pub struct GotExpected { /// The actual value. pub got: T, @@ -13,14 +11,6 @@ pub struct GotExpected { pub expected: T, } -impl fmt::Display for GotExpected { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "got {}, expected {}", self.got, self.expected) - } -} - -impl core::error::Error for GotExpected {} - impl From<(T, T)> for GotExpected { #[inline] fn from((got, expected): (T, T)) -> Self { @@ -41,23 +31,10 @@ impl GotExpected { /// Same as [`GotExpected`], but [`Box`]ed for smaller size. /// /// Prefer instantiating using [`GotExpected`], and then using `.into()` to convert to this type. -#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, thiserror::Error, Debug)] +#[error(transparent)] pub struct GotExpectedBoxed(pub Box>); -impl fmt::Debug for GotExpectedBoxed { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - self.0.fmt(f) - } -} - -impl fmt::Display for GotExpectedBoxed { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - self.0.fmt(f) - } -} - -impl core::error::Error for GotExpectedBoxed {} - impl Deref for GotExpectedBoxed { type Target = GotExpected; diff --git a/crates/primitives-traits/src/transaction/error.rs b/crates/primitives-traits/src/transaction/error.rs index 15d1d44ac594..d155656c0e68 100644 --- a/crates/primitives-traits/src/transaction/error.rs +++ b/crates/primitives-traits/src/transaction/error.rs @@ -4,17 +4,17 @@ use crate::GotExpectedBoxed; use alloy_primitives::U256; /// Represents error variants that can happen when trying to validate a transaction. -#[derive(Debug, Clone, Eq, PartialEq, derive_more::Display)] +#[derive(Debug, Clone, Eq, PartialEq, thiserror::Error)] pub enum InvalidTransactionError { /// The sender does not have enough funds to cover the transaction fees - #[display( + #[error( "sender does not have enough funds ({}) to cover transaction fees: {}", _0.got, _0.expected )] InsufficientFunds(GotExpectedBoxed), /// The nonce is lower than the account's nonce, or there is a nonce gap present. /// /// This is a consensus error. - #[display("transaction nonce is not consistent: next nonce {state}, tx nonce {tx}")] + #[error("transaction nonce is not consistent: next nonce {state}, tx nonce {tx}")] NonceNotConsistent { /// The nonce of the transaction. tx: u64, @@ -22,49 +22,47 @@ pub enum InvalidTransactionError { state: u64, }, /// The transaction is before Spurious Dragon and has a chain ID. - #[display("transactions before Spurious Dragon should not have a chain ID")] + #[error("transactions before Spurious Dragon should not have a chain ID")] OldLegacyChainId, /// The chain ID in the transaction does not match the current network configuration. - #[display("transaction's chain ID does not match")] + #[error("transaction's chain ID does not match")] ChainIdMismatch, /// The transaction requires EIP-2930 which is not enabled currently. - #[display("EIP-2930 transactions are disabled")] + #[error("EIP-2930 transactions are disabled")] Eip2930Disabled, /// The transaction requires EIP-1559 which is not enabled currently. - #[display("EIP-1559 transactions are disabled")] + #[error("EIP-1559 transactions are disabled")] Eip1559Disabled, /// The transaction requires EIP-4844 which is not enabled currently. - #[display("EIP-4844 transactions are disabled")] + #[error("EIP-4844 transactions are disabled")] Eip4844Disabled, /// The transaction requires EIP-7702 which is not enabled currently. - #[display("EIP-7702 transactions are disabled")] + #[error("EIP-7702 transactions are disabled")] Eip7702Disabled, /// Thrown if a transaction is not supported in the current network configuration. - #[display("transaction type not supported")] + #[error("transaction type not supported")] TxTypeNotSupported, /// The calculated gas of the transaction exceeds `u64::MAX`. - #[display("gas overflow (maximum of u64)")] + #[error("gas overflow (maximum of u64)")] GasUintOverflow, /// The transaction is specified to use less gas than required to start the invocation. - #[display("intrinsic gas too low")] + #[error("intrinsic gas too low")] GasTooLow, /// The transaction gas exceeds the limit - #[display("intrinsic gas too high")] + #[error("intrinsic gas too high")] GasTooHigh, /// Thrown to ensure no one is able to specify a transaction with a tip higher than the total /// fee cap. - #[display("max priority fee per gas higher than max fee per gas")] + #[error("max priority fee per gas higher than max fee per gas")] TipAboveFeeCap, /// Thrown post London if the transaction's fee is less than the base fee of the block. - #[display("max fee per gas less than block base fee")] + #[error("max fee per gas less than block base fee")] FeeCapTooLow, /// Thrown if the sender of a transaction is a contract. - #[display("transaction signer has bytecode set")] + #[error("transaction signer has bytecode set")] SignerAccountHasBytecode, } -impl core::error::Error for InvalidTransactionError {} - /// Represents error variants that can happen when trying to convert a transaction to pooled /// transaction. #[derive(Debug, Clone, Eq, PartialEq, derive_more::Display, derive_more::Error)] @@ -76,14 +74,12 @@ pub enum TransactionConversionError { } /// Represents error variants than can happen when trying to convert a recovered transaction. -#[derive(Debug, Clone, Eq, PartialEq, derive_more::Display)] +#[derive(Debug, Clone, Eq, PartialEq, thiserror::Error)] pub enum TryFromRecoveredTransactionError { /// Thrown if the transaction type is unsupported. - #[display("Unsupported transaction type: {_0}")] + #[error("Unsupported transaction type: {_0}")] UnsupportedTransactionType(u8), /// This error variant is used when a blob sidecar is missing. - #[display("Blob sidecar missing for an EIP-4844 transaction")] + #[error("Blob sidecar missing for an EIP-4844 transaction")] BlobSidecarMissing, } - -impl core::error::Error for TryFromRecoveredTransactionError {} diff --git a/crates/rpc/rpc-eth-types/src/error/mod.rs b/crates/rpc/rpc-eth-types/src/error/mod.rs index aeea8ea5b894..7e80b243942c 100644 --- a/crates/rpc/rpc-eth-types/src/error/mod.rs +++ b/crates/rpc/rpc-eth-types/src/error/mod.rs @@ -579,7 +579,7 @@ impl From for RpcInvalidTransactionErr /// Represents a reverted transaction and its output data. /// /// Displays "execution reverted(: reason)?" if the reason is a string. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, thiserror::Error)] pub struct RevertError { /// The transaction output data /// @@ -617,8 +617,6 @@ impl std::fmt::Display for RevertError { } } -impl core::error::Error for RevertError {} - /// A helper error type that's mainly used to mirror `geth` Txpool's error messages #[derive(Debug, thiserror::Error)] pub enum RpcPoolError { diff --git a/crates/storage/errors/Cargo.toml b/crates/storage/errors/Cargo.toml index 2e864e09d43a..db5c31a31b1a 100644 --- a/crates/storage/errors/Cargo.toml +++ b/crates/storage/errors/Cargo.toml @@ -23,6 +23,7 @@ alloy-rlp.workspace = true # misc derive_more.workspace = true +thiserror.workspace = true [features] default = ["std"] diff --git a/crates/storage/errors/src/db.rs b/crates/storage/errors/src/db.rs index a9000a952b7f..c26ec44f2a09 100644 --- a/crates/storage/errors/src/db.rs +++ b/crates/storage/errors/src/db.rs @@ -5,60 +5,51 @@ use alloc::{ vec::Vec, }; use core::{ - fmt, fmt::{Debug, Display}, str::FromStr, }; /// Database error type. -#[derive(Clone, Debug, PartialEq, Eq, derive_more::Display)] +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] pub enum DatabaseError { /// Failed to open the database. - #[display("failed to open the database: {_0}")] + #[error("failed to open the database: {_0}")] Open(DatabaseErrorInfo), /// Failed to create a table in the database. - #[display("failed to create a table: {_0}")] + #[error("failed to create a table: {_0}")] CreateTable(DatabaseErrorInfo), /// Failed to write a value into a table. + #[error("Failed to write a value into a table: {_0}")] Write(Box), /// Failed to read a value from a table. - #[display("failed to read a value from a database table: {_0}")] + #[error("failed to read a value from a database table: {_0}")] Read(DatabaseErrorInfo), /// Failed to delete a `(key, value)` pair from a table. - #[display("database delete error code: {_0}")] + #[error("database delete error code: {_0}")] Delete(DatabaseErrorInfo), /// Failed to commit transaction changes into the database. - #[display("failed to commit transaction changes: {_0}")] + #[error("failed to commit transaction changes: {_0}")] Commit(DatabaseErrorInfo), /// Failed to initiate a transaction. - #[display("failed to initialize a transaction: {_0}")] + #[error("failed to initialize a transaction: {_0}")] InitTx(DatabaseErrorInfo), /// Failed to initialize a cursor. - #[display("failed to initialize a cursor: {_0}")] + #[error("failed to initialize a cursor: {_0}")] InitCursor(DatabaseErrorInfo), /// Failed to decode a key from a table. - #[display("failed to decode a key from a table")] + #[error("failed to decode a key from a table")] Decode, /// Failed to get database stats. - #[display("failed to get stats: {_0}")] + #[error("failed to get stats: {_0}")] Stats(DatabaseErrorInfo), /// Failed to use the specified log level, as it's not available. - #[display("log level {_0:?} is not available")] + #[error("log level {_0:?} is not available")] LogLevelUnavailable(LogLevel), /// Other unspecified error. - #[display("{_0}")] + #[error("{_0}")] Other(String), } -impl core::error::Error for DatabaseError { - fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { - match self { - Self::Write(err) => core::error::Error::source(err), - _ => Option::None, - } - } -} - /// Common error struct to propagate implementation-specific error information. #[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)] #[display("{message} ({code})")] @@ -87,7 +78,12 @@ impl From for DatabaseError { } /// Database write error. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +#[error("write operation {:?} failed for key \"{}\" in table {}: {}", + self.operation, + alloy_primitives::hex::encode(&self.key), + self.table_name, + self.info)] pub struct DatabaseWriteError { /// The error code and message. pub info: DatabaseErrorInfo, @@ -99,21 +95,6 @@ pub struct DatabaseWriteError { pub key: Vec, } -impl fmt::Display for DatabaseWriteError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "write operation {:?} failed for key \"{}\" in table {}: {}", - self.operation, - alloy_primitives::hex::encode(&self.key), - self.table_name, - self.info - ) - } -} - -impl core::error::Error for DatabaseWriteError {} - /// Database write operation type. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DatabaseWriteOperation { diff --git a/crates/storage/errors/src/lockfile.rs b/crates/storage/errors/src/lockfile.rs index 9a3af4ba325a..7c04869e9771 100644 --- a/crates/storage/errors/src/lockfile.rs +++ b/crates/storage/errors/src/lockfile.rs @@ -1,19 +1,17 @@ -use alloc::string::{String, ToString}; +use alloc::string::String; use reth_fs_util::FsPathError; /// Storage lock error. -#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)] +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum StorageLockError { /// Write lock taken - #[display("storage directory is currently in use as read-write by another process: PID {_0}")] + #[error("storage directory is currently in use as read-write by another process: PID {_0}")] Taken(usize), /// Indicates other unspecified errors. - #[display("{_0}")] + #[error("{_0}")] Other(String), } -impl core::error::Error for StorageLockError {} - /// TODO: turn into variant once `ProviderError` impl From for StorageLockError { fn from(error: FsPathError) -> Self { diff --git a/crates/storage/errors/src/provider.rs b/crates/storage/errors/src/provider.rs index d4b69cffb08e..7076984405d3 100644 --- a/crates/storage/errors/src/provider.rs +++ b/crates/storage/errors/src/provider.rs @@ -1,3 +1,5 @@ +use std::path::PathBuf; + use crate::{db::DatabaseError, lockfile::StorageLockError, writer::UnifiedStorageWriterError}; use alloc::{boxed::Box, string::String}; use alloy_eips::{BlockHashOrNumber, HashOrNumber}; @@ -10,169 +12,176 @@ use reth_static_file_types::StaticFileSegment; pub type ProviderResult = Result; /// Bundled errors variants thrown by various providers. -#[derive(Clone, Debug, Display, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] pub enum ProviderError { /// Database error. - Database(DatabaseError), + #[error(transparent)] + Database(#[from] DatabaseError), + /// RLP error. + #[error(transparent)] Rlp(alloy_rlp::Error), /// Filesystem path error. - #[display("{_0}")] + #[error("{0}")] FsPathError(String), + /// Nippy jar error. - #[display("nippy jar error: {_0}")] + #[error("nippy jar error: {0}")] NippyJar(String), + /// Trie witness error. - #[display("trie witness error: {_0}")] + #[error("trie witness error: {0}")] TrieWitnessError(String), + /// Error when recovering the sender for a transaction - #[display("failed to recover sender for transaction")] + #[error("failed to recover sender for transaction")] SenderRecoveryError, + /// The header number was not found for the given block hash. - #[display("block hash {_0} does not exist in Headers table")] + #[error("block hash {0} does not exist in Headers table")] BlockHashNotFound(BlockHash), + /// A block body is missing. - #[display("block meta not found for block #{_0}")] + #[error("block meta not found for block #{0}")] BlockBodyIndicesNotFound(BlockNumber), + /// The transition ID was found for the given address and storage key, but the changeset was /// not found. - #[display( - "storage change set for address {address} and key {storage_key} at block #{block_number} does not exist" - )] + #[error("storage change set for address {address} and key {storage_key} at block #{block_number} does not exist")] StorageChangesetNotFound { /// The block number found for the address and storage key. block_number: BlockNumber, /// The account address. address: Address, /// The storage key. - // NOTE: This is a Box only because otherwise this variant is 16 bytes larger than the - // second largest (which uses `BlockHashOrNumber`). storage_key: Box, }, + /// The block number was found for the given address, but the changeset was not found. - #[display("account change set for address {address} at block #{block_number} does not exist")] + #[error("account change set for address {address} at block #{block_number} does not exist")] AccountChangesetNotFound { /// Block number found for the address. block_number: BlockNumber, /// The account address. address: Address, }, + /// The total difficulty for a block is missing. - #[display("total difficulty not found for block #{_0}")] + #[error("total difficulty not found for block #{0}")] TotalDifficultyNotFound(BlockNumber), - /// when required header related data was not found but was required. - #[display("no header found for {_0:?}")] + + /// When required header related data was not found but was required. + #[error("no header found for {0:?}")] HeaderNotFound(BlockHashOrNumber), + /// The specific transaction identified by hash or id is missing. - #[display("no transaction found for {_0:?}")] + #[error("no transaction found for {0:?}")] TransactionNotFound(HashOrNumber), + /// The specific receipt for a transaction identified by hash or id is missing - #[display("no receipt found for {_0:?}")] + #[error("no receipt found for {0:?}")] ReceiptNotFound(HashOrNumber), + /// Unable to find the best block. - #[display("best block does not exist")] + #[error("best block does not exist")] BestBlockNotFound, + /// Unable to find the finalized block. - #[display("finalized block does not exist")] + #[error("finalized block does not exist")] FinalizedBlockNotFound, + /// Unable to find the safe block. - #[display("safe block does not exist")] + #[error("safe block does not exist")] SafeBlockNotFound, + /// Thrown when the cache service task dropped. - #[display("cache service task stopped")] + #[error("cache service task stopped")] CacheServiceUnavailable, + /// Thrown when we failed to lookup a block for the pending state. - #[display("unknown block {_0}")] + #[error("unknown block {0}")] UnknownBlockHash(B256), + /// Thrown when we were unable to find a state for a block hash. - #[display("no state found for block {_0}")] + #[error("no state found for block {0}")] StateForHashNotFound(B256), + /// Thrown when we were unable to find a state for a block number. - #[display("no state found for block number {_0}")] + #[error("no state found for block number {0}")] StateForNumberNotFound(u64), + /// Unable to find the block number for a given transaction index. - #[display("unable to find the block number for a given transaction index")] + #[error("unable to find the block number for a given transaction index")] BlockNumberForTransactionIndexNotFound, + /// Root mismatch. - #[display("merkle trie {_0}")] + #[error("merkle trie {0}")] StateRootMismatch(Box), + /// Root mismatch during unwind - #[display("unwind merkle trie {_0}")] + #[error("unwind merkle trie {0}")] UnwindStateRootMismatch(Box), + /// State is not available for the given block number because it is pruned. - #[display("state at block #{_0} is pruned")] + #[error("state at block #{0} is pruned")] StateAtBlockPruned(BlockNumber), + /// Provider does not support this particular request. - #[display("this provider does not support this request")] + #[error("this provider does not support this request")] UnsupportedProvider, + /// Static File is not found at specified path. #[cfg(feature = "std")] - #[display("not able to find {_0} static file at {_1:?}")] - MissingStaticFilePath(StaticFileSegment, std::path::PathBuf), + #[error("not able to find {0} static file at {1:?}")] + MissingStaticFilePath(StaticFileSegment, PathBuf), + /// Static File is not found for requested block. - #[display("not able to find {_0} static file for block number {_1}")] + #[error("not able to find {0} static file for block number {1}")] MissingStaticFileBlock(StaticFileSegment, BlockNumber), + /// Static File is not found for requested transaction. - #[display("unable to find {_0} static file for transaction id {_1}")] + #[error("unable to find {0} static file for transaction id {1}")] MissingStaticFileTx(StaticFileSegment, TxNumber), + /// Static File is finalized and cannot be written to. - #[display("unable to write block #{_1} to finalized static file {_0}")] + #[error("unable to write block #{1} to finalized static file {0}")] FinalizedStaticFile(StaticFileSegment, BlockNumber), + /// Trying to insert data from an unexpected block number. - #[display("trying to append data to {_0} as block #{_1} but expected block #{_2}")] + #[error("trying to append data to {0} as block #{1} but expected block #{2}")] UnexpectedStaticFileBlockNumber(StaticFileSegment, BlockNumber, BlockNumber), + /// Trying to insert data from an unexpected block number. - #[display("trying to append row to {_0} at index #{_1} but expected index #{_2}")] + #[error("trying to append row to {0} at index #{1} but expected index #{2}")] UnexpectedStaticFileTxNumber(StaticFileSegment, TxNumber, TxNumber), + /// Static File Provider was initialized as read-only. - #[display("cannot get a writer on a read-only environment.")] + #[error("cannot get a writer on a read-only environment.")] ReadOnlyStaticFileAccess, + /// Consistent view error. - #[display("failed to initialize consistent view: {_0}")] + #[error("failed to initialize consistent view: {0}")] ConsistentView(Box), + /// Storage lock error. - StorageLockError(StorageLockError), + #[error(transparent)] + StorageLockError(#[from] StorageLockError), + /// Storage writer error. - UnifiedStorageWriterError(UnifiedStorageWriterError), + #[error(transparent)] + UnifiedStorageWriterError(#[from] UnifiedStorageWriterError), + /// Received invalid output from configured storage implementation. + #[error("received invalid output from storage")] InvalidStorageOutput, } -impl From for ProviderError { - fn from(error: DatabaseError) -> Self { - Self::Database(error) - } -} - impl From for ProviderError { fn from(error: alloy_rlp::Error) -> Self { Self::Rlp(error) } } -impl From for ProviderError { - fn from(error: StorageLockError) -> Self { - Self::StorageLockError(error) - } -} - -impl From for ProviderError { - fn from(error: UnifiedStorageWriterError) -> Self { - Self::UnifiedStorageWriterError(error) - } -} - -impl core::error::Error for ProviderError { - fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { - match self { - Self::Database(source) => core::error::Error::source(source), - Self::StorageLockError(source) => core::error::Error::source(source), - Self::UnifiedStorageWriterError(source) => core::error::Error::source(source), - _ => Option::None, - } - } -} - /// A root mismatch error at a given block height. #[derive(Clone, Debug, PartialEq, Eq, Display)] #[display("root mismatch at #{block_number} ({block_hash}): {root}")]