feat: bump alloy (#12215)

Co-authored-by: Matthias Seitz <matthias.seitz@outlook.de>
This commit is contained in:
Arsenii Kulikov
2024-11-06 18:50:25 +04:00
committed by GitHub
parent 12b0637485
commit 38fdc93a12
52 changed files with 588 additions and 1046 deletions

View File

@ -3,11 +3,11 @@
use std::sync::Arc;
use alloy_eips::BlockId;
use alloy_rpc_types::{Header, Index};
use alloy_rpc_types::{Block, Header, Index};
use futures::Future;
use reth_primitives::{Receipt, SealedBlock, SealedBlockWithSenders};
use reth_provider::{BlockIdReader, BlockReader, BlockReaderIdExt, HeaderProvider};
use reth_rpc_types_compat::block::{from_block, uncle_block_from_header};
use reth_rpc_types_compat::block::from_block;
use crate::{node::RpcNodeCoreExt, FromEthApiError, FullEthApiTypes, RpcBlock, RpcReceipt};
@ -189,7 +189,7 @@ pub trait EthBlocks: LoadBlock {
}
.unwrap_or_default();
Ok(uncles.into_iter().nth(index.into()).map(uncle_block_from_header))
Ok(uncles.into_iter().nth(index.into()).map(Block::uncle_from_header))
}
}
}

View File

@ -5,6 +5,7 @@ use crate::{
AsEthApiError, FromEthApiError, FromEvmError, FullEthApiTypes, IntoEthApiError, RpcBlock,
RpcNodeCore,
};
use alloy_consensus::BlockHeader;
use alloy_eips::{eip1559::calc_next_block_base_fee, eip2930::AccessListResult};
use alloy_primitives::{Address, Bytes, TxKind, B256, U256};
use alloy_rpc_types::{
@ -125,9 +126,9 @@ pub trait EthCall: Call + LoadPendingBlock {
let base_fee = if let Some(latest) = blocks.last() {
let header = &latest.inner.header;
calc_next_block_base_fee(
header.gas_used,
header.gas_limit,
header.base_fee_per_gas.unwrap_or_default(),
header.gas_used(),
header.gas_limit(),
header.base_fee_per_gas().unwrap_or_default(),
base_fee_params,
)
} else {
@ -192,19 +193,20 @@ pub trait EthCall: Call + LoadPendingBlock {
results.push((env.tx.caller, res.result));
}
let block = simulate::build_block(
results,
transactions,
&block_env,
parent_hash,
total_difficulty,
return_full_transactions,
&db,
this.tx_resp_builder(),
)?;
let block: SimulatedBlock<RpcBlock<Self::NetworkTypes>> =
simulate::build_block(
results,
transactions,
&block_env,
parent_hash,
total_difficulty,
return_full_transactions,
&db,
this.tx_resp_builder(),
)?;
parent_hash = block.inner.header.hash;
gas_used += block.inner.header.gas_used;
gas_used += block.inner.header.gas_used();
blocks.push(block);
}

View File

@ -1,7 +1,7 @@
//! An abstraction over ethereum signers.
use alloy_dyn_abi::TypedData;
use alloy_primitives::{Address, Signature};
use alloy_primitives::{Address, PrimitiveSignature as Signature};
use alloy_rpc_types_eth::TransactionRequest;
use dyn_clone::DynClone;
use reth_primitives::TransactionSigned;

View File

@ -74,7 +74,7 @@ pub trait EthState: LoadState + SpawnBlocking {
self.spawn_blocking_io(move |this| {
Ok(B256::new(
this.state_at_block_id_or_latest(block_id)?
.storage(address, index.0)
.storage(address, index.as_b256())
.map_err(Self::Error::from_eth_err)?
.unwrap_or_default()
.to_be_bytes(),
@ -118,7 +118,7 @@ pub trait EthState: LoadState + SpawnBlocking {
self.spawn_blocking_io(move |this| {
let state = this.state_at_block_id(block_id)?;
let storage_keys = keys.iter().map(|key| key.0).collect::<Vec<_>>();
let storage_keys = keys.iter().map(|key| key.as_b256()).collect::<Vec<_>>();
let proof = state
.proof(Default::default(), address, &storage_keys)
.map_err(Self::Error::from_eth_err)?;

View File

@ -1,6 +1,9 @@
//! Trait for specifying `eth` network dependent API types.
use std::{error::Error, fmt};
use std::{
error::Error,
fmt::{self},
};
use alloy_network::Network;
use alloy_rpc_types::Block;

View File

@ -1,7 +1,7 @@
//! Utilities for serving `eth_simulateV1`
use alloy_consensus::{Transaction as _, TxEip4844Variant, TxType, TypedTransaction};
use alloy_primitives::{Parity, Signature};
use alloy_primitives::PrimitiveSignature as Signature;
use alloy_rpc_types::{
simulate::{SimCallResult, SimulateError, SimulatedBlock},
Block, BlockTransactionsKind,
@ -133,8 +133,7 @@ where
};
// Create an empty signature for the transaction.
let signature =
Signature::new(Default::default(), Default::default(), Parity::Parity(false));
let signature = Signature::new(Default::default(), Default::default(), false);
let tx = match tx {
TypedTransaction::Legacy(tx) => {
@ -170,7 +169,7 @@ where
}
/// Handles outputs of the calls execution and builds a [`SimulatedBlock`].
#[expect(clippy::too_many_arguments)]
#[expect(clippy::complexity)]
pub fn build_block<T: TransactionCompat>(
results: Vec<(Address, ExecutionResult)>,
transactions: Vec<TransactionSigned>,
@ -306,6 +305,6 @@ pub fn build_block<T: TransactionCompat>(
let txs_kind =
if full_transactions { BlockTransactionsKind::Full } else { BlockTransactionsKind::Hashes };
let block = from_block(block, total_difficulty, txs_kind, None, tx_resp_builder)?;
let block = from_block::<T>(block, total_difficulty, txs_kind, None, tx_resp_builder)?;
Ok(SimulatedBlock { inner: block, calls })
}

View File

@ -1,13 +1,12 @@
//! Compatibility functions for rpc `Block` type.
use alloy_consensus::Sealed;
use alloy_primitives::{B256, U256};
use alloy_rlp::Encodable;
use alloy_rpc_types::{
Block, BlockError, BlockTransactions, BlockTransactionsKind, Header, TransactionInfo,
};
use reth_primitives::{
Block as PrimitiveBlock, BlockWithSenders, Header as PrimitiveHeader, SealedHeader, Withdrawals,
};
use reth_primitives::{Block as PrimitiveBlock, BlockWithSenders, Withdrawals};
use crate::{transaction::from_recovered_with_block_context, TransactionCompat};
@ -100,64 +99,6 @@ pub fn from_block_full<T: TransactionCompat>(
))
}
/// Converts from a [`reth_primitives::SealedHeader`] to a [`alloy-rpc-types::Header`]
///
/// # Note
///
/// This does not set the `totalDifficulty` field.
pub fn from_primitive_with_hash(primitive_header: reth_primitives::SealedHeader) -> Header {
let (header, hash) = primitive_header.split();
let PrimitiveHeader {
parent_hash,
ommers_hash,
beneficiary,
state_root,
transactions_root,
receipts_root,
logs_bloom,
difficulty,
number,
gas_limit,
gas_used,
timestamp,
mix_hash,
nonce,
base_fee_per_gas,
extra_data,
withdrawals_root,
blob_gas_used,
excess_blob_gas,
parent_beacon_block_root,
requests_hash,
} = header;
Header {
hash,
parent_hash,
uncles_hash: ommers_hash,
miner: beneficiary,
state_root,
transactions_root,
receipts_root,
withdrawals_root,
number,
gas_used,
gas_limit,
extra_data,
logs_bloom,
timestamp,
difficulty,
mix_hash: Some(mix_hash),
nonce: Some(nonce),
base_fee_per_gas,
blob_gas_used,
excess_blob_gas,
parent_beacon_block_root,
total_difficulty: None,
requests_hash,
}
}
#[inline]
fn from_block_with_transactions<T>(
block_length: usize,
@ -166,31 +107,19 @@ fn from_block_with_transactions<T>(
total_difficulty: U256,
transactions: BlockTransactions<T>,
) -> Block<T> {
let uncles = block.body.ommers.into_iter().map(|h| h.hash_slow()).collect();
let mut header = from_primitive_with_hash(SealedHeader::new(block.header, block_hash));
header.total_difficulty = Some(total_difficulty);
let withdrawals = header
let withdrawals = block
.header
.withdrawals_root
.is_some()
.then(|| block.body.withdrawals.map(Withdrawals::into_inner))
.then(|| block.body.withdrawals.map(Withdrawals::into_inner).map(Into::into))
.flatten();
Block { header, uncles, transactions, size: Some(U256::from(block_length)), withdrawals }
}
let uncles = block.body.ommers.into_iter().map(|h| h.hash_slow()).collect();
let header = Header::from_consensus(
Sealed::new_unchecked(block.header, block_hash),
Some(total_difficulty),
Some(U256::from(block_length)),
);
/// Build an RPC block response representing
/// an Uncle from its header.
pub fn uncle_block_from_header<T>(header: PrimitiveHeader) -> Block<T> {
let hash = header.hash_slow();
let uncle_block = PrimitiveBlock { header, ..Default::default() };
let size = Some(U256::from(uncle_block.length()));
let rpc_header = from_primitive_with_hash(SealedHeader::new(uncle_block.header, hash));
Block {
uncles: vec![],
header: rpc_header,
transactions: BlockTransactions::Uncle,
withdrawals: None,
size,
}
Block { header, uncles, transactions, withdrawals }
}

View File

@ -6,7 +6,11 @@ use reth_trie_common::{AccountProof, StorageProof};
/// Creates a new rpc storage proof from a primitive storage proof type.
pub fn from_primitive_storage_proof(proof: StorageProof) -> EIP1186StorageProof {
EIP1186StorageProof { key: JsonStorageKey(proof.key), value: proof.value, proof: proof.proof }
EIP1186StorageProof {
key: JsonStorageKey::Hash(proof.key),
value: proof.value,
proof: proof.proof,
}
}
/// Creates a new rpc account proof from a primitive account proof type.

View File

@ -1,7 +1,4 @@
//! Compatibility functions for rpc `Transaction` type.
mod signature;
pub use signature::*;
use std::fmt;
@ -10,7 +7,7 @@ use alloy_rpc_types::{
request::{TransactionInput, TransactionRequest},
TransactionInfo,
};
use reth_primitives::{TransactionSigned, TransactionSignedEcRecovered, TxType};
use reth_primitives::TransactionSignedEcRecovered;
use serde::{Deserialize, Serialize};
/// Create a new rpc transaction result for a mined transaction, using the given block hash,
@ -44,36 +41,8 @@ pub trait TransactionCompat: Send + Sync + Unpin + Clone + fmt::Debug {
+ Sync
+ Unpin
+ Clone
+ Default
+ fmt::Debug;
///
/// Formats gas price and max fee per gas for RPC transaction response w.r.t. network specific
/// transaction type.
fn gas_price(signed_tx: &TransactionSigned, base_fee: Option<u64>) -> GasPrice {
#[allow(unreachable_patterns)]
match signed_tx.tx_type() {
TxType::Legacy | TxType::Eip2930 => {
GasPrice { gas_price: Some(signed_tx.max_fee_per_gas()), max_fee_per_gas: None }
}
TxType::Eip1559 | TxType::Eip4844 | TxType::Eip7702 => {
// the gas price field for EIP1559 is set to `min(tip, gasFeeCap - baseFee) +
// baseFee`
let gas_price = base_fee
.and_then(|base_fee| {
signed_tx.effective_tip_per_gas(base_fee).map(|tip| tip + base_fee as u128)
})
.unwrap_or_else(|| signed_tx.max_fee_per_gas());
GasPrice {
gas_price: Some(gas_price),
max_fee_per_gas: Some(signed_tx.max_fee_per_gas()),
}
}
_ => GasPrice::default(),
}
}
/// Create a new rpc transaction result for a _pending_ signed transaction, setting block
/// environment related fields to `None`.
fn fill(&self, tx: TransactionSignedEcRecovered, tx_inf: TransactionInfo) -> Self::Transaction;
@ -82,19 +51,6 @@ pub trait TransactionCompat: Send + Sync + Unpin + Clone + fmt::Debug {
// todo: remove in favour of using constructor on `TransactionResponse` or similar
// <https://github.com/alloy-rs/alloy/issues/1315>.
fn otterscan_api_truncate_input(tx: &mut Self::Transaction);
/// Returns the transaction type.
// todo: remove when alloy TransactionResponse trait it updated.
fn tx_type(tx: &Self::Transaction) -> u8;
}
/// Gas price and max fee per gas for a transaction. Helper type to format transaction RPC response.
#[derive(Debug, Default)]
pub struct GasPrice {
/// Gas price for transaction.
pub gas_price: Option<u128>,
/// Max fee per gas for transaction.
pub max_fee_per_gas: Option<u128>,
}
/// Convert [`TransactionSignedEcRecovered`] to [`TransactionRequest`]

View File

@ -6,7 +6,7 @@ use crate::EthApi;
use alloy_dyn_abi::TypedData;
use alloy_eips::eip2718::Decodable2718;
use alloy_network::{eip2718::Encodable2718, EthereumWallet, TransactionBuilder};
use alloy_primitives::{eip191_hash_message, Address, Signature, B256};
use alloy_primitives::{eip191_hash_message, Address, PrimitiveSignature as Signature, B256};
use alloy_rpc_types_eth::TransactionRequest;
use alloy_signer::SignerSync;
use alloy_signer_local::PrivateKeySigner;
@ -109,7 +109,7 @@ impl EthSigner for DevSigner {
#[cfg(test)]
mod tests {
use alloy_primitives::{Bytes, Parity, U256};
use alloy_primitives::{Bytes, U256};
use alloy_rpc_types_eth::TransactionInput;
use revm_primitives::TxKind;
@ -205,7 +205,7 @@ mod tests {
16,
)
.unwrap(),
Parity::Parity(false),
false,
);
assert_eq!(sig, expected)
}
@ -227,7 +227,7 @@ mod tests {
16,
)
.unwrap(),
Parity::Parity(true),
true,
);
assert_eq!(sig, expected)
}

View File

@ -1,14 +1,10 @@
//! L1 `eth` API types.
use alloy_consensus::Transaction as _;
use alloy_consensus::{Signed, TxEip4844Variant, TxEnvelope};
use alloy_network::{Ethereum, Network};
use alloy_primitives::{Address, TxKind};
use alloy_rpc_types::{Transaction, TransactionInfo};
use reth_primitives::TransactionSignedEcRecovered;
use reth_rpc_types_compat::{
transaction::{from_primitive_signature, GasPrice},
TransactionCompat,
};
use reth_primitives::{TransactionSigned, TransactionSignedEcRecovered};
use reth_rpc_types_compat::TransactionCompat;
/// Builds RPC transaction response for l1.
#[derive(Debug, Clone, Copy)]
@ -25,65 +21,46 @@ where
tx: TransactionSignedEcRecovered,
tx_info: TransactionInfo,
) -> Self::Transaction {
let signer = tx.signer();
let signed_tx = tx.into_signed();
let from = tx.signer();
let TransactionSigned { transaction, signature, hash } = tx.into_signed();
let to: Option<Address> = match signed_tx.kind() {
TxKind::Create => None,
TxKind::Call(to) => Some(Address(*to)),
let inner = match transaction {
reth_primitives::Transaction::Legacy(tx) => {
Signed::new_unchecked(tx, signature, hash).into()
}
reth_primitives::Transaction::Eip2930(tx) => {
Signed::new_unchecked(tx, signature, hash).into()
}
reth_primitives::Transaction::Eip1559(tx) => {
Signed::new_unchecked(tx, signature, hash).into()
}
reth_primitives::Transaction::Eip4844(tx) => {
Signed::new_unchecked(tx, signature, hash).into()
}
reth_primitives::Transaction::Eip7702(tx) => {
Signed::new_unchecked(tx, signature, hash).into()
}
#[allow(unreachable_patterns)]
_ => unreachable!(),
};
let TransactionInfo {
base_fee, block_hash, block_number, index: transaction_index, ..
} = tx_info;
let TransactionInfo { block_hash, block_number, index: transaction_index, .. } = tx_info;
let GasPrice { gas_price, max_fee_per_gas } =
Self::gas_price(&signed_tx, base_fee.map(|fee| fee as u64));
let input = signed_tx.input().to_vec().into();
let chain_id = signed_tx.chain_id();
let blob_versioned_hashes = signed_tx.blob_versioned_hashes().map(|hs| hs.to_vec());
let access_list = signed_tx.access_list().cloned();
let authorization_list = signed_tx.authorization_list().map(|l| l.to_vec());
let signature = from_primitive_signature(
*signed_tx.signature(),
signed_tx.tx_type(),
signed_tx.chain_id(),
);
Transaction {
hash: signed_tx.hash(),
nonce: signed_tx.nonce(),
from: signer,
to,
value: signed_tx.value(),
gas_price,
max_fee_per_gas,
max_priority_fee_per_gas: signed_tx.max_priority_fee_per_gas(),
signature: Some(signature),
gas: signed_tx.gas_limit(),
input,
chain_id,
access_list,
transaction_type: Some(signed_tx.tx_type() as u8),
// These fields are set to None because they are not stored as part of the
// transaction
block_hash,
block_number,
transaction_index,
// EIP-4844 fields
max_fee_per_blob_gas: signed_tx.max_fee_per_blob_gas(),
blob_versioned_hashes,
authorization_list,
}
Transaction { inner, block_hash, block_number, transaction_index, from }
}
fn otterscan_api_truncate_input(tx: &mut Self::Transaction) {
tx.input = tx.input.slice(..4);
}
fn tx_type(tx: &Self::Transaction) -> u8 {
tx.transaction_type.unwrap_or(0)
let input = match &mut tx.inner {
TxEnvelope::Eip1559(tx) => &mut tx.tx_mut().input,
TxEnvelope::Eip2930(tx) => &mut tx.tx_mut().input,
TxEnvelope::Legacy(tx) => &mut tx.tx_mut().input,
TxEnvelope::Eip4844(tx) => match tx.tx_mut() {
TxEip4844Variant::TxEip4844(tx) => &mut tx.input,
TxEip4844Variant::TxEip4844WithSidecar(tx) => &mut tx.tx.input,
},
TxEnvelope::Eip7702(tx) => &mut tx.tx_mut().input,
_ => return,
};
*input = input.slice(..4);
}
}

View File

@ -329,7 +329,7 @@ where
self.chain_events.canonical_state_stream().flat_map(|new_chain| {
let headers = new_chain.committed().headers().collect::<Vec<_>>();
futures::stream::iter(
headers.into_iter().map(reth_rpc_types_compat::block::from_primitive_with_hash),
headers.into_iter().map(|h| Header::from_consensus(h.into(), None, None)),
)
})
}

View File

@ -165,7 +165,7 @@ where
}
/// Handler for `ots_getBlockDetails`
async fn get_block_details(&self, block_number: u64) -> RpcResult<BlockDetails> {
async fn get_block_details(&self, block_number: u64) -> RpcResult<BlockDetails<Header>> {
let block_id = block_number.into();
let block = self.eth.block_by_number(block_id, true);
let block_id = block_id.into();
@ -178,7 +178,7 @@ where
}
/// Handler for `getBlockDetailsByHash`
async fn get_block_details_by_hash(&self, block_hash: B256) -> RpcResult<BlockDetails> {
async fn get_block_details_by_hash(&self, block_hash: B256) -> RpcResult<BlockDetails<Header>> {
let block = self.eth.block_by_hash(block_hash, true);
let block_id = block_hash.into();
let receipts = self.eth.block_receipts(block_id);
@ -195,7 +195,7 @@ where
block_number: u64,
page_number: usize,
page_size: usize,
) -> RpcResult<OtsBlockTransactions<RpcTransaction<Eth::NetworkTypes>>> {
) -> RpcResult<OtsBlockTransactions<RpcTransaction<Eth::NetworkTypes>, Header>> {
let block_id = block_number.into();
// retrieve full block and its receipts
let block = self.eth.block_by_number(block_id, true);
@ -239,7 +239,7 @@ where
let timestamp = Some(block.header.timestamp);
let receipts = receipts
.drain(page_start..page_end)
.zip(transactions.iter().map(Eth::TransactionCompat::tx_type))
.zip(transactions.iter().map(Transaction::ty))
.map(|(receipt, tx_ty)| {
let inner = OtsReceipt {
status: receipt.status(),