Skip to content

Commit

Permalink
feat: feature gate rpc-types import for alloy conversions (#7963)
Browse files Browse the repository at this point in the history
Co-authored-by: Matthias Seitz <[email protected]>
  • Loading branch information
andrzejSulkowski and mattsse authored May 8, 2024
1 parent db86820 commit dd7c021
Show file tree
Hide file tree
Showing 12 changed files with 170 additions and 183 deletions.
236 changes: 115 additions & 121 deletions Cargo.lock

Large diffs are not rendered by default.

10 changes: 6 additions & 4 deletions crates/primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ workspace = true
reth-codecs.workspace = true
reth-ethereum-forks.workspace = true
reth-network-types.workspace = true
reth-rpc-types.workspace = true
revm.workspace = true
revm-primitives = { workspace = true, features = ["serde"] }

Expand All @@ -25,9 +24,10 @@ alloy-chains = { workspace = true, features = ["serde", "rlp"] }
alloy-primitives = { workspace = true, features = ["rand", "rlp"] }
alloy-rlp = { workspace = true, features = ["arrayvec"] }
alloy-trie = { workspace = true, features = ["serde"] }
nybbles = { workspace = true, features = ["serde", "rlp"] }
alloy-rpc-types = { workspace = true, optional = true }
alloy-genesis.workspace = true
alloy-eips.workspace = true
alloy-eips = { workspace = true, features = ["serde"] }
nybbles = { workspace = true, features = ["serde", "rlp"] }

# crypto
secp256k1 = { workspace = true, features = ["global-context", "recovery", "rand"] }
Expand Down Expand Up @@ -66,7 +66,9 @@ revm-primitives = { workspace = true, features = ["arbitrary"] }
nybbles = { workspace = true, features = ["arbitrary"] }
alloy-trie = { workspace = true, features = ["arbitrary"] }
alloy-eips = { workspace = true, features = ["arbitrary"] }

assert_matches.workspace = true
arbitrary = { workspace = true, features = ["derive"] }
proptest.workspace = true
proptest-derive.workspace = true
rand.workspace = true
Expand All @@ -91,7 +93,6 @@ default = ["c-kzg", "zstd-codec"]
asm-keccak = ["alloy-primitives/asm-keccak"]
arbitrary = [
"revm-primitives/arbitrary",
"reth-rpc-types/arbitrary",
"reth-ethereum-forks/arbitrary",
"nybbles/arbitrary",
"alloy-trie/arbitrary",
Expand All @@ -110,6 +111,7 @@ optimism = [
"reth-ethereum-forks/optimism",
"revm/optimism",
]
alloy-compat = ["alloy-rpc-types"]
test-utils = ["dep:plain_hasher", "dep:hash-db"]

[[bench]]
Expand Down
24 changes: 13 additions & 11 deletions crates/primitives/src/block.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
use crate::{
Address, Bytes, GotExpected, Header, SealedHeader, Signature, TransactionSigned,
Address, Bytes, GotExpected, Header, SealedHeader, TransactionSigned,
TransactionSignedEcRecovered, Withdrawals, B256,
};
use alloy_rlp::{RlpDecodable, RlpEncodable};
#[cfg(any(test, feature = "arbitrary"))]
use proptest::prelude::{any, prop_compose};
use reth_codecs::derive_arbitrary;
use reth_rpc_types::ConversionError;
use serde::{Deserialize, Serialize};
use std::ops::Deref;

pub use reth_rpc_types::{
pub use alloy_eips::eip1898::{
BlockHashOrNumber, BlockId, BlockNumHash, BlockNumberOrTag, ForkBlock, RpcBlockHash,
};

Expand Down Expand Up @@ -148,33 +147,36 @@ impl Deref for Block {
}
}

impl TryFrom<reth_rpc_types::Block> for Block {
type Error = ConversionError;
#[cfg(feature = "alloy-compat")]
impl TryFrom<alloy_rpc_types::Block> for Block {
type Error = alloy_rpc_types::ConversionError;

fn try_from(block: alloy_rpc_types::Block) -> Result<Self, Self::Error> {
use alloy_rpc_types::ConversionError;

fn try_from(block: reth_rpc_types::Block) -> Result<Self, Self::Error> {
let body = {
let transactions: Result<Vec<TransactionSigned>, ConversionError> = match block
.transactions
{
reth_rpc_types::BlockTransactions::Full(transactions) => transactions
alloy_rpc_types::BlockTransactions::Full(transactions) => transactions
.into_iter()
.map(|tx| {
let signature = tx.signature.ok_or(ConversionError::MissingSignature)?;
Ok(TransactionSigned::from_transaction_and_signature(
tx.try_into()?,
Signature {
crate::Signature {
r: signature.r,
s: signature.s,
odd_y_parity: signature
.y_parity
.unwrap_or(reth_rpc_types::Parity(false))
.unwrap_or(alloy_rpc_types::Parity(false))
.0,
},
))
})
.collect(),
reth_rpc_types::BlockTransactions::Hashes(_) |
reth_rpc_types::BlockTransactions::Uncle => {
alloy_rpc_types::BlockTransactions::Hashes(_) |
alloy_rpc_types::BlockTransactions::Uncle => {
return Err(ConversionError::MissingFullTransactions)
}
};
Expand Down
10 changes: 6 additions & 4 deletions crates/primitives/src/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ use bytes::BufMut;
#[cfg(any(test, feature = "arbitrary"))]
use proptest::prelude::*;
use reth_codecs::{add_arbitrary_tests, derive_arbitrary, main_codec, Compact};
use reth_rpc_types::ConversionError;
use serde::{Deserialize, Serialize};
use std::{mem, ops::Deref};

Expand Down Expand Up @@ -486,10 +485,13 @@ impl Decodable for Header {
}
}

impl TryFrom<reth_rpc_types::Header> for Header {
type Error = ConversionError;
#[cfg(feature = "alloy-compat")]
impl TryFrom<alloy_rpc_types::Header> for Header {
type Error = alloy_rpc_types::ConversionError;

fn try_from(header: alloy_rpc_types::Header) -> Result<Self, Self::Error> {
use alloy_rpc_types::ConversionError;

fn try_from(header: reth_rpc_types::Header) -> Result<Self, Self::Error> {
Ok(Self {
base_fee_per_gas: header
.base_fee_per_gas
Expand Down
2 changes: 1 addition & 1 deletion crates/primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
//!
//! ## Feature Flags
//!
//! - `alloy-compat`: Adds compatibility conversions for certain alloy types.
//! - `arbitrary`: Adds `proptest` and `arbitrary` support for primitive types.
//! - `test-utils`: Export utilities for testing

Expand Down Expand Up @@ -38,7 +39,6 @@ mod prune;
mod receipt;
/// Helpers for working with revm
pub mod revm;
pub mod serde_helper;
pub mod stage;
pub mod static_file;
mod storage;
Expand Down
11 changes: 3 additions & 8 deletions crates/primitives/src/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,15 +120,10 @@ pub fn parse_nodes(nodes: impl IntoIterator<Item = impl AsRef<str>>) -> Vec<Node

#[cfg(test)]
mod tests {
use std::{
net::{IpAddr, Ipv4Addr},
str::FromStr,
};

use super::*;
use alloy_rlp::Decodable;
use rand::{thread_rng, Rng, RngCore};
use reth_rpc_types::PeerId;
use std::net::{IpAddr, Ipv4Addr};

#[test]
fn test_mapped_ipv6() {
Expand Down Expand Up @@ -232,7 +227,7 @@ mod tests {
address: IpAddr::V4([10, 3, 58, 6].into()),
tcp_port: 30303u16,
udp_port: 30301u16,
id: PeerId::from_str("6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0").unwrap(),
id: "6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0".parse().unwrap(),
};
let ser = serde_json::to_string::<NodeRecord>(&node).expect("couldn't serialize");
assert_eq!(ser, "\"enode://6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@10.3.58.6:30303?discport=30301\"")
Expand All @@ -246,7 +241,7 @@ mod tests {
address: IpAddr::V4([10, 3, 58, 6].into()),
tcp_port: 30303u16,
udp_port: 30301u16,
id: PeerId::from_str("6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0").unwrap(),
id: "6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0".parse().unwrap(),
})
}
}
3 changes: 0 additions & 3 deletions crates/primitives/src/serde_helper.rs

This file was deleted.

20 changes: 12 additions & 8 deletions crates/primitives/src/transaction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
use crate::compression::{TRANSACTION_COMPRESSOR, TRANSACTION_DECOMPRESSOR};
use crate::{keccak256, Address, BlockHashOrNumber, Bytes, TxHash, TxKind, B256, U256};

use alloy_eips::eip2718::Eip2718Error;
use alloy_rlp::{
Decodable, Encodable, Error as RlpError, Header, EMPTY_LIST_CODE, EMPTY_STRING_CODE,
};
Expand All @@ -11,7 +10,6 @@ use derive_more::{AsRef, Deref};
use once_cell::sync::Lazy;
use rayon::prelude::{IntoParallelIterator, ParallelIterator};
use reth_codecs::{add_arbitrary_tests, derive_arbitrary, Compact};
use reth_rpc_types::ConversionError;
use serde::{Deserialize, Serialize};
use std::mem;

Expand Down Expand Up @@ -614,10 +612,14 @@ impl From<TxEip4844> for Transaction {
}
}

impl TryFrom<reth_rpc_types::Transaction> for Transaction {
type Error = ConversionError;
#[cfg(feature = "alloy-compat")]
impl TryFrom<alloy_rpc_types::Transaction> for Transaction {
type Error = alloy_rpc_types::ConversionError;

fn try_from(tx: alloy_rpc_types::Transaction) -> Result<Self, Self::Error> {
use alloy_eips::eip2718::Eip2718Error;
use alloy_rpc_types::ConversionError;

fn try_from(tx: reth_rpc_types::Transaction) -> Result<Self, Self::Error> {
match tx.transaction_type.map(TryInto::try_into).transpose().map_err(|_| {
ConversionError::Eip2718Error(Eip2718Error::UnexpectedType(
tx.transaction_type.unwrap(),
Expand Down Expand Up @@ -1717,10 +1719,12 @@ impl IntoRecoveredTransaction for TransactionSignedEcRecovered {
}
}

impl TryFrom<reth_rpc_types::Transaction> for TransactionSignedEcRecovered {
type Error = ConversionError;
#[cfg(feature = "alloy-compat")]
impl TryFrom<alloy_rpc_types::Transaction> for TransactionSignedEcRecovered {
type Error = alloy_rpc_types::ConversionError;

fn try_from(tx: reth_rpc_types::Transaction) -> Result<Self, Self::Error> {
fn try_from(tx: alloy_rpc_types::Transaction) -> Result<Self, Self::Error> {
use alloy_rpc_types::ConversionError;
let signature = tx.signature.ok_or(ConversionError::MissingSignature)?;

let transaction: Transaction = tx.try_into()?;
Expand Down
5 changes: 1 addition & 4 deletions crates/primitives/src/withdrawal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ impl From<Vec<Withdrawal>> for Withdrawals {
#[cfg(test)]
mod tests {
use super::*;
use crate::{serde_helper::u64_via_ruint, Address};
use crate::Address;
use alloy_rlp::{RlpDecodable, RlpEncodable};
use proptest::proptest;

Expand All @@ -95,15 +95,12 @@ mod tests {
#[derive(Debug, Clone, PartialEq, Eq, Default, Hash, RlpEncodable, RlpDecodable)]
struct RethWithdrawal {
/// Monotonically increasing identifier issued by consensus layer.
#[serde(with = "u64_via_ruint")]
index: u64,
/// Index of validator associated with withdrawal.
#[serde(with = "u64_via_ruint", rename = "validatorIndex")]
validator_index: u64,
/// Target address for withdrawn ether.
address: Address,
/// Value of the withdrawal in gwei.
#[serde(with = "u64_via_ruint")]
amount: u64,
}

Expand Down
11 changes: 5 additions & 6 deletions crates/rpc/rpc-api/src/eth.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
use jsonrpsee::{core::RpcResult, proc_macros::rpc};
use reth_primitives::{
serde_helper::JsonStorageKey, Address, BlockId, BlockNumberOrTag, Bytes, B256, B64, U256, U64,
};
use reth_primitives::{Address, BlockId, BlockNumberOrTag, Bytes, B256, B64, U256, U64};
use reth_rpc_types::{
state::StateOverride, AccessListWithGasUsed, AnyTransactionReceipt, BlockOverrides, Bundle,
EIP1186AccountProofResponse, EthCallResponse, FeeHistory, Header, Index, RichBlock,
StateContext, SyncStatus, Transaction, TransactionRequest, Work,
serde_helpers::JsonStorageKey, state::StateOverride, AccessListWithGasUsed,
AnyTransactionReceipt, BlockOverrides, Bundle, EIP1186AccountProofResponse, EthCallResponse,
FeeHistory, Header, Index, RichBlock, StateContext, SyncStatus, Transaction,
TransactionRequest, Work,
};

/// Eth rpc interface: <https://ethereum.github.io/execution-apis/api-documentation/>
Expand Down
15 changes: 6 additions & 9 deletions crates/rpc/rpc/src/eth/api/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,22 @@
//! Handles RPC requests for the `eth_` namespace.

use jsonrpsee::core::RpcResult as Result;
use serde_json::Value;
use tracing::trace;

use reth_evm::ConfigureEvm;
use reth_network_api::NetworkInfo;
use reth_primitives::{
serde_helper::JsonStorageKey, Address, BlockId, BlockNumberOrTag, Bytes, B256, B64, U256, U64,
};
use reth_primitives::{Address, BlockId, BlockNumberOrTag, Bytes, B256, B64, U256, U64};
use reth_provider::{
BlockIdReader, BlockReader, BlockReaderIdExt, ChainSpecProvider, EvmEnvProvider,
HeaderProvider, StateProviderFactory,
};
use reth_rpc_api::EthApiServer;
use reth_rpc_types::{
state::StateOverride, AccessListWithGasUsed, AnyTransactionReceipt, BlockOverrides, Bundle,
EIP1186AccountProofResponse, EthCallResponse, FeeHistory, Header, Index, RichBlock,
StateContext, SyncStatus, TransactionRequest, Work,
serde_helpers::JsonStorageKey, state::StateOverride, AccessListWithGasUsed,
AnyTransactionReceipt, BlockOverrides, Bundle, EIP1186AccountProofResponse, EthCallResponse,
FeeHistory, Header, Index, RichBlock, StateContext, SyncStatus, TransactionRequest, Work,
};
use reth_transaction_pool::TransactionPool;
use serde_json::Value;
use tracing::trace;

use crate::{
eth::{
Expand Down
6 changes: 2 additions & 4 deletions crates/rpc/rpc/src/eth/api/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,11 @@ use crate::{
EthApi,
};
use reth_evm::ConfigureEvm;
use reth_primitives::{
serde_helper::JsonStorageKey, Address, BlockId, BlockNumberOrTag, Bytes, B256, U256,
};
use reth_primitives::{Address, BlockId, BlockNumberOrTag, Bytes, B256, U256};
use reth_provider::{
BlockReaderIdExt, ChainSpecProvider, EvmEnvProvider, StateProvider, StateProviderFactory,
};
use reth_rpc_types::EIP1186AccountProofResponse;
use reth_rpc_types::{serde_helpers::JsonStorageKey, EIP1186AccountProofResponse};
use reth_rpc_types_compat::proof::from_primitive_account_proof;
use reth_transaction_pool::{PoolTransaction, TransactionPool};

Expand Down

0 comments on commit dd7c021

Please sign in to comment.