Skip to content

Commit

Permalink
chore: move to alloy pt5 (#2000)
Browse files Browse the repository at this point in the history
* chore: move to alloy pt5

* chore: add signature type

* chore: todo

* chore: remove error

* fix: error

* chore: add todo

* chore: fix errors

* chore: fix errors

* chore: compilable version

* chore: todo

* chore: lint evm input

* chore: lint executor

* chore: lint external tx

* chore: lint tx input

* chore: repalce blockchain client

* chore: remove tx types

* chore: replace keccak256

* chore: remove rng from ethers

* chore: fix merge

* chore: update evm_input

* chore: update executor

* chore: remove unused import

* chore: improve naming and proc tests

* chore: paths

* chore: doc

* fix: tx input

* chore: make more clear the types of txs

* chore: improve chain id

* chore: remove todo

* enha: refine Decodable supporting legacy and types transactions

* chore: improve

* chore: remove doc

* chore: improve

* chore: remove outdated fn because we receive type in txs now

* chore: remove unused default derive

* chore: remove unused EthersTransaction type alias

* chore: reorder
  • Loading branch information
gabriel-aranha-cw authored Feb 6, 2025
1 parent 29f6841 commit 9de7f30
Show file tree
Hide file tree
Showing 17 changed files with 213 additions and 133 deletions.
14 changes: 8 additions & 6 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,9 @@ triehash = "=0.8.4"
revm-inspectors = "=0.14.1"
alloy-rpc-types-trace = "=0.9.2"
alloy-rpc-types-eth = "=0.9.2"
alloy-consensus = "=0.9.2"
alloy-consensus = { version = "=0.9.2", features = ["k256"] }
alloy-primitives = "=0.8.15"
alloy-eips = "=0.9.2"

# network
jsonrpsee = { version = "=0.24.7", features = ["server", "client"] }
Expand Down
2 changes: 0 additions & 2 deletions src/alias.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ pub type AlloyUint256 = alloy_primitives::Uint<256, 4>;
// -----------------------------------------------------------------------------
// Ethers
// -----------------------------------------------------------------------------
pub type AlloyBlockEthersTransaction = alloy_rpc_types_eth::Block<ethers_core::types::Transaction>;
pub type EthersBytes = ethers_core::types::Bytes;
pub type EthersTransaction = ethers_core::types::Transaction;

// -----------------------------------------------------------------------------
// REVM
Expand Down
13 changes: 3 additions & 10 deletions src/bin/importer_offline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ use stratus::eth::miner::MinerMode;
use stratus::eth::primitives::Block;
use stratus::eth::primitives::BlockNumber;
use stratus::eth::primitives::ExternalReceipts;
use stratus::eth::primitives::ExternalTransaction;
use stratus::ext::spawn_named;
use stratus::ext::spawn_thread;
use stratus::log_and_err;
Expand Down Expand Up @@ -235,17 +234,11 @@ fn run_external_block_executor(
for blocks in Itertools::chunks(blocks.into_iter(), SAVER_BATCH_SIZE).into_iter() {
let mut executed_batch = Vec::with_capacity(SAVER_BATCH_SIZE);

for (mut block, receipts) in blocks {
for (block, receipts) in blocks {
if GlobalState::is_shutdown_warn(TASK_NAME) {
return Ok(());
}

// fill missing transaction_type with `v`
let BlockTransactions::Full(txs) = &mut block.transactions else {
return log_and_err!(GlobalState::shutdown_from(TASK_NAME, "expected full transactions, got hashes or uncle"));
};
txs.iter_mut().for_each(ExternalTransaction::fill_missing_transaction_type);

// TODO: remove clone
executor.execute_external_block(block.clone(), ExternalReceipts::from(receipts))?;
let mined_block = miner.mine_external(block)?;
Expand Down Expand Up @@ -318,8 +311,8 @@ async fn fetch_blocks_and_receipts(rpc_storage: Arc<PostgresExternalRpc>, block_

// perform additional checks on the transaction index
for window in transactions.windows(2) {
let tx_index = window[0].transaction_index.ok_or(anyhow!("missing transaction index"))?.as_u32();
let next_tx_index = window[1].transaction_index.ok_or(anyhow!("missing transaction index"))?.as_u32();
let tx_index = window[0].transaction_index.ok_or(anyhow!("missing transaction index"))? as u32;
let next_tx_index = window[1].transaction_index.ok_or(anyhow!("missing transaction index"))? as u32;
assert!(
tx_index + 1 == next_tx_index,
"two consecutive transactions must have consecutive indices: {} and {}",
Expand Down
20 changes: 9 additions & 11 deletions src/eth/executor/evm_input.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use alloy_consensus::Transaction;
use alloy_rpc_types_trace::geth::GethDebugTracingOptions;
use display_json::DebugAsJson;

Expand Down Expand Up @@ -139,20 +140,17 @@ impl EvmInput {
/// Successful external transactions executes with max gas and zero gas price to ensure we will have the same execution result.
pub fn from_external(tx: &ExternalTransaction, receipt: &ExternalReceipt, block_number: BlockNumber, block_timestamp: UnixTime) -> anyhow::Result<Self> {
Ok(Self {
from: tx.0.from.into(),
to: tx.0.to.map_into(),
value: tx.0.value.into(),
data: tx.0.input.clone().into(),
nonce: Some(tx.0.nonce.try_into()?),
gas_limit: if_else!(receipt.is_success(), Gas::MAX, tx.0.gas.try_into()?),
gas_price: if_else!(receipt.is_success(), Wei::ZERO, tx.0.gas_price.map_into().unwrap_or(Wei::ZERO)),
from: tx.from.into(),
to: tx.inner.to().map_into(),
value: tx.inner.value().into(),
data: tx.inner.input().clone().into(),
nonce: Some(tx.inner.nonce().into()),
gas_limit: if_else!(receipt.is_success(), Gas::MAX, tx.inner.gas_limit().into()),
gas_price: if_else!(receipt.is_success(), Wei::ZERO, tx.inner.gas_price().map_into().unwrap_or(Wei::ZERO)),
point_in_time: PointInTime::Pending,
block_number,
block_timestamp,
chain_id: match tx.0.chain_id {
Some(chain_id) => Some(chain_id.try_into()?),
None => None,
},
chain_id: tx.inner.chain_id().map(Into::into),
})
}

Expand Down
9 changes: 7 additions & 2 deletions src/eth/executor/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::mem;
use std::str::FromStr;
use std::sync::Arc;

use alloy_consensus::Transaction;
use alloy_rpc_types_trace::geth::GethDebugTracingOptions;
use alloy_rpc_types_trace::geth::GethTrace;
use anyhow::anyhow;
Expand Down Expand Up @@ -358,10 +359,14 @@ impl Executor {
) -> anyhow::Result<()> {
// track
#[cfg(feature = "metrics")]
let (start, tx_function, tx_contract) = (metrics::now(), codegen::function_sig(&tx.0.input), codegen::contract_name(&tx.0.to.map_into()));
let (start, tx_function, tx_contract) = (
metrics::now(),
codegen::function_sig(tx.inner.input()),
codegen::contract_name(&tx.0.to().map_into()),
);

#[cfg(feature = "tracing")]
let _span = info_span!("executor::external_transaction", tx_hash = %tx.hash).entered();
let _span = info_span!("executor::external_transaction", tx_hash = %tx.hash()).entered();
tracing::info!(%block_number, tx_hash = %tx.hash(), "reexecuting external transaction");

// when transaction externally failed, create fake transaction instead of reexecuting
Expand Down
4 changes: 2 additions & 2 deletions src/eth/follower/importer/importer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -455,8 +455,8 @@ impl Importer {

// perform additional checks on the transaction index
for window in transactions.windows(2) {
let tx_index = window[0].transaction_index.ok_or(anyhow!("missing transaction index"))?.as_u32();
let next_tx_index = window[1].transaction_index.ok_or(anyhow!("missing transaction index"))?.as_u32();
let tx_index = window[0].transaction_index.ok_or(anyhow!("missing transaction index"))? as u32;
let next_tx_index = window[1].transaction_index.ok_or(anyhow!("missing transaction index"))? as u32;
if tx_index + 1 != next_tx_index {
tracing::error!(tx_index, next_tx_index, "two consecutive transactions must have consecutive indices");
}
Expand Down
12 changes: 6 additions & 6 deletions src/eth/primitives/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ use alloy_rpc_types_eth::BlockTransactions;
use display_json::DebugAsJson;
use itertools::Itertools;

use crate::alias::AlloyBlockEthersTransaction;
use crate::alias::AlloyBlockAlloyTransaction;
use crate::alias::AlloyBlockH256;
use crate::alias::EthersTransaction;
use crate::alias::AlloyTransaction;
use crate::alias::JsonValue;
use crate::eth::primitives::Address;
use crate::eth::primitives::BlockHeader;
Expand Down Expand Up @@ -70,7 +70,7 @@ impl Block {

/// Serializes itself to JSON-RPC block format with full transactions included.
pub fn to_json_rpc_with_full_transactions(self) -> JsonValue {
let alloy_block: AlloyBlockEthersTransaction = self.into();
let alloy_block: AlloyBlockAlloyTransaction = self.into();
to_json_value(alloy_block)
}

Expand Down Expand Up @@ -127,10 +127,10 @@ impl Block {
// -----------------------------------------------------------------------------
// Conversions: Self -> Other
// -----------------------------------------------------------------------------
impl From<Block> for AlloyBlockEthersTransaction {
impl From<Block> for AlloyBlockAlloyTransaction {
fn from(block: Block) -> Self {
let alloy_block: AlloyBlockEthersTransaction = block.header.into();
let transactions: Vec<EthersTransaction> = block.transactions.into_iter().map_into().collect();
let alloy_block: AlloyBlockAlloyTransaction = block.header.into();
let transactions: Vec<AlloyTransaction> = block.transactions.into_iter().map_into().collect();

Self {
transactions: BlockTransactions::Full(transactions),
Expand Down
2 changes: 1 addition & 1 deletion src/eth/primitives/execution_result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ impl std::fmt::Display for RevertReason {

#[cfg(test)]
mod tests {
use ethers_core::utils::hex;
use alloy_primitives::hex;

use super::*;

Expand Down
26 changes: 6 additions & 20 deletions src/eth/primitives/external_transaction.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
use anyhow::Context;
use anyhow::Result;

use crate::alias::EthersTransaction;
use crate::alias::AlloyTransaction;
use crate::eth::primitives::BlockNumber;
use crate::eth::primitives::Hash;

#[derive(Debug, Clone, Default, derive_more::Deref, serde::Deserialize, serde::Serialize)]
#[derive(Debug, Clone, derive_more::Deref, serde::Deserialize, serde::Serialize)]
#[serde(transparent)]
pub struct ExternalTransaction(#[deref] pub EthersTransaction);
pub struct ExternalTransaction(#[deref] pub AlloyTransaction);

impl ExternalTransaction {
/// Returns the block number where the transaction was mined.
Expand All @@ -17,28 +16,15 @@ impl ExternalTransaction {

/// Returns the transaction hash.
pub fn hash(&self) -> Hash {
self.0.hash.into()
}

/// Fills the field transaction_type based on `v`
pub fn fill_missing_transaction_type(&mut self) {
// Don't try overriding if it's already set
if self.0.transaction_type.is_some() {
return;
}

let v = self.0.v.as_u64();
if [0, 1].contains(&v) {
self.0.transaction_type = Some(2.into());
}
Hash::from(*self.0.inner.tx_hash())
}
}

// -----------------------------------------------------------------------------
// Conversions: Other -> Self
// -----------------------------------------------------------------------------
impl From<EthersTransaction> for ExternalTransaction {
fn from(value: EthersTransaction) -> Self {
impl From<AlloyTransaction> for ExternalTransaction {
fn from(value: AlloyTransaction) -> Self {
ExternalTransaction(value)
}
}
3 changes: 3 additions & 0 deletions src/eth/primitives/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ mod nonce;
mod pending_block;
mod pending_block_header;
mod point_in_time;
mod signature_component;
mod size;
mod slot;
mod slot_index;
Expand Down Expand Up @@ -89,6 +90,7 @@ pub use nonce::Nonce;
pub use pending_block::PendingBlock;
pub use pending_block_header::PendingBlockHeader;
pub use point_in_time::PointInTime;
pub use signature_component::SignatureComponent;
pub use size::Size;
pub use slot::Slot;
pub use slot_index::SlotIndex;
Expand Down Expand Up @@ -168,6 +170,7 @@ mod tests {
gen_test_serde!(LogTopic);
gen_test_serde!(MinerNonce);
gen_test_serde!(Nonce);
gen_test_serde!(SignatureComponent);
gen_test_serde!(Size);
gen_test_serde!(Slot);
gen_test_serde!(SlotIndex);
Expand Down
45 changes: 45 additions & 0 deletions src/eth/primitives/signature_component.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use alloy_primitives::Uint;
use display_json::DebugAsJson;
use ethereum_types::U256;
use fake::Dummy;
use fake::Faker;
use rand::Rng;

use crate::alias::AlloyUint256;
use crate::gen_newtype_from;

/// A signature component (r or s value)
#[derive(DebugAsJson, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct SignatureComponent(pub U256);

impl Dummy<Faker> for SignatureComponent {
fn dummy_with_rng<R: Rng + ?Sized>(_: &Faker, rng: &mut R) -> Self {
Self(U256::from(rng.gen::<u64>()))
}
}

// -----------------------------------------------------------------------------
// Conversions: Other -> Self
// -----------------------------------------------------------------------------
gen_newtype_from!(self = SignatureComponent, other = U256);

impl From<Uint<256, 4>> for SignatureComponent {
fn from(value: Uint<256, 4>) -> Self {
Self(U256::from(value.to_be_bytes::<32>()))
}
}

// -----------------------------------------------------------------------------
// Conversions: Self -> Other
// -----------------------------------------------------------------------------
impl From<SignatureComponent> for AlloyUint256 {
fn from(value: SignatureComponent) -> Self {
Self::from_limbs(value.0 .0)
}
}

impl From<SignatureComponent> for U256 {
fn from(value: SignatureComponent) -> Self {
value.0
}
}
Loading

0 comments on commit 9de7f30

Please sign in to comment.