Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: improve error implementations #1183

Merged
merged 1 commit into from
Mar 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 15 additions & 15 deletions crates/primitives/src/kzg/trusted_setup_points.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
pub use c_kzg::{BYTES_PER_G1_POINT, BYTES_PER_G2_POINT};
use core::fmt::Display;
use core::fmt;
use derive_more::{AsMut, AsRef, Deref, DerefMut};
use std::boxed::Box;

pub use c_kzg::{BYTES_PER_G1_POINT, BYTES_PER_G2_POINT};

/// Number of G1 Points.
pub const NUM_G1_POINTS: usize = 4096;

Expand Down Expand Up @@ -113,19 +114,18 @@ pub enum KzgErrors {
MismatchedNumberOfPoints,
}

impl Display for KzgErrors {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
KzgErrors::FailedCurrentDirectory => write!(f, "Failed to get current directory"),
KzgErrors::PathNotExists => write!(f, "The specified path does not exist"),
KzgErrors::IOError => write!(f, "Problems related to I/O"),
KzgErrors::NotValidFile => write!(f, "Not a valid file"),
KzgErrors::FileFormatError => write!(f, "File is not properly formatted"),
KzgErrors::ParseError => write!(f, "Not able to parse to usize"),
KzgErrors::MismatchedNumberOfPoints => {
write!(f, "Number of points does not match what is expected")
}
}
impl fmt::Display for KzgErrors {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Self::FailedCurrentDirectory => "failed to get current directory",
Self::PathNotExists => "the specified path does not exist",
Self::IOError => "IO error",
Self::NotValidFile => "not a valid file",
Self::FileFormatError => "file is not properly formatted",
Self::ParseError => "could not parse as usize",
Self::MismatchedNumberOfPoints => "number of points does not match what is expected",
};
f.write_str(s)
}
}

Expand Down
41 changes: 16 additions & 25 deletions crates/primitives/src/precompile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,31 +140,22 @@ impl std::error::Error for PrecompileError {}

impl fmt::Display for PrecompileError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PrecompileError::OutOfGas => write!(f, "out of gas"),
PrecompileError::Blake2WrongLength => write!(f, "wrong input length for blake2"),
PrecompileError::Blake2WrongFinalIndicatorFlag => {
write!(f, "wrong final indicator flag for blake2")
}
PrecompileError::ModexpExpOverflow => write!(f, "modexp exp overflow"),
PrecompileError::ModexpBaseOverflow => write!(f, "modexp base overflow"),
PrecompileError::ModexpModOverflow => write!(f, "modexp mod overflow"),
PrecompileError::Bn128FieldPointNotAMember => {
write!(f, "field point not a member of bn128 curve")
}
PrecompileError::Bn128AffineGFailedToCreate => {
write!(f, "failed to create affine g point for bn128 curve")
}
PrecompileError::Bn128PairLength => write!(f, "bn128 invalid pair length"),
PrecompileError::BlobInvalidInputLength => write!(f, "invalid blob input length"),
PrecompileError::BlobMismatchedVersion => write!(f, "mismatched blob version"),
PrecompileError::BlobVerifyKzgProofFailed => {
write!(f, "verifying blob kzg proof failed")
}
PrecompileError::Other(why) => {
write!(f, "other precompile error: {why}")
}
}
let s = match self {
Self::OutOfGas => "out of gas",
Self::Blake2WrongLength => "wrong input length for blake2",
Self::Blake2WrongFinalIndicatorFlag => "wrong final indicator flag for blake2",
Self::ModexpExpOverflow => "modexp exp overflow",
Self::ModexpBaseOverflow => "modexp base overflow",
Self::ModexpModOverflow => "modexp mod overflow",
Self::Bn128FieldPointNotAMember => "field point not a member of bn128 curve",
Self::Bn128AffineGFailedToCreate => "failed to create affine g point for bn128 curve",
Self::Bn128PairLength => "bn128 invalid pair length",
Self::BlobInvalidInputLength => "invalid blob input length",
Self::BlobMismatchedVersion => "mismatched blob version",
Self::BlobVerifyKzgProofFailed => "verifying blob kzg proof failed",
Self::Other(s) => s,
};
f.write_str(s)
}
}

Expand Down
117 changes: 62 additions & 55 deletions crates/primitives/src/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,22 +151,37 @@ pub enum EVMError<DBError> {
}

#[cfg(feature = "std")]
impl<DBError: fmt::Debug + fmt::Display> std::error::Error for EVMError<DBError> {}
impl<DBError: std::error::Error + 'static> std::error::Error for EVMError<DBError> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Transaction(e) => Some(e),
Self::Header(e) => Some(e),
Self::Database(e) => Some(e),
Self::Custom(_) => None,
}
}
}

impl<DBError: fmt::Display> fmt::Display for EVMError<DBError> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
EVMError::Transaction(e) => write!(f, "Transaction error: {e:?}"),
EVMError::Header(e) => write!(f, "Header error: {e:?}"),
EVMError::Database(e) => write!(f, "Database error: {e}"),
EVMError::Custom(e) => write!(f, "Custom error: {e}"),
Self::Transaction(e) => write!(f, "transaction validation error: {e}"),
Self::Header(e) => write!(f, "header validation error: {e}"),
Self::Database(e) => write!(f, "database error: {e}"),
Self::Custom(e) => f.write_str(e),
}
}
}

impl<DBError> From<InvalidTransaction> for EVMError<DBError> {
fn from(invalid: InvalidTransaction) -> Self {
EVMError::Transaction(invalid)
fn from(value: InvalidTransaction) -> Self {
Self::Transaction(value)
}
}

impl<DBError> From<InvalidHeader> for EVMError<DBError> {
fn from(value: InvalidHeader) -> Self {
Self::Header(value)
}
}

Expand Down Expand Up @@ -270,80 +285,72 @@ impl std::error::Error for InvalidTransaction {}
impl fmt::Display for InvalidTransaction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
InvalidTransaction::PriorityFeeGreaterThanMaxFee => {
write!(f, "Priority fee is greater than max fee")
}
InvalidTransaction::GasPriceLessThanBasefee => {
write!(f, "Gas price is less than basefee")
Self::PriorityFeeGreaterThanMaxFee => {
write!(f, "priority fee is greater than max fee")
}
InvalidTransaction::CallerGasLimitMoreThanBlock => {
write!(f, "Caller gas limit exceeds the block gas limit")
Self::GasPriceLessThanBasefee => {
write!(f, "gas price is less than basefee")
}
InvalidTransaction::CallGasCostMoreThanGasLimit => {
write!(f, "Call gas cost exceeds the gas limit")
Self::CallerGasLimitMoreThanBlock => {
write!(f, "caller gas limit exceeds the block gas limit")
}
InvalidTransaction::RejectCallerWithCode => {
write!(f, "Reject transactions from senders with deployed code")
Self::CallGasCostMoreThanGasLimit => {
write!(f, "call gas cost exceeds the gas limit")
}
InvalidTransaction::LackOfFundForMaxFee { fee, balance } => {
write!(f, "Lack of funds {} for max fee {}", balance, fee)
Self::RejectCallerWithCode => {
write!(f, "reject transactions from senders with deployed code")
}
InvalidTransaction::OverflowPaymentInTransaction => {
write!(f, "Overflow payment in transaction")
Self::LackOfFundForMaxFee { fee, balance } => {
write!(f, "lack of funds ({balance}) for max fee ({fee})")
}
InvalidTransaction::NonceOverflowInTransaction => {
write!(f, "Nonce overflow in transaction")
Self::OverflowPaymentInTransaction => {
write!(f, "overflow payment in transaction")
}
InvalidTransaction::NonceTooHigh { tx, state } => {
write!(f, "Nonce too high {}, expected {}", tx, state)
Self::NonceOverflowInTransaction => {
write!(f, "nonce overflow in transaction")
}
InvalidTransaction::NonceTooLow { tx, state } => {
write!(f, "Nonce {} too low, expected {}", tx, state)
Self::NonceTooHigh { tx, state } => {
write!(f, "nonce {tx} too high, expected {state}")
}
InvalidTransaction::CreateInitCodeSizeLimit => {
write!(f, "Create initcode size limit")
Self::NonceTooLow { tx, state } => {
write!(f, "nonce {tx} too low, expected {state}")
}
InvalidTransaction::InvalidChainId => write!(f, "Invalid chain id"),
InvalidTransaction::AccessListNotSupported => {
write!(f, "Access list not supported")
Self::CreateInitCodeSizeLimit => {
write!(f, "create initcode size limit")
}
InvalidTransaction::MaxFeePerBlobGasNotSupported => {
write!(f, "Max fee per blob gas not supported")
Self::InvalidChainId => write!(f, "invalid chain ID"),
Self::AccessListNotSupported => write!(f, "access list not supported"),
Self::MaxFeePerBlobGasNotSupported => {
write!(f, "max fee per blob gas not supported")
}
InvalidTransaction::BlobVersionedHashesNotSupported => {
write!(f, "Blob versioned hashes not supported")
Self::BlobVersionedHashesNotSupported => {
write!(f, "blob versioned hashes not supported")
}
InvalidTransaction::BlobGasPriceGreaterThanMax => {
write!(f, "Blob gas price is greater than max fee per blob gas")
Self::BlobGasPriceGreaterThanMax => {
write!(f, "blob gas price is greater than max fee per blob gas")
}
InvalidTransaction::EmptyBlobs => write!(f, "Empty blobs"),
InvalidTransaction::BlobCreateTransaction => write!(f, "Blob create transaction"),
InvalidTransaction::TooManyBlobs => write!(f, "Too many blobs"),
InvalidTransaction::BlobVersionNotSupported => write!(f, "Blob version not supported"),
Self::EmptyBlobs => write!(f, "empty blobs"),
Self::BlobCreateTransaction => write!(f, "blob create transaction"),
Self::TooManyBlobs => write!(f, "too many blobs"),
Self::BlobVersionNotSupported => write!(f, "blob version not supported"),
#[cfg(feature = "optimism")]
InvalidTransaction::DepositSystemTxPostRegolith => {
Self::DepositSystemTxPostRegolith => {
write!(
f,
"Deposit system transactions post regolith hardfork are not supported"
"deposit system transactions post regolith hardfork are not supported"
)
}
#[cfg(feature = "optimism")]
InvalidTransaction::HaltedDepositPostRegolith => {
Self::HaltedDepositPostRegolith => {
write!(
f,
"Deposit transaction halted post-regolith. Error will be bubbled up to main return handler."
"deposit transaction halted post-regolith; error will be bubbled up to main return handler"
)
}
}
}
}

impl<DBError> From<InvalidHeader> for EVMError<DBError> {
fn from(invalid: InvalidHeader) -> Self {
EVMError::Header(invalid)
}
}

/// Errors related to misconfiguration of a [`crate::env::BlockEnv`].
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
Expand All @@ -360,8 +367,8 @@ impl std::error::Error for InvalidHeader {}
impl fmt::Display for InvalidHeader {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
InvalidHeader::PrevrandaoNotSet => write!(f, "Prevrandao not set"),
InvalidHeader::ExcessBlobGasNotSet => write!(f, "Excess blob gas not set"),
Self::PrevrandaoNotSet => write!(f, "`prevrandao` not set"),
Self::ExcessBlobGasNotSet => write!(f, "`excess_blob_gas` not set"),
}
}
}
Expand Down
Loading