Skip to content

Commit

Permalink
implemented thiserror
Browse files Browse the repository at this point in the history
  • Loading branch information
PelleKrab committed Dec 12, 2024
1 parent e775325 commit f7606bf
Show file tree
Hide file tree
Showing 13 changed files with 159 additions and 254 deletions.
77 changes: 14 additions & 63 deletions crates/blockchain-tree-api/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand All @@ -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<B: Block> {
block: SealedBlockFor<B>,
#[source]
kind: InsertBlockErrorKindTwo,
}

impl<B: Block> std::fmt::Display for InsertBlockErrorDataTwo<B> {
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<B: Block> std::fmt::Debug for InsertBlockErrorDataTwo<B> {
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<B: Block> core::error::Error for InsertBlockErrorDataTwo<B> {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
Some(&self.kind)
}
}

impl<B: Block> InsertBlockErrorDataTwo<B> {
const fn new(block: SealedBlockFor<B>, kind: InsertBlockErrorKindTwo) -> Self {
Self { block, kind }
Expand Down
1 change: 1 addition & 0 deletions crates/optimism/chainspec/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
15 changes: 4 additions & 11 deletions crates/optimism/chainspec/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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:
/// <https://github.com/ethereum-optimism/specs/blob/main/specs/protocol/holocene/exec-engine.md#eip1559params-encoding>
pub fn decode_holocene_1559_params(extra_data: &[u8]) -> Result<(u32, u32), DecodeError> {
Expand Down
1 change: 1 addition & 0 deletions crates/optimism/evm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand Down
20 changes: 9 additions & 11 deletions crates/optimism/evm/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<OpBlockExecutionError> 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),
}
1 change: 1 addition & 0 deletions crates/primitives-traits/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
33 changes: 5 additions & 28 deletions crates/primitives-traits/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,16 @@
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<T> {
/// The actual value.
pub got: T,
/// The expected value.
pub expected: T,
}

impl<T: fmt::Display> fmt::Display for GotExpected<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "got {}, expected {}", self.got, self.expected)
}
}

impl<T: fmt::Debug + fmt::Display> core::error::Error for GotExpected<T> {}

impl<T> From<(T, T)> for GotExpected<T> {
#[inline]
fn from((got, expected): (T, T)) -> Self {
Expand All @@ -41,23 +31,10 @@ impl<T> GotExpected<T> {
/// 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<T>(pub Box<GotExpected<T>>);

impl<T: fmt::Debug> fmt::Debug for GotExpectedBoxed<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}

impl<T: fmt::Display> fmt::Display for GotExpectedBoxed<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}

impl<T: fmt::Debug + fmt::Display> core::error::Error for GotExpectedBoxed<T> {}

impl<T> Deref for GotExpectedBoxed<T> {
type Target = GotExpected<T>;

Expand Down
42 changes: 19 additions & 23 deletions crates/primitives-traits/src/transaction/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,67 +4,65 @@ 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<U256>),
/// 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,
/// The current state of the nonce in the local chain.
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)]
Expand All @@ -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 {}
4 changes: 1 addition & 3 deletions crates/rpc/rpc-eth-types/src/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,7 @@ impl From<reth_primitives::InvalidTransactionError> 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
///
Expand Down Expand Up @@ -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 {
Expand Down
1 change: 1 addition & 0 deletions crates/storage/errors/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ alloy-rlp.workspace = true

# misc
derive_more.workspace = true
thiserror.workspace = true

[features]
default = ["std"]
Expand Down
Loading

0 comments on commit f7606bf

Please sign in to comment.