Skip to content

Commit

Permalink
Merge pull request #12 from HerodotusDev/error
Browse files Browse the repository at this point in the history
error unify with `thisiserror`
  • Loading branch information
rkdud007 authored Jun 26, 2024
2 parents e2b4606 + 8e0f71a commit 6a6717d
Show file tree
Hide file tree
Showing 9 changed files with 137 additions and 85 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ clap = { version = "4.5.4", features = ["derive"] }
serde = "1.0.197"
serde_with = { version = "3.7.0", features = ["hex"] }
serde_json = "1.0.114"
thiserror = "1.0"

[[bin]]
name = "etp-cli"
Expand Down
8 changes: 4 additions & 4 deletions src/bin/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use serde::Serialize;
use serde_with::serde_as;

use eth_trie_proofs::tx_receipt_trie::TxReceiptsMptHandler;
use eth_trie_proofs::Error;
use eth_trie_proofs::EthTrieError;

#[derive(Debug, Parser)]
#[command(name = "eth-trie-proof")]
Expand Down Expand Up @@ -45,7 +45,7 @@ struct MptProof {
}

#[tokio::main]
async fn main() -> Result<(), Error> {
async fn main() -> Result<(), EthTrieError> {
let cli = Cli::parse();
match cli.command {
Commands::Tx { tx_hash, rpc_url } => {
Expand All @@ -71,7 +71,7 @@ async fn main() -> Result<(), Error> {
Ok(())
}

async fn generate_tx_proof(tx_hash: &str, rpc_url: &str) -> Result<(), Error> {
async fn generate_tx_proof(tx_hash: &str, rpc_url: &str) -> Result<(), EthTrieError> {
let rpc_url = url::Url::parse(rpc_url).expect("Invalid URL");
let mut txs_mpt_handler = TxsMptHandler::new(rpc_url)?;
let tx_hash = B256::from_hex(tx_hash).unwrap();
Expand All @@ -86,7 +86,7 @@ async fn generate_tx_proof(tx_hash: &str, rpc_url: &str) -> Result<(), Error> {
Ok(())
}

async fn generate_receipt_proof(tx_hash: &str, rpc_url: &str) -> Result<(), Error> {
async fn generate_receipt_proof(tx_hash: &str, rpc_url: &str) -> Result<(), EthTrieError> {
let rpc_url = url::Url::parse(rpc_url).expect("Invalid URL");
let mut tx_receipts_mpt_handler = TxReceiptsMptHandler::new(rpc_url)?;
let tx_hash = B256::from_hex(tx_hash).unwrap();
Expand Down
40 changes: 36 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,40 @@
use core::fmt;

use alloy::transports::{RpcError, TransportErrorKind};
use eth_trie::TrieError;
use thiserror::Error;

mod rpc;
pub mod tx;
pub mod tx_receipt;
pub mod tx_receipt_trie;
pub mod tx_trie;

#[derive(Debug)]
pub enum Error {
#[derive(Error, Debug)]
pub enum EthTrieError {
#[error("Trie error: {0}")]
Trie(TrieError),
#[error("EIP error: {0}")]
Eip(alloy::eips::eip2718::Eip2718Error),
#[error("RLP error: {0}")]
Rlp(alloy_rlp::Error),
#[error("RPC error: {0}")]
RPC(RpcError<TransportErrorKind>),
#[error("Transaction not found")]
TxNotFound,
#[error("Block not found")]
BlockNotFound,
#[error("Invalid transaction version")]
InvalidTxVersion,
#[error("Error converting field: {0}")]
ConversionError(Field),
#[error("Unexpected root")]
UnexpectedRoot,
#[error("Invalid mpt proof")]
InvalidMPTProof,
#[error("Invalid transaction trie")]
TrieNotFound,
#[error("Field not found")]
FieldNotFound,
}

Expand All @@ -37,8 +52,25 @@ pub enum Field {
Signature,
}

impl From<TrieError> for Error {
impl fmt::Display for Field {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Field::ChainId => write!(f, "chain_id"),
Field::Nonce => write!(f, "nonce"),
Field::GasPrice => write!(f, "gas_price"),
Field::GasLimit => write!(f, "gas_limit"),
Field::Input => write!(f, "input"),
Field::AccessList => write!(f, "access_list"),
Field::MaxFeePerGas => write!(f, "max_fee_per_gas"),
Field::MaxPriorityFeePerGas => write!(f, "max_priority_fee_per_gas"),
Field::MaxFeePerBlobGas => write!(f, "max_fee_per_blob_gas"),
Field::Signature => write!(f, "signature"),
}
}
}

impl From<TrieError> for EthTrieError {
fn from(err: TrieError) -> Self {
Error::Trie(err)
EthTrieError::Trie(err)
}
}
26 changes: 13 additions & 13 deletions src/rpc.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::Error;
use crate::EthTrieError;
use alloy::network::Ethereum;
use alloy::primitives::B256;
use alloy::providers::{Provider, RootProvider};
Expand All @@ -20,19 +20,19 @@ impl RpcProvider {
pub(crate) async fn get_block_transactions(
&self,
block_number: u64,
) -> Result<(Vec<Transaction>, B256), Error> {
) -> Result<(Vec<Transaction>, B256), EthTrieError> {
let block = self
.provider
.get_block(
block_number.into(),
alloy::rpc::types::BlockTransactionsKind::Full,
)
.await?
.ok_or_else(|| Error::BlockNotFound)?;
.ok_or_else(|| EthTrieError::BlockNotFound)?;

let txs = match block.transactions {
BlockTransactions::Full(txs) => txs,
_ => return Err(Error::TxNotFound),
_ => return Err(EthTrieError::TxNotFound),
};

Ok((txs, block.header.transactions_root))
Expand All @@ -41,26 +41,26 @@ impl RpcProvider {
pub(crate) async fn get_block_transaction_receipts(
&self,
block_number: u64,
) -> Result<(Vec<TransactionReceipt>, B256), Error> {
) -> Result<(Vec<TransactionReceipt>, B256), EthTrieError> {
let block = self
.provider
.get_block(
block_number.into(),
alloy::rpc::types::BlockTransactionsKind::Full,
)
.await?
.ok_or_else(|| Error::BlockNotFound)?;
.ok_or_else(|| EthTrieError::BlockNotFound)?;

let tx_receipts = self
.provider
.get_block_receipts(block_number.into())
.await?
.ok_or_else(|| Error::BlockNotFound)?;
.ok_or_else(|| EthTrieError::BlockNotFound)?;

Ok((tx_receipts, block.header.receipts_root))
}

pub(crate) async fn get_tx_index_by_hash(&self, tx_hash: B256) -> Result<u64, Error> {
pub(crate) async fn get_tx_index_by_hash(&self, tx_hash: B256) -> Result<u64, EthTrieError> {
let tx = self
.provider
.get_transaction_by_hash(tx_hash)
Expand All @@ -69,13 +69,13 @@ impl RpcProvider {

let index: u64 = match tx.transaction_index {
Some(index) => index,
None => return Err(Error::TxNotFound),
None => return Err(EthTrieError::TxNotFound),
};

Ok(index)
}

pub(crate) async fn get_tx_block_height(&self, tx_hash: B256) -> Result<u64, Error> {
pub(crate) async fn get_tx_block_height(&self, tx_hash: B256) -> Result<u64, EthTrieError> {
let tx = self
.provider
.get_transaction_by_hash(tx_hash)
Expand All @@ -84,15 +84,15 @@ impl RpcProvider {

let height: u64 = match tx.block_number {
Some(height) => height,
None => return Err(Error::TxNotFound),
None => return Err(EthTrieError::TxNotFound),
};

Ok(height)
}
}

impl From<RpcError<TransportErrorKind>> for Error {
impl From<RpcError<TransportErrorKind>> for EthTrieError {
fn from(err: RpcError<TransportErrorKind>) -> Self {
Error::RPC(err)
EthTrieError::RPC(err)
}
}
36 changes: 18 additions & 18 deletions src/tx.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{Error, Field};
use crate::{EthTrieError, Field};
use alloy::consensus::{
SignableTransaction, TxEip1559, TxEip2930, TxEip4844, TxEnvelope, TxLegacy, TxType,
};
Expand All @@ -18,8 +18,8 @@ impl ConsensusTx {
self.0.encoded_2718()
}

pub fn rlp_decode(mut data: &[u8]) -> Result<Self, Error> {
let tx = TxEnvelope::decode_2718(&mut data).map_err(Error::Eip)?;
pub fn rlp_decode(mut data: &[u8]) -> Result<Self, EthTrieError> {
let tx = TxEnvelope::decode_2718(&mut data).map_err(EthTrieError::Eip)?;
Ok(ConsensusTx(tx))
}

Expand Down Expand Up @@ -207,8 +207,8 @@ impl ConsensusTx {
pub(crate) struct RpcTx(pub Transaction);

impl TryFrom<RpcTx> for ConsensusTx {
type Error = Error;
fn try_from(tx: RpcTx) -> Result<ConsensusTx, Error> {
type Error = EthTrieError;
fn try_from(tx: RpcTx) -> Result<ConsensusTx, EthTrieError> {
let chain_id = tx.chain_id();
let nonce: u64 = tx.0.nonce;
let gas_limit: u128 = tx.0.gas;
Expand Down Expand Up @@ -267,13 +267,13 @@ impl TryFrom<RpcTx> for ConsensusTx {
TxType::Eip4844 => {
let to = match tx.to() {
TxKind::Call(to) => to,
TxKind::Create => return Err(Error::InvalidTxVersion),
TxKind::Create => return Err(EthTrieError::InvalidTxVersion),
};
let blob_versioned_hashes = tx
.clone()
.0
.blob_versioned_hashes
.ok_or(Error::ConversionError(Field::Input))?;
.ok_or(EthTrieError::ConversionError(Field::Input))?;
let max_fee_per_gas = tx.max_fee_per_gas()?;
let max_priority_fee_per_gas = tx.max_priority_fee_per_gas()?;
let max_fee_per_blob_gas = tx.max_fee_per_blob_gas()?;
Expand Down Expand Up @@ -309,42 +309,42 @@ impl RpcTx {
}
}

fn version(&self) -> Result<TxType, Error> {
fn version(&self) -> Result<TxType, EthTrieError> {
match self.0.transaction_type {
Some(0) => Ok(TxType::Legacy),
Some(1) => Ok(TxType::Eip2930),
Some(2) => Ok(TxType::Eip1559),
Some(3) => Ok(TxType::Eip4844),
None => Ok(TxType::Legacy),
_ => Err(Error::InvalidTxVersion),
_ => Err(EthTrieError::InvalidTxVersion),
}
}

fn max_fee_per_gas(&self) -> Result<u128, Error> {
fn max_fee_per_gas(&self) -> Result<u128, EthTrieError> {
if let Some(value) = self.0.max_fee_per_gas {
Ok(value)
} else {
Ok(0)
}
}

fn max_priority_fee_per_gas(&self) -> Result<u128, Error> {
fn max_priority_fee_per_gas(&self) -> Result<u128, EthTrieError> {
if let Some(value) = self.0.max_priority_fee_per_gas {
Ok(value)
} else {
Ok(0)
}
}

fn max_fee_per_blob_gas(&self) -> Result<u128, Error> {
fn max_fee_per_blob_gas(&self) -> Result<u128, EthTrieError> {
if let Some(value) = self.0.max_fee_per_blob_gas {
Ok(value)
} else {
Ok(0)
}
}

fn signature(&self) -> Result<Signature, Error> {
fn signature(&self) -> Result<Signature, EthTrieError> {
if let Some(signature) = self.0.signature {
let sig = Signature::from_rs_and_parity(
signature.r,
Expand All @@ -353,23 +353,23 @@ impl RpcTx {
signature
.v
.try_into()
.map_err(|_| Error::ConversionError(Field::Signature))?,
.map_err(|_| EthTrieError::ConversionError(Field::Signature))?,
),
)
.map_err(|_| Error::ConversionError(Field::Signature))?;
.map_err(|_| EthTrieError::ConversionError(Field::Signature))?;

Ok(sig)
} else {
Err(Error::ConversionError(Field::Signature))
Err(EthTrieError::ConversionError(Field::Signature))
}
}

fn access_list(&self) -> Result<AccessList, Error> {
fn access_list(&self) -> Result<AccessList, EthTrieError> {
if let Some(al) = self.0.access_list.clone() {
let target_list_items: Vec<AccessListItem> = Vec::<AccessListItem>::from(al);
Ok(AccessList(target_list_items))
} else {
Err(Error::ConversionError(Field::AccessList))
Err(EthTrieError::ConversionError(Field::AccessList))
}
}
}
12 changes: 6 additions & 6 deletions src/tx_receipt.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::Error;
use crate::EthTrieError;
use alloy::consensus::{Eip658Value, Receipt, ReceiptWithBloom, TxReceipt};
use alloy::consensus::{ReceiptEnvelope, TxType};
use alloy::eips::eip2718::Decodable2718;
Expand All @@ -15,8 +15,8 @@ impl ConsensusTxReceipt {
self.0.encoded_2718()
}

pub fn rlp_decode(mut data: &[u8]) -> Result<Self, Error> {
let envelope = ReceiptEnvelope::decode_2718(&mut data).map_err(Error::Eip)?;
pub fn rlp_decode(mut data: &[u8]) -> Result<Self, EthTrieError> {
let envelope = ReceiptEnvelope::decode_2718(&mut data).map_err(EthTrieError::Eip)?;
Ok(ConsensusTxReceipt(envelope))
}

Expand Down Expand Up @@ -65,8 +65,8 @@ impl ConsensusTxReceipt {
pub(crate) struct RpcTxReceipt(pub TransactionReceipt);

impl TryFrom<RpcTxReceipt> for ConsensusTxReceipt {
type Error = Error;
fn try_from(tx: RpcTxReceipt) -> Result<ConsensusTxReceipt, Error> {
type Error = EthTrieError;
fn try_from(tx: RpcTxReceipt) -> Result<ConsensusTxReceipt, EthTrieError> {
match &tx.version()? {
TxType::Legacy => {
let res = ReceiptEnvelope::Legacy(ReceiptWithBloom {
Expand Down Expand Up @@ -117,7 +117,7 @@ impl TryFrom<RpcTxReceipt> for ConsensusTxReceipt {
}

impl RpcTxReceipt {
fn version(&self) -> Result<TxType, Error> {
fn version(&self) -> Result<TxType, EthTrieError> {
Ok(self.0.transaction_type())
}

Expand Down
Loading

0 comments on commit 6a6717d

Please sign in to comment.