From 7142b1e5c0622b7ae9edd915d325414f28dcaa0f Mon Sep 17 00:00:00 2001 From: Jorge Martinez Date: Thu, 1 Aug 2024 18:49:08 -0700 Subject: [PATCH 01/10] no_std support --- Cargo.lock | 1 + crates/storage/errors/Cargo.toml | 5 +- crates/storage/errors/src/db.rs | 75 ++++++++++++------- crates/storage/errors/src/lib.rs | 3 +- crates/storage/errors/src/lockfile.rs | 6 +- crates/storage/errors/src/provider.rs | 104 ++++++++++++++------------ crates/storage/errors/src/writer.rs | 13 ++-- 7 files changed, 121 insertions(+), 86 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d3447ba7f553..d64153346d20 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8678,6 +8678,7 @@ name = "reth-storage-errors" version = "1.0.4" dependencies = [ "alloy-rlp", + "derive_more", "reth-fs-util", "reth-primitives", "thiserror-no-std", diff --git a/crates/storage/errors/Cargo.toml b/crates/storage/errors/Cargo.toml index 5ef6f15771ef..a51c42ad0d09 100644 --- a/crates/storage/errors/Cargo.toml +++ b/crates/storage/errors/Cargo.toml @@ -15,8 +15,9 @@ alloy-rlp.workspace = true reth-primitives.workspace = true reth-fs-util.workspace = true -thiserror-no-std = { workspace = true, default-features = false } +thiserror-no-std = { workspace = true, default-features = false, optional = true} +derive_more.workspace = true [features] default = ["std"] -std = ["thiserror-no-std/std"] \ No newline at end of file +std = ["thiserror-no-std?/std"] \ No newline at end of file diff --git a/crates/storage/errors/src/db.rs b/crates/storage/errors/src/db.rs index 8b4896d23236..c5e202f47297 100644 --- a/crates/storage/errors/src/db.rs +++ b/crates/storage/errors/src/db.rs @@ -1,7 +1,7 @@ -#[cfg(feature = "std")] -use std::{fmt::Display, str::FromStr, string::String}; +// #[cfg(feature = "std")] +// use std::{fmt::Display, str::FromStr, string::String}; -#[cfg(not(feature = "std"))] +// #[cfg(not(feature = "std"))] use alloc::{ boxed::Box, format, @@ -9,53 +9,56 @@ use alloc::{ vec::Vec, }; -#[cfg(not(feature = "std"))] -use core::{fmt::Display, str::FromStr}; +// #[cfg(not(feature = "std"))] +use core::{fmt, fmt::{Display, Debug}, str::FromStr}; /// Database error type. -#[derive(Clone, Debug, PartialEq, Eq, thiserror_no_std::Error)] +#[derive(Clone, Debug, PartialEq, Eq, derive_more::Display)] pub enum DatabaseError { /// Failed to open the database. - #[error("failed to open the database: {0}")] + #[display(fmt="failed to open the database: {_0}")] Open(DatabaseErrorInfo), /// Failed to create a table in the database. - #[error("failed to create a table: {0}")] + #[display(fmt="failed to create a table: {_0}")] CreateTable(DatabaseErrorInfo), /// Failed to write a value into a table. - #[error(transparent)] - Write(#[from] Box), + // #[display(transparent)] + Write(Box), /// Failed to read a value from a table. - #[error("failed to read a value from a database table: {0}")] + #[display(fmt="failed to read a value from a database table: {_0}")] Read(DatabaseErrorInfo), /// Failed to delete a `(key, value)` pair from a table. - #[error("database delete error code: {0}")] + #[display(fmt="database delete error code: {_0}")] Delete(DatabaseErrorInfo), /// Failed to commit transaction changes into the database. - #[error("failed to commit transaction changes: {0}")] + #[display(fmt="failed to commit transaction changes: {_0}")] Commit(DatabaseErrorInfo), /// Failed to initiate a transaction. - #[error("failed to initialize a transaction: {0}")] + #[display(fmt="failed to initialize a transaction: {_0}")] InitTx(DatabaseErrorInfo), /// Failed to initialize a cursor. - #[error("failed to initialize a cursor: {0}")] + #[display(fmt="failed to initialize a cursor: {_0}")] InitCursor(DatabaseErrorInfo), /// Failed to decode a key from a table. - #[error("failed to decode a key from a table")] + #[display(fmt="failed to decode a key from a table")] Decode, /// Failed to get database stats. - #[error("failed to get stats: {0}")] + #[display(fmt="failed to get stats: {_0}")] Stats(DatabaseErrorInfo), /// Failed to use the specified log level, as it's not available. - #[error("log level {0:?} is not available")] + #[display(fmt="log level {_0:?} is not available")] LogLevelUnavailable(LogLevel), /// Other unspecified error. - #[error("{0}")] + #[display(fmt="{_0}")] Other(String), } +#[cfg(feature = "std")] +impl std::error::Error for DatabaseError {} + /// Common error struct to propagate implementation-specific error information. -#[derive(Debug, Clone, PartialEq, Eq, thiserror_no_std::Error)] -#[error("{message} ({code})")] +#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)] +#[display(fmt="{message} ({code})")] pub struct DatabaseErrorInfo { /// Human-readable error message. pub message: String, @@ -81,11 +84,7 @@ impl From for DatabaseError { } /// Database write error. -#[derive(Clone, Debug, PartialEq, Eq, thiserror_no_std::Error)] -#[error( - "write operation {operation:?} failed for key \"{key}\" in table {table_name:?}: {info}", - key = reth_primitives::hex::encode(key), -)] +#[derive(Clone, Debug, PartialEq, Eq)] pub struct DatabaseWriteError { /// The error code and message. pub info: DatabaseErrorInfo, @@ -97,18 +96,40 @@ 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, + reth_primitives::hex::encode(self.key.clone()), + self.table_name, + self.info + ) + } +} + +#[cfg(feature = "std")] +impl std::error::Error for DatabaseWriteError {} + /// Database write operation type. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, derive_more::Display)] +#[display(fmt="DatabaseWriteOperation: {}")] pub enum DatabaseWriteOperation { /// Append cursor. + #[display(fmt="CursorAppend")] CursorAppend, /// Upsert cursor. + #[display(fmt="CursorUpsert")] CursorUpsert, /// Insert cursor. + #[display(fmt="CursorInsert")] CursorInsert, /// Append duplicate cursor. + #[display(fmt="CursorAppendDup")] CursorAppendDup, /// Put. + #[display(fmt="Put")] Put, } diff --git a/crates/storage/errors/src/lib.rs b/crates/storage/errors/src/lib.rs index cf1a1a97627a..c99fd614780d 100644 --- a/crates/storage/errors/src/lib.rs +++ b/crates/storage/errors/src/lib.rs @@ -9,7 +9,8 @@ #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] #![cfg_attr(not(feature = "std"), no_std)] -#[cfg(not(feature = "std"))] +// #[cfg(not(feature = "std"))] +// #[macro_use] extern crate alloc; /// Database error diff --git a/crates/storage/errors/src/lockfile.rs b/crates/storage/errors/src/lockfile.rs index db27cb6e2e45..f8edb1855ff4 100644 --- a/crates/storage/errors/src/lockfile.rs +++ b/crates/storage/errors/src/lockfile.rs @@ -4,13 +4,13 @@ use reth_fs_util::FsPathError; use alloc::string::{String, ToString}; /// Storage lock error. -#[derive(Debug, Clone, PartialEq, Eq, thiserror_no_std::Error)] +#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)] pub enum StorageLockError { /// Write lock taken - #[error("storage directory is currently in use as read-write by another process: PID {0}")] + #[display(fmt="storage directory is currently in use as read-write by another process: PID {_0}")] Taken(usize), /// Indicates other unspecified errors. - #[error("{0}")] + #[display(fmt="{_0}")] Other(String), } diff --git a/crates/storage/errors/src/provider.rs b/crates/storage/errors/src/provider.rs index 1ef05c34d945..0c3163053cd6 100644 --- a/crates/storage/errors/src/provider.rs +++ b/crates/storage/errors/src/provider.rs @@ -5,8 +5,11 @@ use reth_primitives::{ #[cfg(feature = "std")] use std::path::PathBuf; +// #[cfg(feature = "std")] +// use std::fmt; -#[cfg(not(feature = "std"))] +// #[cfg(not(feature = "std"))] +// use core::fmt; use alloc::{ boxed::Box, string::{String, ToString}, @@ -16,35 +19,35 @@ use alloc::{ pub type ProviderResult = Result; /// Bundled errors variants thrown by various providers. -#[derive(Clone, Debug, thiserror_no_std::Error, PartialEq, Eq)] +#[derive(Clone, Debug, derive_more::Display, PartialEq, Eq)] pub enum ProviderError { /// Database error. - #[error(transparent)] - Database(#[from] crate::db::DatabaseError), + // #[error(transparent)] + Database(crate::db::DatabaseError), /// RLP error. - #[error(transparent)] - Rlp(#[from] alloy_rlp::Error), + // #[error(transparent)] + Rlp(alloy_rlp::Error), /// Filesystem path error. - #[error("{0}")] + #[display(fmt="{_0}")] FsPathError(String), /// Nippy jar error. - #[error("nippy jar error: {0}")] + #[display(fmt="nippy jar error: {_0}")] NippyJar(String), /// Trie witness error. - #[error("trie witness error: {0}")] + #[display(fmt="trie witness error: {_0}")] TrieWitnessError(String), /// Error when recovering the sender for a transaction - #[error("failed to recover sender for transaction")] + #[display(fmt="failed to recover sender for transaction")] SenderRecoveryError, /// The header number was not found for the given block hash. - #[error("block hash {0} does not exist in Headers table")] + #[display(fmt="block hash {_0} does not exist in Headers table")] BlockHashNotFound(BlockHash), /// A block body is missing. - #[error("block meta not found for block #{0}")] + #[display(fmt="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. - #[error("storage change set for address {address} and key {storage_key} at block #{block_number} does not exist")] + #[display(fmt="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, @@ -56,7 +59,7 @@ pub enum ProviderError { storage_key: Box, }, /// The block number was found for the given address, but the changeset was not found. - #[error("account change set for address {address} at block #{block_number} does not exist")] + #[display(fmt="account change set for address {address} at block #{block_number} does not exist")] AccountChangesetNotFound { /// Block number found for the address. block_number: BlockNumber, @@ -64,92 +67,97 @@ pub enum ProviderError { address: Address, }, /// The total difficulty for a block is missing. - #[error("total difficulty not found for block #{0}")] + #[display(fmt="total difficulty not found for block #{_0}")] TotalDifficultyNotFound(BlockNumber), /// when required header related data was not found but was required. - #[error("no header found for {0:?}")] + #[display(fmt="no header found for {_0:?}")] HeaderNotFound(BlockHashOrNumber), /// The specific transaction is missing. - #[error("no transaction found for {0:?}")] + #[display(fmt="no transaction found for {_0:?}")] TransactionNotFound(TxHashOrNumber), /// The specific receipt is missing - #[error("no receipt found for {0:?}")] + #[display(fmt="no receipt found for {_0:?}")] ReceiptNotFound(TxHashOrNumber), /// Unable to find the best block. - #[error("best block does not exist")] + #[display(fmt="best block does not exist")] BestBlockNotFound, /// Unable to find the finalized block. - #[error("finalized block does not exist")] + #[display(fmt="finalized block does not exist")] FinalizedBlockNotFound, /// Unable to find the safe block. - #[error("safe block does not exist")] + #[display(fmt="safe block does not exist")] SafeBlockNotFound, /// Mismatch of sender and transaction. - #[error("mismatch of sender and transaction id {tx_id}")] + #[display(fmt="mismatch of sender and transaction id {tx_id}")] MismatchOfTransactionAndSenderId { /// The transaction ID. tx_id: TxNumber, }, /// Block body wrong transaction count. - #[error("stored block indices does not match transaction count")] + #[display(fmt="stored block indices does not match transaction count")] BlockBodyTransactionCount, /// Thrown when the cache service task dropped. - #[error("cache service task stopped")] + #[display(fmt="cache service task stopped")] CacheServiceUnavailable, /// Thrown when we failed to lookup a block for the pending state. - #[error("unknown block {0}")] + #[display(fmt="unknown block {_0}")] UnknownBlockHash(B256), /// Thrown when we were unable to find a state for a block hash. - #[error("no state found for block {0}")] + #[display(fmt="no state found for block {_0}")] StateForHashNotFound(B256), /// Unable to find the block number for a given transaction index. - #[error("unable to find the block number for a given transaction index")] + #[display(fmt="unable to find the block number for a given transaction index")] BlockNumberForTransactionIndexNotFound, /// Root mismatch. - #[error("merkle trie {0}")] + #[display(fmt="merkle trie {_0}")] StateRootMismatch(Box), /// Root mismatch during unwind - #[error("unwind merkle trie {0}")] + #[display(fmt="unwind merkle trie {_0}")] UnwindStateRootMismatch(Box), /// State is not available for the given block number because it is pruned. - #[error("state at block #{0} is pruned")] + #[display(fmt="state at block #{_0} is pruned")] StateAtBlockPruned(BlockNumber), /// Provider does not support this particular request. - #[error("this provider does not support this request")] + #[display(fmt="this provider does not support this request")] UnsupportedProvider, /// Static File is not found at specified path. #[cfg(feature = "std")] - #[error("not able to find {0} static file at {1}")] + #[display(fmt="not able to find {_0} static file at {_1:?}")] MissingStaticFilePath(StaticFileSegment, PathBuf), /// Static File is not found for requested block. - #[error("not able to find {0} static file for block number {1}")] + #[display(fmt="not able to find {_0} static file for block number {_1}")] MissingStaticFileBlock(StaticFileSegment, BlockNumber), /// Static File is not found for requested transaction. - #[error("unable to find {0} static file for transaction id {1}")] + #[display(fmt="unable to find {_0} static file for transaction id {_1}")] MissingStaticFileTx(StaticFileSegment, TxNumber), /// Static File is finalized and cannot be written to. - #[error("unable to write block #{1} to finalized static file {0}")] + #[display(fmt="unable to write block #{_1} to finalized static file {_0}")] FinalizedStaticFile(StaticFileSegment, BlockNumber), /// Trying to insert data from an unexpected block number. - #[error("trying to append data to {0} as block #{1} but expected block #{2}")] + #[display(fmt="trying to append data to {_0} as block #{_1} but expected block #{_2}")] UnexpectedStaticFileBlockNumber(StaticFileSegment, BlockNumber, BlockNumber), /// Static File Provider was initialized as read-only. - #[error("cannot get a writer on a read-only environment.")] + #[display(fmt="cannot get a writer on a read-only environment.")] ReadOnlyStaticFileAccess, /// Error encountered when the block number conversion from U256 to u64 causes an overflow. - #[error("failed to convert block number U256 to u64: {0}")] + #[display(fmt="failed to convert block number U256 to u64: {_0}")] BlockNumberOverflow(U256), /// Consistent view error. - #[error("failed to initialize consistent view: {0}")] + #[display(fmt="failed to initialize consistent view: {_0}")] ConsistentView(Box), /// Storage lock error. - #[error(transparent)] - StorageLockError(#[from] crate::lockfile::StorageLockError), + StorageLockError(crate::lockfile::StorageLockError), /// Storage writer error. - #[error(transparent)] - UnifiedStorageWriterError(#[from] crate::writer::UnifiedStorageWriterError), + UnifiedStorageWriterError(crate::writer::UnifiedStorageWriterError), } +// #[cfg(feature = "std")] +// impl fmt::Display for PathBuf { +// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +// write!(f, "{}", self) +// } +// } + impl From for ProviderError { fn from(err: reth_fs_util::FsPathError) -> Self { Self::FsPathError(err.to_string()) @@ -157,8 +165,8 @@ impl From for ProviderError { } /// A root mismatch error at a given block height. -#[derive(Clone, Debug, PartialEq, Eq, thiserror_no_std::Error)] -#[error("root mismatch at #{block_number} ({block_hash}): {root}")] +#[derive(Clone, Debug, PartialEq, Eq, derive_more::Display)] +#[display(fmt="root mismatch at #{block_number} ({block_hash}): {root}")] pub struct RootMismatch { /// The target block root diff. pub root: GotExpected, @@ -169,16 +177,16 @@ pub struct RootMismatch { } /// Consistent database view error. -#[derive(Clone, Debug, PartialEq, Eq, thiserror_no_std::Error)] +#[derive(Clone, Debug, PartialEq, Eq, derive_more::Display)] pub enum ConsistentViewError { /// Error thrown on attempt to initialize provider while node is still syncing. - #[error("node is syncing. best block: {best_block:?}")] + #[display(fmt="node is syncing. best block: {best_block:?}")] Syncing { /// Best block diff. best_block: GotExpected, }, /// Error thrown on inconsistent database view. - #[error("inconsistent database state: {tip:?}")] + #[display(fmt="inconsistent database state: {tip:?}")] Inconsistent { /// The tip diff. tip: GotExpected>, diff --git a/crates/storage/errors/src/writer.rs b/crates/storage/errors/src/writer.rs index 362140da7b61..067b1e32b2c3 100644 --- a/crates/storage/errors/src/writer.rs +++ b/crates/storage/errors/src/writer.rs @@ -2,15 +2,18 @@ use crate::db::DatabaseError; use reth_primitives::StaticFileSegment; /// `UnifiedStorageWriter` related errors -#[derive(Clone, Debug, thiserror_no_std::Error, PartialEq, Eq)] +/// `StorageWriter` related errors +#[derive(Clone, Debug, derive_more::Display, PartialEq, Eq)] pub enum UnifiedStorageWriterError { + /// Database writer is missing + #[display(fmt="Database writer is missing")] + MissingDatabaseWriter, /// Static file writer is missing - #[error("Static file writer is missing")] + #[display(fmt="Static file writer is missing")] MissingStaticFileWriter, /// Static file writer is of wrong segment - #[error("Static file writer is of wrong segment: got {0}, expected {1}")] + #[display(fmt="Static file writer is of wrong segment: got {_0}, expected {_1}")] IncorrectStaticFileWriter(StaticFileSegment, StaticFileSegment), /// Database-related errors. - #[error(transparent)] - Database(#[from] DatabaseError), + Database(DatabaseError), } From f7b776e8a3d7987eba6fd7fa52669dd5d29685e7 Mon Sep 17 00:00:00 2001 From: Jorge Martinez Date: Thu, 1 Aug 2024 19:10:19 -0700 Subject: [PATCH 02/10] Cleaning up unused code --- crates/storage/errors/src/provider.rs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/crates/storage/errors/src/provider.rs b/crates/storage/errors/src/provider.rs index 0c3163053cd6..d1f9a1243b06 100644 --- a/crates/storage/errors/src/provider.rs +++ b/crates/storage/errors/src/provider.rs @@ -151,13 +151,6 @@ pub enum ProviderError { UnifiedStorageWriterError(crate::writer::UnifiedStorageWriterError), } -// #[cfg(feature = "std")] -// impl fmt::Display for PathBuf { -// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { -// write!(f, "{}", self) -// } -// } - impl From for ProviderError { fn from(err: reth_fs_util::FsPathError) -> Self { Self::FsPathError(err.to_string()) From af3338145246b2a802a37c909d277e6ae1061367 Mon Sep 17 00:00:00 2001 From: Jorge Martinez Date: Fri, 2 Aug 2024 12:12:19 -0700 Subject: [PATCH 03/10] Removing thiserror-no-std, fixing formatting, and impl From for various error variants --- Cargo.lock | 1 - crates/storage/errors/Cargo.toml | 4 +- crates/storage/errors/src/db.rs | 39 +++++----- crates/storage/errors/src/lib.rs | 2 - crates/storage/errors/src/lockfile.rs | 4 +- crates/storage/errors/src/provider.rs | 105 +++++++++++++++----------- crates/storage/errors/src/writer.rs | 12 ++- 7 files changed, 94 insertions(+), 73 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d64153346d20..da25f51e8358 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8681,7 +8681,6 @@ dependencies = [ "derive_more", "reth-fs-util", "reth-primitives", - "thiserror-no-std", ] [[package]] diff --git a/crates/storage/errors/Cargo.toml b/crates/storage/errors/Cargo.toml index a51c42ad0d09..c93adfbe1955 100644 --- a/crates/storage/errors/Cargo.toml +++ b/crates/storage/errors/Cargo.toml @@ -15,9 +15,9 @@ alloy-rlp.workspace = true reth-primitives.workspace = true reth-fs-util.workspace = true -thiserror-no-std = { workspace = true, default-features = false, optional = true} +# misc derive_more.workspace = true [features] default = ["std"] -std = ["thiserror-no-std?/std"] \ No newline at end of file +std = [] \ No newline at end of file diff --git a/crates/storage/errors/src/db.rs b/crates/storage/errors/src/db.rs index c5e202f47297..03781f985497 100644 --- a/crates/storage/errors/src/db.rs +++ b/crates/storage/errors/src/db.rs @@ -16,40 +16,39 @@ use core::{fmt, fmt::{Display, Debug}, str::FromStr}; #[derive(Clone, Debug, PartialEq, Eq, derive_more::Display)] pub enum DatabaseError { /// Failed to open the database. - #[display(fmt="failed to open the database: {_0}")] + #[display(fmt = "failed to open the database: {_0}")] Open(DatabaseErrorInfo), /// Failed to create a table in the database. - #[display(fmt="failed to create a table: {_0}")] + #[display(fmt = "failed to create a table: {_0}")] CreateTable(DatabaseErrorInfo), /// Failed to write a value into a table. - // #[display(transparent)] Write(Box), /// Failed to read a value from a table. - #[display(fmt="failed to read a value from a database table: {_0}")] + #[display(fmt = "failed to read a value from a database table: {_0}")] Read(DatabaseErrorInfo), /// Failed to delete a `(key, value)` pair from a table. - #[display(fmt="database delete error code: {_0}")] + #[display(fmt = "database delete error code: {_0}")] Delete(DatabaseErrorInfo), /// Failed to commit transaction changes into the database. - #[display(fmt="failed to commit transaction changes: {_0}")] + #[display(fmt = "failed to commit transaction changes: {_0}")] Commit(DatabaseErrorInfo), /// Failed to initiate a transaction. - #[display(fmt="failed to initialize a transaction: {_0}")] + #[display(fmt = "failed to initialize a transaction: {_0}")] InitTx(DatabaseErrorInfo), /// Failed to initialize a cursor. - #[display(fmt="failed to initialize a cursor: {_0}")] + #[display(fmt = "failed to initialize a cursor: {_0}")] InitCursor(DatabaseErrorInfo), /// Failed to decode a key from a table. - #[display(fmt="failed to decode a key from a table")] + #[display(fmt = "failed to decode a key from a table")] Decode, /// Failed to get database stats. - #[display(fmt="failed to get stats: {_0}")] + #[display(fmt = "failed to get stats: {_0}")] Stats(DatabaseErrorInfo), /// Failed to use the specified log level, as it's not available. - #[display(fmt="log level {_0:?} is not available")] + #[display(fmt = "log level {_0:?} is not available")] LogLevelUnavailable(LogLevel), /// Other unspecified error. - #[display(fmt="{_0}")] + #[display(fmt = "{_0}")] Other(String), } @@ -58,7 +57,7 @@ impl std::error::Error for DatabaseError {} /// Common error struct to propagate implementation-specific error information. #[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)] -#[display(fmt="{message} ({code})")] +#[display(fmt = "{message} ({code})")] pub struct DatabaseErrorInfo { /// Human-readable error message. pub message: String, @@ -102,7 +101,7 @@ impl fmt::Display for DatabaseWriteError { f, "write operation {} failed for key \"{}\" in table {}: {}", self.operation, - reth_primitives::hex::encode(self.key.clone()), + reth_primitives::hex::encode(&self.key), self.table_name, self.info ) @@ -114,22 +113,22 @@ impl std::error::Error for DatabaseWriteError {} /// Database write operation type. #[derive(Clone, Copy, Debug, PartialEq, Eq, derive_more::Display)] -#[display(fmt="DatabaseWriteOperation: {}")] +#[display(fmt = "DatabaseWriteOperation: {}")] pub enum DatabaseWriteOperation { /// Append cursor. - #[display(fmt="CursorAppend")] + #[display(fmt = "CursorAppend")] CursorAppend, /// Upsert cursor. - #[display(fmt="CursorUpsert")] + #[display(fmt = "CursorUpsert")] CursorUpsert, /// Insert cursor. - #[display(fmt="CursorInsert")] + #[display(fmt = "CursorInsert")] CursorInsert, /// Append duplicate cursor. - #[display(fmt="CursorAppendDup")] + #[display(fmt = "CursorAppendDup")] CursorAppendDup, /// Put. - #[display(fmt="Put")] + #[display(fmt = "Put")] Put, } diff --git a/crates/storage/errors/src/lib.rs b/crates/storage/errors/src/lib.rs index c99fd614780d..6abb0cd9b425 100644 --- a/crates/storage/errors/src/lib.rs +++ b/crates/storage/errors/src/lib.rs @@ -9,8 +9,6 @@ #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] #![cfg_attr(not(feature = "std"), no_std)] -// #[cfg(not(feature = "std"))] -// #[macro_use] extern crate alloc; /// Database error diff --git a/crates/storage/errors/src/lockfile.rs b/crates/storage/errors/src/lockfile.rs index f8edb1855ff4..19da101e65f1 100644 --- a/crates/storage/errors/src/lockfile.rs +++ b/crates/storage/errors/src/lockfile.rs @@ -7,10 +7,10 @@ use alloc::string::{String, ToString}; #[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)] pub enum StorageLockError { /// Write lock taken - #[display(fmt="storage directory is currently in use as read-write by another process: PID {_0}")] + #[display(fmt = "storage directory is currently in use as read-write by another process: PID {_0}")] Taken(usize), /// Indicates other unspecified errors. - #[display(fmt="{_0}")] + #[display(fmt = "{_0}")] Other(String), } diff --git a/crates/storage/errors/src/provider.rs b/crates/storage/errors/src/provider.rs index d1f9a1243b06..0288b010db2f 100644 --- a/crates/storage/errors/src/provider.rs +++ b/crates/storage/errors/src/provider.rs @@ -2,14 +2,11 @@ use reth_primitives::{ Address, BlockHash, BlockHashOrNumber, BlockNumber, GotExpected, StaticFileSegment, TxHashOrNumber, TxNumber, B256, U256, }; +use crate::{db::DatabaseError, lockfile::StorageLockError, writer::UnifiedStorageWriterError}; #[cfg(feature = "std")] use std::path::PathBuf; -// #[cfg(feature = "std")] -// use std::fmt; -// #[cfg(not(feature = "std"))] -// use core::fmt; use alloc::{ boxed::Box, string::{String, ToString}, @@ -22,32 +19,30 @@ pub type ProviderResult = Result; #[derive(Clone, Debug, derive_more::Display, PartialEq, Eq)] pub enum ProviderError { /// Database error. - // #[error(transparent)] - Database(crate::db::DatabaseError), + Database(DatabaseError), /// RLP error. - // #[error(transparent)] Rlp(alloy_rlp::Error), /// Filesystem path error. - #[display(fmt="{_0}")] + #[display(fmt = "{_0}")] FsPathError(String), /// Nippy jar error. - #[display(fmt="nippy jar error: {_0}")] + #[display(fmt = "nippy jar error: {_0}")] NippyJar(String), /// Trie witness error. - #[display(fmt="trie witness error: {_0}")] + #[display(fmt = "trie witness error: {_0}")] TrieWitnessError(String), /// Error when recovering the sender for a transaction - #[display(fmt="failed to recover sender for transaction")] + #[display(fmt = "failed to recover sender for transaction")] SenderRecoveryError, /// The header number was not found for the given block hash. - #[display(fmt="block hash {_0} does not exist in Headers table")] + #[display(fmt = "block hash {_0} does not exist in Headers table")] BlockHashNotFound(BlockHash), /// A block body is missing. - #[display(fmt="block meta not found for block #{_0}")] + #[display(fmt = "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(fmt="storage change set for address {address} and key {storage_key} at block #{block_number} does not exist")] + #[display(fmt = "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, @@ -59,7 +54,7 @@ pub enum ProviderError { storage_key: Box, }, /// The block number was found for the given address, but the changeset was not found. - #[display(fmt="account change set for address {address} at block #{block_number} does not exist")] + #[display(fmt = "account change set for address {address} at block #{block_number} does not exist")] AccountChangesetNotFound { /// Block number found for the address. block_number: BlockNumber, @@ -67,83 +62,83 @@ pub enum ProviderError { address: Address, }, /// The total difficulty for a block is missing. - #[display(fmt="total difficulty not found for block #{_0}")] + #[display(fmt = "total difficulty not found for block #{_0}")] TotalDifficultyNotFound(BlockNumber), /// when required header related data was not found but was required. - #[display(fmt="no header found for {_0:?}")] + #[display(fmt = "no header found for {_0:?}")] HeaderNotFound(BlockHashOrNumber), /// The specific transaction is missing. - #[display(fmt="no transaction found for {_0:?}")] + #[display(fmt = "no transaction found for {_0:?}")] TransactionNotFound(TxHashOrNumber), /// The specific receipt is missing - #[display(fmt="no receipt found for {_0:?}")] + #[display(fmt = "no receipt found for {_0:?}")] ReceiptNotFound(TxHashOrNumber), /// Unable to find the best block. - #[display(fmt="best block does not exist")] + #[display(fmt = "best block does not exist")] BestBlockNotFound, /// Unable to find the finalized block. - #[display(fmt="finalized block does not exist")] + #[display(fmt = "finalized block does not exist")] FinalizedBlockNotFound, /// Unable to find the safe block. - #[display(fmt="safe block does not exist")] + #[display(fmt = "safe block does not exist")] SafeBlockNotFound, /// Mismatch of sender and transaction. - #[display(fmt="mismatch of sender and transaction id {tx_id}")] + #[display(fmt = "mismatch of sender and transaction id {tx_id}")] MismatchOfTransactionAndSenderId { /// The transaction ID. tx_id: TxNumber, }, /// Block body wrong transaction count. - #[display(fmt="stored block indices does not match transaction count")] + #[display(fmt = "stored block indices does not match transaction count")] BlockBodyTransactionCount, /// Thrown when the cache service task dropped. - #[display(fmt="cache service task stopped")] + #[display(fmt = "cache service task stopped")] CacheServiceUnavailable, /// Thrown when we failed to lookup a block for the pending state. - #[display(fmt="unknown block {_0}")] + #[display(fmt = "unknown block {_0}")] UnknownBlockHash(B256), /// Thrown when we were unable to find a state for a block hash. - #[display(fmt="no state found for block {_0}")] + #[display(fmt = "no state found for block {_0}")] StateForHashNotFound(B256), /// Unable to find the block number for a given transaction index. - #[display(fmt="unable to find the block number for a given transaction index")] + #[display(fmt = "unable to find the block number for a given transaction index")] BlockNumberForTransactionIndexNotFound, /// Root mismatch. - #[display(fmt="merkle trie {_0}")] + #[display(fmt = "merkle trie {_0}")] StateRootMismatch(Box), /// Root mismatch during unwind - #[display(fmt="unwind merkle trie {_0}")] + #[display(fmt = "unwind merkle trie {_0}")] UnwindStateRootMismatch(Box), /// State is not available for the given block number because it is pruned. - #[display(fmt="state at block #{_0} is pruned")] + #[display(fmt = "state at block #{_0} is pruned")] StateAtBlockPruned(BlockNumber), /// Provider does not support this particular request. - #[display(fmt="this provider does not support this request")] + #[display(fmt = "this provider does not support this request")] UnsupportedProvider, /// Static File is not found at specified path. #[cfg(feature = "std")] - #[display(fmt="not able to find {_0} static file at {_1:?}")] + #[display(fmt = "not able to find {_0} static file at {_1:?}")] MissingStaticFilePath(StaticFileSegment, PathBuf), /// Static File is not found for requested block. - #[display(fmt="not able to find {_0} static file for block number {_1}")] + #[display(fmt = "not able to find {_0} static file for block number {_1}")] MissingStaticFileBlock(StaticFileSegment, BlockNumber), /// Static File is not found for requested transaction. - #[display(fmt="unable to find {_0} static file for transaction id {_1}")] + #[display(fmt = "unable to find {_0} static file for transaction id {_1}")] MissingStaticFileTx(StaticFileSegment, TxNumber), /// Static File is finalized and cannot be written to. - #[display(fmt="unable to write block #{_1} to finalized static file {_0}")] + #[display(fmt = "unable to write block #{_1} to finalized static file {_0}")] FinalizedStaticFile(StaticFileSegment, BlockNumber), /// Trying to insert data from an unexpected block number. - #[display(fmt="trying to append data to {_0} as block #{_1} but expected block #{_2}")] + #[display(fmt = "trying to append data to {_0} as block #{_1} but expected block #{_2}")] UnexpectedStaticFileBlockNumber(StaticFileSegment, BlockNumber, BlockNumber), /// Static File Provider was initialized as read-only. - #[display(fmt="cannot get a writer on a read-only environment.")] + #[display(fmt = "cannot get a writer on a read-only environment.")] ReadOnlyStaticFileAccess, /// Error encountered when the block number conversion from U256 to u64 causes an overflow. - #[display(fmt="failed to convert block number U256 to u64: {_0}")] + #[display(fmt = "failed to convert block number U256 to u64: {_0}")] BlockNumberOverflow(U256), /// Consistent view error. - #[display(fmt="failed to initialize consistent view: {_0}")] + #[display(fmt = "failed to initialize consistent view: {_0}")] ConsistentView(Box), /// Storage lock error. StorageLockError(crate::lockfile::StorageLockError), @@ -151,6 +146,30 @@ pub enum ProviderError { UnifiedStorageWriterError(crate::writer::UnifiedStorageWriterError), } +impl From for ProviderError { + fn from(value: DatabaseError) -> Self { + Self::Database(value) + } +} + +impl From for ProviderError { + fn from(value: alloy_rlp::Error) -> Self { + Self::Rlp(value) + } +} + +impl From for ProviderError { + fn from(value: StorageLockError) -> Self { + Self::StorageLockError(value) + } +} + +impl From for ProviderError { + fn from(value: UnifiedStorageWriterError) -> Self { + Self::UnifiedStorageWriterError(value) + } +} + impl From for ProviderError { fn from(err: reth_fs_util::FsPathError) -> Self { Self::FsPathError(err.to_string()) @@ -159,7 +178,7 @@ impl From for ProviderError { /// A root mismatch error at a given block height. #[derive(Clone, Debug, PartialEq, Eq, derive_more::Display)] -#[display(fmt="root mismatch at #{block_number} ({block_hash}): {root}")] +#[display(fmt = "root mismatch at #{block_number} ({block_hash}): {root}")] pub struct RootMismatch { /// The target block root diff. pub root: GotExpected, @@ -173,13 +192,13 @@ pub struct RootMismatch { #[derive(Clone, Debug, PartialEq, Eq, derive_more::Display)] pub enum ConsistentViewError { /// Error thrown on attempt to initialize provider while node is still syncing. - #[display(fmt="node is syncing. best block: {best_block:?}")] + #[display(fmt = "node is syncing. best block: {best_block:?}")] Syncing { /// Best block diff. best_block: GotExpected, }, /// Error thrown on inconsistent database view. - #[display(fmt="inconsistent database state: {tip:?}")] + #[display(fmt = "inconsistent database state: {tip:?}")] Inconsistent { /// The tip diff. tip: GotExpected>, diff --git a/crates/storage/errors/src/writer.rs b/crates/storage/errors/src/writer.rs index 067b1e32b2c3..8c3c3ab56801 100644 --- a/crates/storage/errors/src/writer.rs +++ b/crates/storage/errors/src/writer.rs @@ -6,14 +6,20 @@ use reth_primitives::StaticFileSegment; #[derive(Clone, Debug, derive_more::Display, PartialEq, Eq)] pub enum UnifiedStorageWriterError { /// Database writer is missing - #[display(fmt="Database writer is missing")] + #[display(fmt = "Database writer is missing")] MissingDatabaseWriter, /// Static file writer is missing - #[display(fmt="Static file writer is missing")] + #[display(fmt = "Static file writer is missing")] MissingStaticFileWriter, /// Static file writer is of wrong segment - #[display(fmt="Static file writer is of wrong segment: got {_0}, expected {_1}")] + #[display(fmt = "Static file writer is of wrong segment: got {_0}, expected {_1}")] IncorrectStaticFileWriter(StaticFileSegment, StaticFileSegment), /// Database-related errors. Database(DatabaseError), } + +impl From for UnifiedStorageWriterError { + fn from(value: DatabaseError) -> Self { + Self::Database(value) + } +} \ No newline at end of file From f614356bcd1792778aae48ac2dd01c056cfc1abe Mon Sep 17 00:00:00 2001 From: Jorge Martinez Date: Fri, 2 Aug 2024 12:13:48 -0700 Subject: [PATCH 04/10] removing no_std feature gate from alloc::string::{String,ToString} --- crates/storage/errors/src/lockfile.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/crates/storage/errors/src/lockfile.rs b/crates/storage/errors/src/lockfile.rs index 19da101e65f1..1bbafc2ab9ce 100644 --- a/crates/storage/errors/src/lockfile.rs +++ b/crates/storage/errors/src/lockfile.rs @@ -1,6 +1,4 @@ use reth_fs_util::FsPathError; - -#[cfg(not(feature = "std"))] use alloc::string::{String, ToString}; /// Storage lock error. From 194147f0fa5393edf075076fcc7be2aa5708d2cd Mon Sep 17 00:00:00 2001 From: Jorge Martinez Date: Tue, 6 Aug 2024 15:59:06 -0700 Subject: [PATCH 05/10] implementing source for Database error --- crates/storage/errors/src/db.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/storage/errors/src/db.rs b/crates/storage/errors/src/db.rs index 03781f985497..9bbc817e1792 100644 --- a/crates/storage/errors/src/db.rs +++ b/crates/storage/errors/src/db.rs @@ -53,7 +53,16 @@ pub enum DatabaseError { } #[cfg(feature = "std")] -impl std::error::Error for DatabaseError {} +impl std::error::Error for DatabaseError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Write(err) => { + std::error::Error::source(err) + }, + _ => Option::None + } + } +} /// Common error struct to propagate implementation-specific error information. #[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)] From 4e331405e08ec3c618295282102f29ea0d886a2e Mon Sep 17 00:00:00 2001 From: Jorge Martinez Date: Tue, 6 Aug 2024 16:43:48 -0700 Subject: [PATCH 06/10] implemented source for wrapped errors --- crates/storage/errors/src/db.rs | 6 ------ crates/storage/errors/src/lockfile.rs | 3 +++ crates/storage/errors/src/provider.rs | 20 ++++++++++++++++++++ crates/storage/errors/src/writer.rs | 12 ++++++++++++ 4 files changed, 35 insertions(+), 6 deletions(-) diff --git a/crates/storage/errors/src/db.rs b/crates/storage/errors/src/db.rs index 9bbc817e1792..b69a4674fc52 100644 --- a/crates/storage/errors/src/db.rs +++ b/crates/storage/errors/src/db.rs @@ -1,15 +1,9 @@ -// #[cfg(feature = "std")] -// use std::{fmt::Display, str::FromStr, string::String}; - -// #[cfg(not(feature = "std"))] use alloc::{ boxed::Box, format, string::{String, ToString}, vec::Vec, }; - -// #[cfg(not(feature = "std"))] use core::{fmt, fmt::{Display, Debug}, str::FromStr}; /// Database error type. diff --git a/crates/storage/errors/src/lockfile.rs b/crates/storage/errors/src/lockfile.rs index 1bbafc2ab9ce..fdc3bb274eb7 100644 --- a/crates/storage/errors/src/lockfile.rs +++ b/crates/storage/errors/src/lockfile.rs @@ -12,6 +12,9 @@ pub enum StorageLockError { Other(String), } +#[cfg(feature = "std")] +impl std::error::Error for StorageLockError {} + /// TODO: turn into variant once `ProviderError` impl From for StorageLockError { fn from(source: FsPathError) -> Self { diff --git a/crates/storage/errors/src/provider.rs b/crates/storage/errors/src/provider.rs index 0288b010db2f..58a6b9958fc8 100644 --- a/crates/storage/errors/src/provider.rs +++ b/crates/storage/errors/src/provider.rs @@ -145,6 +145,26 @@ pub enum ProviderError { /// Storage writer error. UnifiedStorageWriterError(crate::writer::UnifiedStorageWriterError), } +#[cfg(feature = "std")] +impl std::error::Error for ProviderError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Database(source) => { + std::error::Error::source(source) + }, + Self::Rlp(source) => { + std::error::Error::source(source) + }, + Self::StorageLockError(source) => { + std::error::Error::source(source) + }, + Self::UnifiedStorageWriterError(source) => { + std::error::Error::source(source) + }, + _ => Option::None + } + } +} impl From for ProviderError { fn from(value: DatabaseError) -> Self { diff --git a/crates/storage/errors/src/writer.rs b/crates/storage/errors/src/writer.rs index 8c3c3ab56801..858f53741801 100644 --- a/crates/storage/errors/src/writer.rs +++ b/crates/storage/errors/src/writer.rs @@ -18,6 +18,18 @@ pub enum UnifiedStorageWriterError { Database(DatabaseError), } +#[cfg(feature = "std")] +impl std::error::Error for UnifiedStorageWriterError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Database(source) => { + std::error::Error::source(source) + }, + _ => Option::None + } + } +} + impl From for UnifiedStorageWriterError { fn from(value: DatabaseError) -> Self { Self::Database(value) From 3fe365224f35f15cb860a5cadd4feafb501dd0e7 Mon Sep 17 00:00:00 2001 From: Jorge Martinez Date: Tue, 6 Aug 2024 18:36:22 -0700 Subject: [PATCH 07/10] formatting --- crates/storage/errors/src/provider.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/storage/errors/src/provider.rs b/crates/storage/errors/src/provider.rs index 58a6b9958fc8..ad490128cb96 100644 --- a/crates/storage/errors/src/provider.rs +++ b/crates/storage/errors/src/provider.rs @@ -145,6 +145,7 @@ pub enum ProviderError { /// Storage writer error. UnifiedStorageWriterError(crate::writer::UnifiedStorageWriterError), } + #[cfg(feature = "std")] impl std::error::Error for ProviderError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { From dc1b877b05e7dc8be545ea70a6aecef9b6dadb16 Mon Sep 17 00:00:00 2001 From: Jorge Martinez Date: Wed, 7 Aug 2024 11:20:39 -0700 Subject: [PATCH 08/10] slightly reduced boilerplate code using derive_more --- crates/storage/errors/src/provider.rs | 64 +++++++++++---------------- 1 file changed, 26 insertions(+), 38 deletions(-) diff --git a/crates/storage/errors/src/provider.rs b/crates/storage/errors/src/provider.rs index ad490128cb96..3f521bc19ca3 100644 --- a/crates/storage/errors/src/provider.rs +++ b/crates/storage/errors/src/provider.rs @@ -2,46 +2,49 @@ use reth_primitives::{ Address, BlockHash, BlockHashOrNumber, BlockNumber, GotExpected, StaticFileSegment, TxHashOrNumber, TxNumber, B256, U256, }; -use crate::{db::DatabaseError, lockfile::StorageLockError, writer::UnifiedStorageWriterError}; +use derive_more::{Display, From}; +use alloc::{boxed::Box, string::String}; +use crate::db::DatabaseError; #[cfg(feature = "std")] use std::path::PathBuf; -use alloc::{ - boxed::Box, - string::{String, ToString}, -}; - /// Provider result type. pub type ProviderResult = Result; /// Bundled errors variants thrown by various providers. -#[derive(Clone, Debug, derive_more::Display, PartialEq, Eq)] +#[derive(Clone, Debug, Display, From, PartialEq, Eq)] pub enum ProviderError { /// Database error. Database(DatabaseError), /// RLP error. Rlp(alloy_rlp::Error), /// Filesystem path error. + #[from(ignore)] #[display(fmt = "{_0}")] FsPathError(String), /// Nippy jar error. + #[from(ignore)] #[display(fmt = "nippy jar error: {_0}")] NippyJar(String), /// Trie witness error. + #[from(ignore)] #[display(fmt = "trie witness error: {_0}")] TrieWitnessError(String), /// Error when recovering the sender for a transaction #[display(fmt = "failed to recover sender for transaction")] SenderRecoveryError, /// The header number was not found for the given block hash. + #[from(ignore)] #[display(fmt = "block hash {_0} does not exist in Headers table")] BlockHashNotFound(BlockHash), /// A block body is missing. + #[from(ignore)] #[display(fmt = "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. + #[from(ignore)] #[display(fmt = "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. @@ -54,6 +57,7 @@ pub enum ProviderError { storage_key: Box, }, /// The block number was found for the given address, but the changeset was not found. + #[from(ignore)] #[display(fmt = "account change set for address {address} at block #{block_number} does not exist")] AccountChangesetNotFound { /// Block number found for the address. @@ -62,15 +66,19 @@ pub enum ProviderError { address: Address, }, /// The total difficulty for a block is missing. + #[from(ignore)] #[display(fmt = "total difficulty not found for block #{_0}")] TotalDifficultyNotFound(BlockNumber), /// when required header related data was not found but was required. + #[from(ignore)] #[display(fmt = "no header found for {_0:?}")] HeaderNotFound(BlockHashOrNumber), /// The specific transaction is missing. + #[from(ignore)] #[display(fmt = "no transaction found for {_0:?}")] TransactionNotFound(TxHashOrNumber), /// The specific receipt is missing + #[from(ignore)] #[display(fmt = "no receipt found for {_0:?}")] ReceiptNotFound(TxHashOrNumber), /// Unable to find the best block. @@ -83,6 +91,7 @@ pub enum ProviderError { #[display(fmt = "safe block does not exist")] SafeBlockNotFound, /// Mismatch of sender and transaction. + #[from(ignore)] #[display(fmt = "mismatch of sender and transaction id {tx_id}")] MismatchOfTransactionAndSenderId { /// The transaction ID. @@ -95,21 +104,25 @@ pub enum ProviderError { #[display(fmt = "cache service task stopped")] CacheServiceUnavailable, /// Thrown when we failed to lookup a block for the pending state. + #[from(ignore)] #[display(fmt = "unknown block {_0}")] UnknownBlockHash(B256), /// Thrown when we were unable to find a state for a block hash. + #[from(ignore)] #[display(fmt = "no state found for block {_0}")] StateForHashNotFound(B256), /// Unable to find the block number for a given transaction index. #[display(fmt = "unable to find the block number for a given transaction index")] BlockNumberForTransactionIndexNotFound, /// Root mismatch. + #[from(ignore)] #[display(fmt = "merkle trie {_0}")] StateRootMismatch(Box), /// Root mismatch during unwind #[display(fmt = "unwind merkle trie {_0}")] UnwindStateRootMismatch(Box), /// State is not available for the given block number because it is pruned. + #[from(ignore)] #[display(fmt = "state at block #{_0} is pruned")] StateAtBlockPruned(BlockNumber), /// Provider does not support this particular request. @@ -120,21 +133,26 @@ pub enum ProviderError { #[display(fmt = "not able to find {_0} static file at {_1:?}")] MissingStaticFilePath(StaticFileSegment, PathBuf), /// Static File is not found for requested block. + #[from(ignore)] #[display(fmt = "not able to find {_0} static file for block number {_1}")] MissingStaticFileBlock(StaticFileSegment, BlockNumber), /// Static File is not found for requested transaction. + #[from(ignore)] #[display(fmt = "unable to find {_0} static file for transaction id {_1}")] MissingStaticFileTx(StaticFileSegment, TxNumber), /// Static File is finalized and cannot be written to. + #[from(ignore)] #[display(fmt = "unable to write block #{_1} to finalized static file {_0}")] FinalizedStaticFile(StaticFileSegment, BlockNumber), /// Trying to insert data from an unexpected block number. + #[from(ignore)] #[display(fmt = "trying to append data to {_0} as block #{_1} but expected block #{_2}")] UnexpectedStaticFileBlockNumber(StaticFileSegment, BlockNumber, BlockNumber), /// Static File Provider was initialized as read-only. #[display(fmt = "cannot get a writer on a read-only environment.")] ReadOnlyStaticFileAccess, /// Error encountered when the block number conversion from U256 to u64 causes an overflow. + #[from(ignore)] #[display(fmt = "failed to convert block number U256 to u64: {_0}")] BlockNumberOverflow(U256), /// Consistent view error. @@ -167,36 +185,6 @@ impl std::error::Error for ProviderError { } } -impl From for ProviderError { - fn from(value: DatabaseError) -> Self { - Self::Database(value) - } -} - -impl From for ProviderError { - fn from(value: alloy_rlp::Error) -> Self { - Self::Rlp(value) - } -} - -impl From for ProviderError { - fn from(value: StorageLockError) -> Self { - Self::StorageLockError(value) - } -} - -impl From for ProviderError { - fn from(value: UnifiedStorageWriterError) -> Self { - Self::UnifiedStorageWriterError(value) - } -} - -impl From for ProviderError { - fn from(err: reth_fs_util::FsPathError) -> Self { - Self::FsPathError(err.to_string()) - } -} - /// A root mismatch error at a given block height. #[derive(Clone, Debug, PartialEq, Eq, derive_more::Display)] #[display(fmt = "root mismatch at #{block_number} ({block_hash}): {root}")] @@ -210,7 +198,7 @@ pub struct RootMismatch { } /// Consistent database view error. -#[derive(Clone, Debug, PartialEq, Eq, derive_more::Display)] +#[derive(Clone, Debug, PartialEq, Eq, Display, From)] pub enum ConsistentViewError { /// Error thrown on attempt to initialize provider while node is still syncing. #[display(fmt = "node is syncing. best block: {best_block:?}")] From 27fe6602de6222f9c553d55969f5b9b4beea0a54 Mon Sep 17 00:00:00 2001 From: Jorge Martinez Date: Thu, 8 Aug 2024 18:12:59 -0700 Subject: [PATCH 09/10] removed #[from] attributes and manually implemented from traits --- crates/storage/errors/src/provider.rs | 59 ++++++++++++++------------- 1 file changed, 31 insertions(+), 28 deletions(-) diff --git a/crates/storage/errors/src/provider.rs b/crates/storage/errors/src/provider.rs index 3f521bc19ca3..72256d47c8b1 100644 --- a/crates/storage/errors/src/provider.rs +++ b/crates/storage/errors/src/provider.rs @@ -2,9 +2,9 @@ use reth_primitives::{ Address, BlockHash, BlockHashOrNumber, BlockNumber, GotExpected, StaticFileSegment, TxHashOrNumber, TxNumber, B256, U256, }; -use derive_more::{Display, From}; +use derive_more::Display; use alloc::{boxed::Box, string::String}; -use crate::db::DatabaseError; +use crate::{db::DatabaseError, lockfile::StorageLockError, writer::UnifiedStorageWriterError}; #[cfg(feature = "std")] use std::path::PathBuf; @@ -13,38 +13,32 @@ use std::path::PathBuf; pub type ProviderResult = Result; /// Bundled errors variants thrown by various providers. -#[derive(Clone, Debug, Display, From, PartialEq, Eq)] +#[derive(Clone, Debug, Display, PartialEq, Eq)] pub enum ProviderError { /// Database error. Database(DatabaseError), /// RLP error. Rlp(alloy_rlp::Error), /// Filesystem path error. - #[from(ignore)] #[display(fmt = "{_0}")] FsPathError(String), /// Nippy jar error. - #[from(ignore)] #[display(fmt = "nippy jar error: {_0}")] NippyJar(String), /// Trie witness error. - #[from(ignore)] #[display(fmt = "trie witness error: {_0}")] TrieWitnessError(String), /// Error when recovering the sender for a transaction #[display(fmt = "failed to recover sender for transaction")] SenderRecoveryError, /// The header number was not found for the given block hash. - #[from(ignore)] #[display(fmt = "block hash {_0} does not exist in Headers table")] BlockHashNotFound(BlockHash), /// A block body is missing. - #[from(ignore)] #[display(fmt = "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. - #[from(ignore)] #[display(fmt = "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. @@ -57,7 +51,6 @@ pub enum ProviderError { storage_key: Box, }, /// The block number was found for the given address, but the changeset was not found. - #[from(ignore)] #[display(fmt = "account change set for address {address} at block #{block_number} does not exist")] AccountChangesetNotFound { /// Block number found for the address. @@ -66,19 +59,15 @@ pub enum ProviderError { address: Address, }, /// The total difficulty for a block is missing. - #[from(ignore)] #[display(fmt = "total difficulty not found for block #{_0}")] TotalDifficultyNotFound(BlockNumber), /// when required header related data was not found but was required. - #[from(ignore)] #[display(fmt = "no header found for {_0:?}")] HeaderNotFound(BlockHashOrNumber), /// The specific transaction is missing. - #[from(ignore)] #[display(fmt = "no transaction found for {_0:?}")] TransactionNotFound(TxHashOrNumber), /// The specific receipt is missing - #[from(ignore)] #[display(fmt = "no receipt found for {_0:?}")] ReceiptNotFound(TxHashOrNumber), /// Unable to find the best block. @@ -91,7 +80,6 @@ pub enum ProviderError { #[display(fmt = "safe block does not exist")] SafeBlockNotFound, /// Mismatch of sender and transaction. - #[from(ignore)] #[display(fmt = "mismatch of sender and transaction id {tx_id}")] MismatchOfTransactionAndSenderId { /// The transaction ID. @@ -104,25 +92,21 @@ pub enum ProviderError { #[display(fmt = "cache service task stopped")] CacheServiceUnavailable, /// Thrown when we failed to lookup a block for the pending state. - #[from(ignore)] #[display(fmt = "unknown block {_0}")] UnknownBlockHash(B256), /// Thrown when we were unable to find a state for a block hash. - #[from(ignore)] #[display(fmt = "no state found for block {_0}")] StateForHashNotFound(B256), /// Unable to find the block number for a given transaction index. #[display(fmt = "unable to find the block number for a given transaction index")] BlockNumberForTransactionIndexNotFound, /// Root mismatch. - #[from(ignore)] #[display(fmt = "merkle trie {_0}")] StateRootMismatch(Box), /// Root mismatch during unwind #[display(fmt = "unwind merkle trie {_0}")] UnwindStateRootMismatch(Box), /// State is not available for the given block number because it is pruned. - #[from(ignore)] #[display(fmt = "state at block #{_0} is pruned")] StateAtBlockPruned(BlockNumber), /// Provider does not support this particular request. @@ -133,35 +117,54 @@ pub enum ProviderError { #[display(fmt = "not able to find {_0} static file at {_1:?}")] MissingStaticFilePath(StaticFileSegment, PathBuf), /// Static File is not found for requested block. - #[from(ignore)] #[display(fmt = "not able to find {_0} static file for block number {_1}")] MissingStaticFileBlock(StaticFileSegment, BlockNumber), /// Static File is not found for requested transaction. - #[from(ignore)] #[display(fmt = "unable to find {_0} static file for transaction id {_1}")] MissingStaticFileTx(StaticFileSegment, TxNumber), /// Static File is finalized and cannot be written to. - #[from(ignore)] #[display(fmt = "unable to write block #{_1} to finalized static file {_0}")] FinalizedStaticFile(StaticFileSegment, BlockNumber), /// Trying to insert data from an unexpected block number. - #[from(ignore)] #[display(fmt = "trying to append data to {_0} as block #{_1} but expected block #{_2}")] UnexpectedStaticFileBlockNumber(StaticFileSegment, BlockNumber, BlockNumber), /// Static File Provider was initialized as read-only. #[display(fmt = "cannot get a writer on a read-only environment.")] ReadOnlyStaticFileAccess, /// Error encountered when the block number conversion from U256 to u64 causes an overflow. - #[from(ignore)] #[display(fmt = "failed to convert block number U256 to u64: {_0}")] BlockNumberOverflow(U256), /// Consistent view error. #[display(fmt = "failed to initialize consistent view: {_0}")] ConsistentView(Box), /// Storage lock error. - StorageLockError(crate::lockfile::StorageLockError), + StorageLockError(StorageLockError), /// Storage writer error. - UnifiedStorageWriterError(crate::writer::UnifiedStorageWriterError), + UnifiedStorageWriterError(UnifiedStorageWriterError), +} + +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) + } } #[cfg(feature = "std")] @@ -186,7 +189,7 @@ impl std::error::Error for ProviderError { } /// A root mismatch error at a given block height. -#[derive(Clone, Debug, PartialEq, Eq, derive_more::Display)] +#[derive(Clone, Debug, PartialEq, Eq, Display)] #[display(fmt = "root mismatch at #{block_number} ({block_hash}): {root}")] pub struct RootMismatch { /// The target block root diff. @@ -198,7 +201,7 @@ pub struct RootMismatch { } /// Consistent database view error. -#[derive(Clone, Debug, PartialEq, Eq, Display, From)] +#[derive(Clone, Debug, PartialEq, Eq, Display)] pub enum ConsistentViewError { /// Error thrown on attempt to initialize provider while node is still syncing. #[display(fmt = "node is syncing. best block: {best_block:?}")] From 6c655611da1fd8ce77224e7b67e80a60d947d885 Mon Sep 17 00:00:00 2001 From: Jorge Martinez Date: Mon, 12 Aug 2024 18:58:32 -0700 Subject: [PATCH 10/10] fmt, feature gates, cleanup --- crates/storage/errors/src/db.rs | 45 ++++++++++++++------------- crates/storage/errors/src/lib.rs | 1 + crates/storage/errors/src/lockfile.rs | 10 ++++-- crates/storage/errors/src/provider.rs | 38 +++++++++++----------- crates/storage/errors/src/writer.rs | 16 +++++----- 5 files changed, 56 insertions(+), 54 deletions(-) diff --git a/crates/storage/errors/src/db.rs b/crates/storage/errors/src/db.rs index b69a4674fc52..a2cbcba33ced 100644 --- a/crates/storage/errors/src/db.rs +++ b/crates/storage/errors/src/db.rs @@ -1,10 +1,19 @@ +#[cfg(feature = "std")] +use std::{fmt, fmt::Display, str::FromStr, string::String}; + +#[cfg(not(feature = "std"))] use alloc::{ boxed::Box, format, string::{String, ToString}, vec::Vec, }; -use core::{fmt, fmt::{Display, Debug}, str::FromStr}; +#[cfg(not(feature = "std"))] +use core::{ + fmt, + fmt::{Debug, Display}, + str::FromStr, +}; /// Database error type. #[derive(Clone, Debug, PartialEq, Eq, derive_more::Display)] @@ -50,10 +59,8 @@ pub enum DatabaseError { impl std::error::Error for DatabaseError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { - Self::Write(err) => { - std::error::Error::source(err) - }, - _ => Option::None + Self::Write(err) => std::error::Error::source(err), + _ => Option::None, } } } @@ -73,15 +80,15 @@ where E: Display + Into, { #[inline] - fn from(value: E) -> Self { - Self { message: value.to_string(), code: value.into() } + fn from(error: E) -> Self { + Self { message: error.to_string(), code: error.into() } } } impl From for DatabaseError { #[inline] - fn from(value: DatabaseWriteError) -> Self { - Self::Write(Box::new(value)) + fn from(error: DatabaseWriteError) -> Self { + Self::Write(Box::new(error)) } } @@ -101,12 +108,12 @@ pub struct DatabaseWriteError { 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, - reth_primitives::hex::encode(&self.key), - self.table_name, - self.info + f, + "write operation {:?} failed for key \"{}\" in table {}: {}", + self.operation, + reth_primitives::hex::encode(&self.key), + self.table_name, + self.info ) } } @@ -115,23 +122,17 @@ impl fmt::Display for DatabaseWriteError { impl std::error::Error for DatabaseWriteError {} /// Database write operation type. -#[derive(Clone, Copy, Debug, PartialEq, Eq, derive_more::Display)] -#[display(fmt = "DatabaseWriteOperation: {}")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DatabaseWriteOperation { /// Append cursor. - #[display(fmt = "CursorAppend")] CursorAppend, /// Upsert cursor. - #[display(fmt = "CursorUpsert")] CursorUpsert, /// Insert cursor. - #[display(fmt = "CursorInsert")] CursorInsert, /// Append duplicate cursor. - #[display(fmt = "CursorAppendDup")] CursorAppendDup, /// Put. - #[display(fmt = "Put")] Put, } diff --git a/crates/storage/errors/src/lib.rs b/crates/storage/errors/src/lib.rs index 6abb0cd9b425..cf1a1a97627a 100644 --- a/crates/storage/errors/src/lib.rs +++ b/crates/storage/errors/src/lib.rs @@ -9,6 +9,7 @@ #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] #![cfg_attr(not(feature = "std"), no_std)] +#[cfg(not(feature = "std"))] extern crate alloc; /// Database error diff --git a/crates/storage/errors/src/lockfile.rs b/crates/storage/errors/src/lockfile.rs index fdc3bb274eb7..ede10401a20c 100644 --- a/crates/storage/errors/src/lockfile.rs +++ b/crates/storage/errors/src/lockfile.rs @@ -1,11 +1,15 @@ use reth_fs_util::FsPathError; + +#[cfg(not(feature = "std"))] use alloc::string::{String, ToString}; /// Storage lock error. #[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)] pub enum StorageLockError { /// Write lock taken - #[display(fmt = "storage directory is currently in use as read-write by another process: PID {_0}")] + #[display( + fmt = "storage directory is currently in use as read-write by another process: PID {_0}" + )] Taken(usize), /// Indicates other unspecified errors. #[display(fmt = "{_0}")] @@ -17,7 +21,7 @@ impl std::error::Error for StorageLockError {} /// TODO: turn into variant once `ProviderError` impl From for StorageLockError { - fn from(source: FsPathError) -> Self { - Self::Other(source.to_string()) + fn from(error: FsPathError) -> Self { + Self::Other(error.to_string()) } } diff --git a/crates/storage/errors/src/provider.rs b/crates/storage/errors/src/provider.rs index 72256d47c8b1..cd3a07a8e4ff 100644 --- a/crates/storage/errors/src/provider.rs +++ b/crates/storage/errors/src/provider.rs @@ -1,14 +1,16 @@ +use crate::{db::DatabaseError, lockfile::StorageLockError, writer::UnifiedStorageWriterError}; +use derive_more::Display; use reth_primitives::{ Address, BlockHash, BlockHashOrNumber, BlockNumber, GotExpected, StaticFileSegment, TxHashOrNumber, TxNumber, B256, U256, }; -use derive_more::Display; -use alloc::{boxed::Box, string::String}; -use crate::{db::DatabaseError, lockfile::StorageLockError, writer::UnifiedStorageWriterError}; #[cfg(feature = "std")] use std::path::PathBuf; +#[cfg(not(feature = "std"))] +use alloc::{boxed::Box, string::String}; + /// Provider result type. pub type ProviderResult = Result; @@ -39,7 +41,9 @@ pub enum ProviderError { BlockBodyIndicesNotFound(BlockNumber), /// The transition ID was found for the given address and storage key, but the changeset was /// not found. - #[display(fmt = "storage change set for address {address} and key {storage_key} at block #{block_number} does not exist")] + #[display( + fmt = "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, @@ -51,7 +55,9 @@ pub enum ProviderError { storage_key: Box, }, /// The block number was found for the given address, but the changeset was not found. - #[display(fmt = "account change set for address {address} at block #{block_number} does not exist")] + #[display( + fmt = "account change set for address {address} at block #{block_number} does not exist" + )] AccountChangesetNotFound { /// Block number found for the address. block_number: BlockNumber, @@ -171,19 +177,11 @@ impl From for ProviderError { impl std::error::Error for ProviderError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { - Self::Database(source) => { - std::error::Error::source(source) - }, - Self::Rlp(source) => { - std::error::Error::source(source) - }, - Self::StorageLockError(source) => { - std::error::Error::source(source) - }, - Self::UnifiedStorageWriterError(source) => { - std::error::Error::source(source) - }, - _ => Option::None + Self::Database(source) => std::error::Error::source(source), + Self::Rlp(source) => std::error::Error::source(source), + Self::StorageLockError(source) => std::error::Error::source(source), + Self::UnifiedStorageWriterError(source) => std::error::Error::source(source), + _ => Option::None, } } } @@ -218,7 +216,7 @@ pub enum ConsistentViewError { } impl From for ProviderError { - fn from(value: ConsistentViewError) -> Self { - Self::ConsistentView(Box::new(value)) + fn from(error: ConsistentViewError) -> Self { + Self::ConsistentView(Box::new(error)) } } diff --git a/crates/storage/errors/src/writer.rs b/crates/storage/errors/src/writer.rs index 858f53741801..e5317043c8d4 100644 --- a/crates/storage/errors/src/writer.rs +++ b/crates/storage/errors/src/writer.rs @@ -21,17 +21,15 @@ pub enum UnifiedStorageWriterError { #[cfg(feature = "std")] impl std::error::Error for UnifiedStorageWriterError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Self::Database(source) => { - std::error::Error::source(source) - }, - _ => Option::None - } + match self { + Self::Database(source) => std::error::Error::source(source), + _ => Option::None, + } } } impl From for UnifiedStorageWriterError { - fn from(value: DatabaseError) -> Self { - Self::Database(value) + fn from(error: DatabaseError) -> Self { + Self::Database(error) } -} \ No newline at end of file +}