diff --git a/Cargo.toml b/Cargo.toml index 0bb4f93d..02bd10a0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -175,6 +175,11 @@ reth-zstd-compressors = { version = "0.8.2", default-features = false } reth-execution-cache = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } reth-trie-parallel = { git = "https://github.com/paradigmxyz/reth", tag = "v2.11.0" } +# StreamingFast Firehose tracer and its Reth integration (local paths pending upstream PRs/tags). +firehose-tracer = "5.7.0" +firehose-tracer-test = "5.7.0" +reth-firehose = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } + # evm2 has no release yet; this is the rev reth v2.11.0 declares, overridden by the # `[patch]` below to match reth's own `[patch]` section. evm2 = { git = "https://github.com/alloy-rs/evm2", rev = "66687c18b34d3bdbb899f5eb7605070615c03475", default-features = false } @@ -199,6 +204,7 @@ alloy-signer-local = "2.5.0" alloy-chains = { version = "0.2.33", default-features = false } async-trait = "0.1.92" auto_impl = "1" +base64 = "0.22" bytes = "1.8" bincode = "2" clap = { version = "4.5.45", features = ["derive"] } @@ -210,6 +216,7 @@ jsonrpsee = { version = "0.26.0", features = ["server", "client", "macros"] } metrics = "0.24.0" mockall = "0.14" parking_lot = "0.12.4" +prost = "0.14" rand = "0.8.5" rayon = "1.10" serde = { version = "1.0.219", features = ["derive"] } @@ -235,7 +242,66 @@ evm2 = { git = "https://github.com/DaniPopes/evm2", rev = "66687c18b34d3bdbb899f evm2-inspectors = { git = "https://github.com/DaniPopes/evm2", rev = "66687c18b34d3bdbb899f5eb7605070615c03475" } evm2-macros = { git = "https://github.com/DaniPopes/evm2", rev = "66687c18b34d3bdbb899f5eb7605070615c03475" } +# Firehose: route every Reth crate to the StreamingFast Firehose fork of Reth v2.11.0 +# (`release/reth-2.x` + chain-agnostic Morph hooks, pending upstream tag). +[patch."https://github.com/paradigmxyz/reth"] +reth-basic-payload-builder = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-chain-state = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-chainspec = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-cli = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-cli-commands = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-cli-runner = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-cli-util = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-consensus = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-consensus-common = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-db = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-db-api = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-e2e-test-utils = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-engine-local = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-engine-tree = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-errors = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-ethereum-cli = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-ethereum-primitives = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-evm = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-evm-ethereum = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-execution-cache = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-execution-errors = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-execution-types = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-exex = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-exex-test-utils = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-metrics = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-network = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-network-peers = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-node-api = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-node-builder = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-node-core = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-node-ethereum = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-payload-builder = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-payload-primitives = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-payload-util = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-provider = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-prune-types = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-rpc = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-rpc-api = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-rpc-builder = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-rpc-convert = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-rpc-eth-api = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-rpc-eth-types = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-rpc-server-types = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-stages-types = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-storage-api = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-storage-errors = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-storage-overlay = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-tasks = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-tracing = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-transaction-pool = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-trie = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-trie-common = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } +reth-trie-parallel = { git = "https://github.com/panos-xyz/reth", rev = "5e9ef20084b9a5f35328e6cf3fbe11558de36f8a" } + [patch.crates-io] +firehose-tracer = { git = "https://github.com/panos-xyz/evm-firehose-tracer-rs", rev = "dae104e9806e2973954b11a2c265e817b21db39d" } +firehose-tracer-test = { git = "https://github.com/panos-xyz/evm-firehose-tracer-rs", rev = "dae104e9806e2973954b11a2c265e817b21db39d" } reth-codecs = { git = "https://github.com/paradigmxyz/reth-core", rev = "275ce4cf5befeb9f1e8acd935ff2882d2d25fc61" } reth-codecs-derive = { git = "https://github.com/paradigmxyz/reth-core", rev = "275ce4cf5befeb9f1e8acd935ff2882d2d25fc61" } reth-primitives-traits = { git = "https://github.com/paradigmxyz/reth-core", rev = "275ce4cf5befeb9f1e8acd935ff2882d2d25fc61" } diff --git a/bin/morph-reth/src/main.rs b/bin/morph-reth/src/main.rs index 900b6b05..c6cee5b9 100644 --- a/bin/morph-reth/src/main.rs +++ b/bin/morph-reth/src/main.rs @@ -126,6 +126,14 @@ fn main() { Cli::::parse(); apply_morph_cli_defaults(&mut cli); + // Install the process-wide Firehose tracer by default before the node builds its components so + // the payload builder disables pre-inserting already-executed blocks. + if let Commands::Node(command) = &cli.command + && !command.ext.no_firehose + { + morph_node::firehose::init_tracer(); + } + // Run the node if let Err(err) = cli.run_with_components::(components, async move |builder, morph_args| { @@ -182,6 +190,7 @@ fn main() { } else { None }; + let firehose = !morph_args.no_firehose; let node = MorphNode::new(morph_args); let mut add_ons = MorphAddOns::new(); @@ -207,6 +216,12 @@ fn main() { ); } + if firehose { + node_builder = node_builder.on_component_initialized(|node| { + morph_node::firehose::init_blockchain(&node.provider) + }); + } + let handle = node_builder.launch_with_debug_capabilities().await?; info!(target: "morph::cli", "Node started successfully"); diff --git a/crates/evm/Cargo.toml b/crates/evm/Cargo.toml index 79cef8b4..ee29be1a 100644 --- a/crates/evm/Cargo.toml +++ b/crates/evm/Cargo.toml @@ -24,6 +24,8 @@ reth-ethereum-primitives = { workspace = true, features = ["serde"] } reth-execution-types.workspace = true reth-primitives-traits.workspace = true reth-rpc-eth-api = { workspace = true, optional = true } +reth-firehose = { workspace = true, optional = true } +firehose-tracer = { workspace = true, optional = true } evm2 = { workspace = true, features = ["std"] } evm2-inspectors = { workspace = true, optional = true } @@ -64,3 +66,9 @@ rpc = [ "dep:reth-rpc-eth-api", "morph-primitives/reth-codec", ] +firehose = [ + "std", + "dep:reth-firehose", + "dep:firehose-tracer", + "morph-primitives/firehose", +] diff --git a/crates/evm/src/config.rs b/crates/evm/src/config.rs index ba989534..0ec80d48 100644 --- a/crates/evm/src/config.rs +++ b/crates/evm/src/config.rs @@ -149,6 +149,22 @@ impl ConfigureEvm for MorphEvmConfig { slot_number: None, }) } + + #[cfg(feature = "firehose")] + fn batch_executor( + &self, + db: DB, + ) -> impl reth_evm::execute::Executor< + DB, + Primitives = Self::Primitives, + Error = reth_evm::execute::BlockExecutionError, + > { + reth_firehose::FirehoseBlockExecutor::new_with_chain_hooks( + self.clone(), + db, + reth_firehose::LiveChainHooks, + ) + } } #[cfg(test)] diff --git a/crates/evm/src/firehose.rs b/crates/evm/src/firehose.rs new file mode 100644 index 00000000..60fac92c --- /dev/null +++ b/crates/evm/src/firehose.rs @@ -0,0 +1,114 @@ +//! StreamingFast Firehose tracing hooks for Morph block execution on `evm2`. +//! +//! `reth-firehose` derives the post-transaction `GasRefund` and `RewardTransactionFee` balance +//! changes from Ethereum gas rules because `evm2` settles gas after the root frame returns without +//! firing inspector hooks. [`MorphPostTxExtras`] supplies Morph's gas accounting and receipt +//! metadata (`MorphTrxOutput`) for both the live engine path (`FirehoseLiveHooks`) and staged sync +//! (`LiveChainHooks`). +//! +//! Tracing is only active once the process-wide tracer is initialized; otherwise every path runs +//! identically to untraced execution. + +use crate::{MorphEvmConfig, evm::MorphEvm}; +use alloy_primitives::U256; +use evm2::TxResult; +use firehose_tracer::{ + pb::sf::ethereum::r#type::v2::{BigInt, MorphTrxOutput}, + types::{BlockData, ReceiptData, TxType}, +}; +use morph_primitives::Block; +use morph_revm::MorphEvmTypes; +use reth_firehose::{ + FirehoseInspector, FirehoseLiveHooks, NoPreTxAdjust, PostTxExtras, PostTxGasAccounting, +}; +use reth_primitives_traits::SealedBlock; +use std::ops::DerefMut; + +fn u256_to_pb(value: U256) -> Option { + (!value.is_zero()).then(|| BigInt { + bytes: value.to_be_bytes_trimmed_vec(), + }) +} + +/// Applies Morph's gas-fee rules and receipt metadata to Firehose traces. +/// +/// - An L1 message has its gas paid on L1, so nothing is refunded or rewarded on L2 and no +/// `MorphTrxOutput` is emitted. +/// - A MorphTx paying its fee in an ERC-20 token moves no native balance for gas. +/// - Every other transaction is refunded at its effective gas price, and the fee recipient +/// (`BlockFees::coinbase`, which comes from `MorphEvmConfig::evm_env` and equals the configured +/// fee vault) receives the whole effective gas price of the consumed gas (Morph does not burn the +/// base fee) plus the L1 data fee, in one `RewardTransactionFee` change. +#[derive(Debug, Clone, Copy, Default)] +pub struct MorphPostTxExtras; + +impl<'a> PostTxExtras> for MorphPostTxExtras { + fn emit_post_tx_extras>( + &self, + _evm: &mut MorphEvm<'a>, + _inspector: &FirehoseInspector, + _gas_used: u64, + _base_fee: u64, + ) { + } + + fn gas_accounting_for_tx( + &self, + _evm: &mut MorphEvm<'a>, + tx_result: &TxResult, + tx_type: TxType, + ethereum: PostTxGasAccounting, + ) -> PostTxGasAccounting { + if tx_type == TxType::MorphL1Message || tx_result.ext.token_fee_info.is_some() { + return PostTxGasAccounting::none(); + } + + PostTxGasAccounting { + refund_gas_price: ethereum.refund_gas_price, + reward_gas_price: ethereum.refund_gas_price, + extra_reward: tx_result.ext.l1_data_fee, + } + } + + fn capture_receipt_extras( + &self, + tx_result: &TxResult, + tx_type: TxType, + ) -> Option> { + if tx_type == TxType::MorphL1Message { + return None; + } + + let l1_fee = u256_to_pb(tx_result.ext.l1_data_fee); + let fee_rate = tx_result + .ext + .token_fee_info + .and_then(|info| u256_to_pb(info.price_ratio)); + let token_scale = tx_result + .ext + .token_fee_info + .and_then(|info| u256_to_pb(info.scale)); + + if l1_fee.is_none() && fee_rate.is_none() && token_scale.is_none() { + return None; + } + + let output = MorphTrxOutput { + l1_fee, + fee_rate, + token_scale, + }; + Some(Box::new(move |receipt: &mut ReceiptData| { + receipt.morph_trx_output = Some(output); + })) + } +} + +impl FirehoseLiveHooks for MorphEvmConfig { + type PreTxAdjust = NoPreTxAdjust; + type PostTxExtras = MorphPostTxExtras; + + fn adjust_block_data(&self, block: &SealedBlock, block_data: &mut BlockData) { + block_data.morph_next_l1_msg_index = Some(block.header().next_l1_msg_index); + } +} diff --git a/crates/evm/src/lib.rs b/crates/evm/src/lib.rs index 3e008f72..e248f75b 100644 --- a/crates/evm/src/lib.rs +++ b/crates/evm/src/lib.rs @@ -75,6 +75,8 @@ pub use context::MorphNextBlockEnvAttributes; mod error; pub use error::MorphEvmError; pub mod evm; +#[cfg(feature = "firehose")] +pub mod firehose; use std::sync::Arc; pub use evm::{MorphEvm, MorphEvmFactory}; diff --git a/crates/node/Cargo.toml b/crates/node/Cargo.toml index 506c60fb..bcb2d5ed 100644 --- a/crates/node/Cargo.toml +++ b/crates/node/Cargo.toml @@ -14,10 +14,10 @@ workspace = true morph-chainspec.workspace = true morph-consensus.workspace = true morph-engine-api.workspace = true -morph-evm = { workspace = true, features = ["engine"] } +morph-evm = { workspace = true, features = ["engine", "firehose"] } morph-payload-builder.workspace = true morph-payload-types.workspace = true -morph-primitives = { workspace = true, features = ["reth-codec"] } +morph-primitives = { workspace = true, features = ["reth-codec", "firehose"] } morph-proofs.workspace = true morph-reference-index.workspace = true morph-rpc.workspace = true @@ -34,6 +34,7 @@ reth-engine-tree.workspace = true reth-errors.workspace = true reth-evm = { workspace = true, features = ["std"] } reth-execution-cache.workspace = true +reth-firehose.workspace = true reth-network.workspace = true reth-node-api.workspace = true reth-node-builder.workspace = true @@ -62,6 +63,7 @@ alloy-rpc-types-eth.workspace = true # Async eyre.workspace = true +firehose-tracer.workspace = true clap.workspace = true futures.workspace = true parking_lot.workspace = true @@ -101,11 +103,14 @@ alloy-signer-local.workspace = true alloy-rpc-types-debug.workspace = true alloy-rpc-types-engine.workspace = true alloy-rpc-types-eth.workspace = true +base64.workspace = true +firehose-tracer-test.workspace = true jsonrpsee.workspace = true morph-chainspec.workspace = true morph-payload-types.workspace = true morph-primitives.workspace = true morph-proofs-exex.workspace = true +prost.workspace = true serde_json.workspace = true tempfile.workspace = true @@ -114,6 +119,11 @@ name = "it" path = "tests/it/main.rs" required-features = ["test-utils"] +[[test]] +name = "firehose" +path = "tests/firehose/main.rs" +required-features = ["test-utils"] + [features] default = [] test-utils = [ diff --git a/crates/node/src/args.rs b/crates/node/src/args.rs index 447bc9bd..0d2d24b9 100644 --- a/crates/node/src/args.rs +++ b/crates/node/src/args.rs @@ -64,6 +64,10 @@ pub struct MorphArgs { value_parser = clap::builder::RangedU64ValueParser::::new().range(1..) )] pub proofs_history_max_multi_proof_targets: usize, + + /// Disable StreamingFast Firehose block trace output (`FIRE INIT` / `FIRE BLOCK`) on stdout. + #[arg(long = "no-firehose", default_value_t = false)] + pub no_firehose: bool, } impl Default for MorphArgs { @@ -75,6 +79,7 @@ impl Default for MorphArgs { proofs_history_window: DEFAULT_PROOFS_HISTORY_WINDOW, proofs_history_verification_interval: 0, proofs_history_max_multi_proof_targets: DEFAULT_MAX_MULTI_PROOF_TARGETS, + no_firehose: false, } } } @@ -178,5 +183,15 @@ mod tests { fn test_default_trait_impl() { let args = MorphArgs::default(); assert_eq!(args.max_tx_payload_bytes, None); + assert!(!args.no_firehose); + } + + #[test] + fn firehose_is_enabled_by_default_and_can_be_disabled() { + let default_args = CommandParser::::parse_from(["test"]).args; + assert!(!default_args.no_firehose); + + let disabled_args = CommandParser::::parse_from(["test", "--no-firehose"]).args; + assert!(disabled_args.no_firehose); } } diff --git a/crates/node/src/firehose.rs b/crates/node/src/firehose.rs new file mode 100644 index 00000000..e3838806 --- /dev/null +++ b/crates/node/src/firehose.rs @@ -0,0 +1,108 @@ +//! StreamingFast Firehose output for the Morph node. +//! +//! When enabled, the node writes one `FIRE BLOCK` line to stdout for every block it executes and +//! validates, for a `fireeth reader-node` to consume. Blocks are traced while they execute: the +//! engine tree traces blocks imported through the Engine API and staged sync traces the blocks it +//! executes (see `morph_evm::firehose`). +//! +//! Following `streamingfast/reth-bsc#10`, initialization runs in the node builder's +//! `on_component_initialized` hook rather than an ExEx, avoiding ExEx WAL accumulation while +//! guaranteeing `FIRE INIT` and the genesis block precede any executed block. + +use morph_chainspec::{MorphChainSpec, MorphHardfork, MorphHardforks}; +use morph_primitives::Block; +use reth_chainspec::{EthChainSpec, EthereumHardfork, EthereumHardforks, ForkCondition}; +use reth_provider::{BlockReader, ChainSpecProvider}; + +/// Client name announced in the `FIRE INIT` line. +const CLIENT_NAME: &str = "morph-reth"; + +/// Installs the process-wide tracer writing to stdout. +/// +/// Must be called once before the node components are built so the payload builder disables +/// pre-inserting already-executed blocks. +pub fn init_tracer() { + reth_firehose::init_tracer(firehose_tracer::config::Config { + chain_client: firehose_tracer::config::ChainClient::Reth, + ..Default::default() + }); +} + +/// Builds the Firehose [`firehose_tracer::config::ChainConfig`] for a [`MorphChainSpec`]. +/// +/// Morph mainnet and Hoodi genesis files activate Shanghai/Cancun at Bernoulli (block 0) without +/// setting `shanghaiTime`/`cancunTime`, and activate Prague (EIP-7702) at Viridian +/// (`viridianTime`) rather than `pragueTime`. Reading the resolved hardfork schedule from +/// `chain_spec` ensures `firehose-tracer` enables Prague delegation tracking (`address_delegates_to`) +/// on mainnet and Hoodi as well as custom genesis files. +pub fn chain_config_from_spec(chain_spec: &MorphChainSpec) -> firehose_tracer::config::ChainConfig { + let mut config = firehose_tracer::config::ChainConfig::from_genesis(chain_spec.genesis()); + let bernoulli_at_genesis = matches!( + chain_spec.morph_fork_activation(MorphHardfork::Bernoulli), + ForkCondition::Block(0) | ForkCondition::Timestamp(0) + ); + if config.shanghai_time.is_none() && bernoulli_at_genesis { + config.shanghai_time = Some(0); + } + if config.cancun_time.is_none() && bernoulli_at_genesis { + config.cancun_time = Some(0); + } + if config.prague_time.is_none() + && let ForkCondition::Timestamp(ts) = + chain_spec.ethereum_fork_activation(EthereumHardfork::Prague) + { + config.prague_time = Some(ts); + } + config +} + +/// Announces `FIRE INIT` and, on an empty chain, emits the genesis block with Morph's header +/// `next_l1_msg_index`. +/// +/// Call once from the node builder's `on_component_initialized` hook so it runs before the +/// consensus engine can execute any block. +pub fn init_blockchain

(provider: &P) -> eyre::Result<()> +where + P: BlockReader + ChainSpecProvider, +{ + let chain_spec = provider.chain_spec(); + let genesis = chain_spec.genesis(); + reth_firehose::tracer().on_blockchain_init( + CLIENT_NAME, + env!("CARGO_PKG_VERSION"), + chain_config_from_spec(chain_spec.as_ref()), + ); + reth_firehose::emit_genesis_block_on_empty_chain_with_adjust( + provider, + genesis, + |block, block_data| { + block_data.morph_next_l1_msg_index = Some(block.header().next_l1_msg_index); + }, + ) +} + +/// Returns `true` once [`init_tracer`] (or a test tracer) has installed the process-wide tracer. +pub fn is_enabled() -> bool { + reth_firehose::is_tracer_initialized() +} + +#[cfg(test)] +mod tests { + use super::*; + use morph_chainspec::{MORPH_HOODI, MORPH_MAINNET}; + + #[test] + fn chain_config_maps_morph_forks_for_mainnet_and_hoodi() { + let mainnet = chain_config_from_spec(MORPH_MAINNET.as_ref()); + assert_eq!(mainnet.chain_id, 2818); + assert_eq!(mainnet.shanghai_time, Some(0)); + assert_eq!(mainnet.cancun_time, Some(0)); + assert_eq!(mainnet.prague_time, Some(1_762_149_600)); + + let hoodi = chain_config_from_spec(MORPH_HOODI.as_ref()); + assert_eq!(hoodi.chain_id, 2910); + assert_eq!(hoodi.shanghai_time, Some(0)); + assert_eq!(hoodi.cancun_time, Some(0)); + assert_eq!(hoodi.prague_time, Some(1_761_544_800)); + } +} diff --git a/crates/node/src/lib.rs b/crates/node/src/lib.rs index 399c8a57..7c660b3d 100644 --- a/crates/node/src/lib.rs +++ b/crates/node/src/lib.rs @@ -22,6 +22,7 @@ pub mod add_ons; pub mod args; pub mod components; +pub mod firehose; pub mod node; #[cfg(feature = "test-utils")] pub mod test_utils; diff --git a/crates/node/src/node.rs b/crates/node/src/node.rs index f9c75056..b78a0779 100644 --- a/crates/node/src/node.rs +++ b/crates/node/src/node.rs @@ -25,7 +25,7 @@ use alloy_consensus::BlockHeader; use alloy_hardforks::EthereumHardforks; use alloy_primitives::{Address, B256}; use alloy_rpc_types_engine::PayloadAttributes; -use morph_chainspec::MorphChainSpec; +use morph_chainspec::{MorphChainSpec, MorphHardforks}; use morph_payload_builder::MorphBuilderConfig; use morph_payload_types::{MorphPayloadAttributes, MorphPayloadTypes}; use morph_primitives::{Block, MorphHeader, MorphPrimitives, MorphReceipt, MorphTxEnvelope}; @@ -119,7 +119,10 @@ where type AddOns = MorphAddOns>; fn components_builder(&self) -> Self::ComponentsBuilder { - let mut config = MorphBuilderConfig::default(); + let mut config = MorphBuilderConfig::default() + // A block inserted straight from the payload builder skips execution on import, so it + // would never be traced. + .with_include_executed_block(!crate::firehose::is_enabled()); if let Some(max_tx_payload_bytes) = self.args.max_tx_payload_bytes { config = config.with_max_da_block_size(max_tx_payload_bytes); } @@ -191,13 +194,25 @@ impl PayloadAttributesBuilder for MorphPayloadAttributesBuilder { fn build(&self, parent: &SealedHeader) -> MorphPayloadAttributes { - let timestamp = std::cmp::max(parent.timestamp().saturating_add(1), unix_timestamp_now()); + // Import rejects a block whose timestamp is ahead of the local clock. From Emerald a block + // may share its parent's timestamp, so several blocks mined within one second never have + // to run ahead of the clock. + let now = unix_timestamp_now(); + let same_second = std::cmp::max(parent.timestamp(), now); + let timestamp = if self.chain_spec.is_emerald_active_at_timestamp(same_second) { + same_second + } else { + std::cmp::max(parent.timestamp().saturating_add(1), now) + }; MorphPayloadAttributes { inner: PayloadAttributes { timestamp, prev_randao: B256::random(), - suggested_fee_recipient: Address::random(), + // The block header always carries a zero beneficiary, and without a fee vault + // import execution credits fees to that header beneficiary. Any other recipient + // would make the built block's state root disagree with its own import. + suggested_fee_recipient: Address::ZERO, withdrawals: self .chain_spec .is_shanghai_active_at_timestamp(timestamp) diff --git a/crates/node/src/validator.rs b/crates/node/src/validator.rs index eab534df..6d3a0271 100644 --- a/crates/node/src/validator.rs +++ b/crates/node/src/validator.rs @@ -111,6 +111,8 @@ where >, >, Node::Provider: ChainSpecProvider, + // The engine tree traces live blocks with the hooks the EVM configuration selects. + Node::Evm: reth_firehose::FirehoseLiveHooks, PVB: PayloadValidatorBuilder, { type EngineValidator = MorphTreeEngineValidator; diff --git a/crates/node/tests/firehose/main.rs b/crates/node/tests/firehose/main.rs new file mode 100644 index 00000000..dc1c3cc0 --- /dev/null +++ b/crates/node/tests/firehose/main.rs @@ -0,0 +1,758 @@ +//! Firehose output of a Morph node driven through the Engine API and staged sync. +//! +//! The tracer is process-wide, so every test in this binary writes to one in-memory buffer and +//! finds its own blocks by hash. + +use alloy_consensus::{BlockHeader, proofs, transaction::TxHashRef}; +use alloy_eips::eip2718::Decodable2718; +use alloy_primitives::{Address, B256, Bytes, Sealable, U256, address, b256}; +use alloy_rpc_types_engine::PayloadAttributes; +use alloy_signer_local::PrivateKeySigner; +use base64::Engine as _; +use firehose_tracer::pb::sf::ethereum::r#type::v2::{ + BigInt, Block as FireBlock, TransactionTrace, TransactionTraceStatus, balance_change::Reason, + transaction_trace::Type as FireTxType, +}; +use firehose_tracer_test::BlockInvariants; +use jsonrpsee::core::client::ClientT; +use morph_evm::{MorphEvmConfig, MorphEvmFactory}; +use morph_node::test_utils::{ + L1MessageBuilder, MorphTestNode, MorphTxBuilder, TestNodeBuilder, sign_authorization, + wallet_at_index, +}; +use morph_payload_types::{ + AssembleL2BlockParams, ExecutableL2Data, MorphBuiltPayload, MorphPayloadAttributes, + MorphPayloadTypes, SafeL2Data, +}; +use morph_primitives::{MorphHeader, MorphTxEnvelope}; +use prost::Message as _; +use reth_evm::{ConfigureEvm, database::StateProviderDatabase, execute::Executor}; +use reth_node_api::{PayloadKind, PayloadTypes}; +use reth_payload_builder::BuildNewPayload; +use reth_payload_primitives::BuiltPayload; +use reth_primitives_traits::SealedBlock; +use reth_provider::{ + BlockReader, BlockReaderIdExt, ChainSpecProvider, ReceiptProvider, StateProvider, + StateProviderFactory, TransactionsProvider, +}; +use reth_transaction_pool::TransactionPool; +use std::{ + sync::OnceLock, + time::{Duration, Instant}, +}; + +/// Chain ID of `tests/assets/test-genesis.json`. +const TEST_CHAIN_ID: u64 = 2910; + +/// Fee vault configured in `tests/assets/test-genesis.json`; the block beneficiary during execution. +const FEE_VAULT: Address = address!("0x530000000000000000000000000000000000000a"); + +const POLL_BUDGET: Duration = Duration::from_secs(10); + +fn signer(index: u32) -> PrivateKeySigner { + wallet_at_index(index, TEST_CHAIN_ID) +} + +/// Installs the process-wide tracer on first use. Must run before a node is built, since the node +/// decides at build time whether built payloads may skip execution on import. +fn tracer_output() -> &'static firehose_tracer::InMemoryBuffer { + static OUTPUT: OnceLock = OnceLock::new(); + OUTPUT.get_or_init(|| { + reth_firehose::init_tracer_with_buffer(TEST_CHAIN_ID, Some(0), Some(0), Some(0)) + }) +} + +/// Every `FIRE BLOCK` emitted so far with the given hash. +fn fire_blocks_with_hash(hash: B256) -> Vec { + let output = tracer_output().get_bytes(); + let text = String::from_utf8(output).expect("tracer output is UTF-8"); + text.lines() + .filter(|line| line.starts_with("FIRE BLOCK ")) + .map(|line| { + let payload = line.rsplit(' ').next().expect("FIRE BLOCK payload"); + let bytes = base64::engine::general_purpose::STANDARD + .decode(payload) + .expect("FIRE BLOCK payload is base64"); + FireBlock::decode(bytes.as_slice()).expect("FIRE BLOCK payload is a block") + }) + .filter(|block| block.hash == hash.as_slice()) + .collect() +} + +/// Waits for the block with `hash` to be emitted once, validates Firehose block invariants, and +/// returns it. +async fn traced_block(hash: B256) -> eyre::Result { + let deadline = Instant::now() + POLL_BUDGET; + loop { + let mut blocks = fire_blocks_with_hash(hash); + match blocks.len() { + 0 if Instant::now() < deadline => tokio::time::sleep(Duration::from_millis(25)).await, + 0 => return Err(eyre::eyre!("block {hash} was never traced")), + 1 => { + let block = blocks.remove(0); + BlockInvariants::assert(&block) + .map_err(|err| eyre::eyre!("Firehose block invariants violated:\n{err}"))?; + return Ok(block); + } + n => return Err(eyre::eyre!("block {hash} was traced {n} times")), + } + } +} + +async fn start_node() -> eyre::Result { + tracer_output(); + let (mut nodes, _wallet) = TestNodeBuilder::new().build().await?; + Ok(nodes.pop().expect("one node")) +} + +async fn send_to_pool(node: &MorphTestNode, raw: Bytes) -> eyre::Result { + let hash: B256 = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("node has no RPC client"))? + .request("eth_sendRawTransaction", (raw,)) + .await?; + let deadline = Instant::now() + POLL_BUDGET; + while !node.inner.pool.contains(&hash) { + if Instant::now() > deadline { + return Err(eyre::eyre!("transaction {hash} never reached the pool")); + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + Ok(hash) +} + +async fn assemble_and_import( + node: &MorphTestNode, + params: AssembleL2BlockParams, +) -> eyre::Result { + let client = node.auth_server_handle().http_client(); + let data: ExecutableL2Data = client.request("engine_assembleL2Block", (params,)).await?; + let _: MorphHeader = client + .request("engine_newL2BlockV2", (data.clone(),)) + .await?; + Ok(data) +} + +fn big(value: &Option) -> U256 { + value + .as_ref() + .map(|value| U256::from_be_slice(&value.bytes)) + .unwrap_or_default() +} + +/// `(address, increase, decrease)` of every balance change of `trace` with `reason`. +fn balance_deltas(trace: &TransactionTrace, reason: Reason) -> Vec<(Address, U256, U256)> { + trace + .calls + .iter() + .flat_map(|call| &call.balance_changes) + .filter(|change| change.reason == reason as i32) + .map(|change| { + let (old, new) = (big(&change.old_value), big(&change.new_value)); + ( + Address::from_slice(&change.address), + new.saturating_sub(old), + old.saturating_sub(new), + ) + }) + .collect() +} + +fn eip1559_call( + signer: &PrivateKeySigner, + nonce: u64, + to: Address, + value: u64, + gas_limit: u64, +) -> eyre::Result { + use alloy_consensus::{SignableTransaction, TxEip1559}; + use alloy_eips::eip2718::Encodable2718; + use alloy_primitives::TxKind; + use alloy_signer::SignerSync; + + let tx = TxEip1559 { + chain_id: TEST_CHAIN_ID, + nonce, + gas_limit, + max_fee_per_gas: 20_000_000_000, + max_priority_fee_per_gas: 1_000_000_000, + to: TxKind::Call(to), + value: U256::from(value), + access_list: Default::default(), + input: Bytes::new(), + }; + let signature = signer.sign_hash_sync(&tx.signature_hash())?; + Ok(MorphTxEnvelope::Eip1559(tx.into_signed(signature)) + .encoded_2718() + .into()) +} + +/// A block the node assembles itself is inserted into the engine tree before it is imported, which +/// would skip the execution that tracing observes. The node must execute it on import instead. +#[tokio::test(flavor = "multi_thread")] +async fn assembled_block_is_traced_once_on_import() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + let node = start_node().await?; + + let tx_hash = send_to_pool( + &node, + eip1559_call(&signer(0), 0, Address::with_last_byte(0x10), 101, 21_000)?, + ) + .await?; + let data = assemble_and_import(&node, AssembleL2BlockParams::empty(1)).await?; + assert_eq!(data.transactions.len(), 1, "the pooled transfer is included"); + + let block = traced_block(data.hash).await?; + assert_eq!(block.number, 1); + assert_eq!( + block.header.as_ref().expect("header").morph_next_l1_msg_index, + Some(0) + ); + assert_eq!(block.transaction_traces.len(), 1); + assert_eq!(block.transaction_traces[0].hash, tx_hash.as_slice()); + Ok(()) +} + +/// Morph credits the beneficiary the whole effective gas price of the consumed gas plus the L1 +/// data fee, refunds unused gas at the effective gas price, and records `l1_fee` on the receipt. +#[tokio::test(flavor = "multi_thread")] +async fn eth_fee_balance_changes_follow_morph_fee_rules() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + let node = start_node().await?; + + let signer = signer(1); + let sender = signer.address(); + // Leaves unused gas to refund and a fee cap above base fee plus tip, so the effective price + // differs from both the cap and the base fee. + let tx_hash = send_to_pool( + &node, + eip1559_call(&signer, 0, Address::with_last_byte(0x42), 100, 60_000)?, + ) + .await?; + let data = assemble_and_import(&node, AssembleL2BlockParams::empty(1)).await?; + let block = traced_block(data.hash).await?; + let trace = &block.transaction_traces[0]; + + let receipt = node + .inner + .provider + .receipt_by_hash(tx_hash)? + .ok_or_else(|| eyre::eyre!("missing receipt"))?; + let l1_fee = receipt.l1_fee(); + assert!(!l1_fee.is_zero(), "the test genesis charges an L1 data fee"); + + let price = big(&trace.gas_price); + let gas_limit = U256::from(trace.gas_limit); + let gas_used = U256::from(trace.gas_used); + + assert_eq!( + balance_deltas(trace, Reason::GasBuy), + vec![(sender, U256::ZERO, gas_limit * price + l1_fee)], + "the gas buy includes the L1 data fee" + ); + assert_eq!( + balance_deltas(trace, Reason::GasRefund), + vec![(sender, (gas_limit - gas_used) * price, U256::ZERO)], + ); + assert_eq!( + balance_deltas(trace, Reason::RewardTransactionFee), + vec![(FEE_VAULT, gas_used * price + l1_fee, U256::ZERO)], + "one reward carries the full execution fee and the L1 data fee" + ); + + let morph_output = trace + .receipt + .as_ref() + .expect("receipt") + .morph_trx_output + .as_ref() + .expect("ETH tx with L1 fee emits morph_trx_output"); + assert_eq!(big(&morph_output.l1_fee), l1_fee); + assert!(morph_output.fee_rate.is_none()); + assert!(morph_output.token_scale.is_none()); + Ok(()) +} + +/// L1 messages pay for gas on L1: they emit `TrxTypeMorphL1Message` + `MorphL1MessageTrxInput`, +/// advance `BlockHeader.morph_next_l1_msg_index`, bump the sender nonce, and move no L2 gas fee. +#[tokio::test(flavor = "multi_thread")] +async fn l1_messages_trace_morph_metadata_and_move_no_gas_fees() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + let node = start_node().await?; + + let sender = address!("0x00000000000000000000000000000000000fee01"); + let messages = (0..2) + .map(|queue_index| { + L1MessageBuilder::new(queue_index) + .with_sender(sender) + .with_target(Address::with_last_byte(0x12)) + .build_encoded() + }) + .collect(); + let data = assemble_and_import( + &node, + AssembleL2BlockParams { + number: 1, + transactions: messages, + timestamp: None, + }, + ) + .await?; + let block = traced_block(data.hash).await?; + assert_eq!( + block.header.as_ref().expect("header").morph_next_l1_msg_index, + Some(2) + ); + assert_eq!(block.transaction_traces.len(), 2); + + for (index, trace) in block.transaction_traces.iter().enumerate() { + assert_eq!(trace.r#type, FireTxType::TrxTypeMorphL1Message as i32); + assert_eq!(trace.nonce, 0); + assert!(trace.gas_price.is_none()); + assert!(trace.v.is_empty()); + assert!(trace.r.is_empty()); + assert!(trace.s.is_empty()); + assert!(trace.morph_trx_input.is_none()); + assert_eq!( + trace + .morph_l1_message_trx_input + .as_ref() + .expect("morph_l1_message_trx_input") + .queue_index, + index as u64 + ); + assert!( + trace + .receipt + .as_ref() + .expect("receipt") + .morph_trx_output + .is_none(), + "L1 message has no MorphTrxOutput" + ); + + for reason in [ + Reason::GasBuy, + Reason::GasRefund, + Reason::RewardTransactionFee, + ] { + assert!( + balance_deltas(trace, reason).is_empty(), + "L1 message {index} must not carry {reason:?}" + ); + } + let nonce_changes: Vec<_> = trace + .calls + .iter() + .flat_map(|call| &call.nonce_changes) + .map(|change| { + ( + Address::from_slice(&change.address), + change.old_value, + change.new_value, + ) + }) + .collect(); + assert_eq!( + nonce_changes, + vec![(sender, index as u64, index as u64 + 1)] + ); + } + Ok(()) +} + +/// MorphTx V1 paying ETH (`fee_token_id == 0`) emits `TrxTypeMorph`, `MorphTrxInput` (version, +/// reference, memo), `MorphTrxOutput.l1_fee`, and Morph ETH gas accounting. +#[tokio::test(flavor = "multi_thread")] +async fn morph_tx_v1_eth_fee_traces_input_output_and_fees() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + let node = start_node().await?; + + let signer = signer(0); + let sender = signer.address(); + let reference = b256!("0x11223344556677889900aabbccddeeff11223344556677889900aabbccddeeff"); + let memo = Bytes::from_static(b"morph-firehose-v1-eth"); + + let raw = MorphTxBuilder::new(TEST_CHAIN_ID, signer, 0) + .with_v1_eth_fee() + .with_to(Address::with_last_byte(0x21)) + .with_value(U256::from(250)) + .with_gas_limit(60_000) + .with_fees(20_000_000_000, 1_000_000_000) + .with_reference(reference) + .with_memo(memo.clone()) + .build_signed()?; + + let tx_hash = send_to_pool(&node, raw).await?; + let data = assemble_and_import(&node, AssembleL2BlockParams::empty(1)).await?; + let block = traced_block(data.hash).await?; + let trace = &block.transaction_traces[0]; + + assert_eq!(trace.hash, tx_hash.as_slice()); + assert_eq!(trace.r#type, FireTxType::TrxTypeMorph as i32); + assert!(trace.morph_l1_message_trx_input.is_none()); + + let input = trace + .morph_trx_input + .as_ref() + .expect("MorphTx carries morph_trx_input"); + assert_eq!(input.version, 1); + assert_eq!(input.fee_token_id, 0); + assert!(input.fee_limit.is_none()); + assert_eq!(input.reference, reference.as_slice()); + assert_eq!(input.memo, memo.as_ref()); + + let receipt = node + .inner + .provider + .receipt_by_hash(tx_hash)? + .ok_or_else(|| eyre::eyre!("missing receipt"))?; + let l1_fee = receipt.l1_fee(); + assert!(!l1_fee.is_zero()); + + let output = trace + .receipt + .as_ref() + .expect("receipt") + .morph_trx_output + .as_ref() + .expect("morph_trx_output"); + assert_eq!(big(&output.l1_fee), l1_fee); + assert!(output.fee_rate.is_none()); + assert!(output.token_scale.is_none()); + + let price = big(&trace.gas_price); + let gas_limit = U256::from(trace.gas_limit); + let gas_used = U256::from(trace.gas_used); + assert_eq!( + balance_deltas(trace, Reason::GasBuy), + vec![(sender, U256::ZERO, gas_limit * price + l1_fee)] + ); + assert_eq!( + balance_deltas(trace, Reason::GasRefund), + vec![(sender, (gas_limit - gas_used) * price, U256::ZERO)] + ); + assert_eq!( + balance_deltas(trace, Reason::RewardTransactionFee), + vec![(FEE_VAULT, gas_used * price + l1_fee, U256::ZERO)] + ); + Ok(()) +} + +/// MorphTx V2 paying ETH (`fee_token_id == 0`) populates EIP-7702 `set_code_authorizations`, +/// distinguishes applied vs discarded tuples, and records `address_delegates_to` when calling the +/// delegated authority. +#[tokio::test(flavor = "multi_thread")] +async fn morph_tx_v2_eth_fee_traces_set_code_authorizations() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + tracer_output(); + + // Minimal delegate contract: STOP (0x00) + let delegate = address!("0x000000000000000000000000000000000000c0de"); + let (mut nodes, _wallet) = TestNodeBuilder::new() + .with_account_code(delegate, "0x00") + .build() + .await?; + let node = nodes.pop().expect("one node"); + + let tx_signer = signer(1); + let authority_signer = signer(2); + let authority = authority_signer.address(); + + let valid_auth = sign_authorization(&authority_signer, TEST_CHAIN_ID, delegate, 0)?; + // Nonce mismatch so the second tuple must be discarded by EIP-7702 validation. + let discarded_auth = sign_authorization(&authority_signer, TEST_CHAIN_ID, delegate, 99)?; + + let reference = b256!("0xabcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"); + let memo = Bytes::from_static(b"morph-firehose-v2-auth"); + + let raw = MorphTxBuilder::new(TEST_CHAIN_ID, tx_signer, 0) + .with_v2_eth_fee() + .with_to(authority) + .with_gas_limit(120_000) + .with_fees(20_000_000_000, 1_000_000_000) + .with_reference(reference) + .with_memo(memo.clone()) + .with_authorization_list(vec![valid_auth, discarded_auth]) + .build_signed()?; + + let tx_hash = send_to_pool(&node, raw).await?; + let data = assemble_and_import(&node, AssembleL2BlockParams::empty(1)).await?; + let block = traced_block(data.hash).await?; + let trace = &block.transaction_traces[0]; + + assert_eq!(trace.hash, tx_hash.as_slice()); + assert_eq!(trace.r#type, FireTxType::TrxTypeMorph as i32); + assert_eq!(trace.status, TransactionTraceStatus::Succeeded as i32); + + let input = trace.morph_trx_input.as_ref().expect("morph_trx_input"); + assert_eq!(input.version, 2); + assert_eq!(input.fee_token_id, 0); + assert_eq!(input.reference, reference.as_slice()); + assert_eq!(input.memo, memo.as_ref()); + + assert_eq!(trace.set_code_authorizations.len(), 2); + let first = &trace.set_code_authorizations[0]; + assert_eq!(first.authority.as_deref(), Some(authority.as_slice())); + assert_eq!(first.address, delegate.as_slice()); + assert_eq!(first.nonce, 0); + assert!(!first.discarded, "valid authorization must not be discarded"); + + let second = &trace.set_code_authorizations[1]; + assert_eq!(second.authority.as_deref(), Some(authority.as_slice())); + assert_eq!(second.nonce, 99); + assert!(second.discarded, "wrong-nonce authorization must be discarded"); + + let root = &trace.calls[0]; + assert_eq!(root.address, authority.as_slice()); + assert_eq!( + root.address_delegates_to.as_deref(), + Some(delegate.as_slice()), + "calling the delegated authority resolves address_delegates_to" + ); + Ok(()) +} + +/// A safe block is rebuilt by the payload builder before it is imported, so it takes the same +/// path as an assembled block and must be traced when imported. +#[tokio::test(flavor = "multi_thread")] +async fn safe_block_is_traced_on_import() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + let node = start_node().await?; + + let genesis = node + .inner + .provider + .sealed_header_by_number_or_tag(alloy_rpc_types_eth::BlockNumberOrTag::Latest)? + .ok_or_else(|| eyre::eyre!("missing genesis header"))?; + let raw = eip1559_call(&signer(2), 0, Address::with_last_byte(0x22), 102, 21_000)?; + let tx: MorphTxEnvelope = Decodable2718::decode_2718(&mut raw.as_ref())?; + let tx_hash = *tx.tx_hash(); + + let safe = SafeL2Data { + number: 1, + gas_limit: genesis.gas_limit(), + base_fee_per_gas: None, + timestamp: genesis.timestamp() + 1, + transactions: vec![raw], + parent_hash: None, + }; + let header: MorphHeader = node + .auth_server_handle() + .http_client() + .request("engine_newSafeL2Block", (safe,)) + .await?; + + let block = traced_block(header.hash_slow()).await?; + assert_eq!(block.number, 1); + assert_eq!(block.transaction_traces.len(), 1); + assert_eq!(block.transaction_traces[0].hash, tx_hash.as_slice()); + assert!( + node.inner.provider.transaction_by_hash(tx_hash)?.is_some(), + "the safe block was imported" + ); + Ok(()) +} + +/// A block that executes but fails post-execution validation is discarded, and the next valid +/// block at the same height is still traced. +#[tokio::test(flavor = "multi_thread")] +async fn block_failing_validation_is_not_traced() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + let node = start_node().await?; + + let payload = build_payload(&node).await?; + let mut block = payload.block().clone_block(); + block.header.inner.state_root = B256::repeat_byte(0xff); + block.header.inner.transactions_root = + proofs::calculate_transaction_root(&block.body.transactions); + let tampered = SealedBlock::seal_slow(block); + let tampered_hash = tampered.hash(); + + let status = node + .inner + .add_ons_handle + .beacon_engine_handle + .new_payload(MorphPayloadTypes::block_to_payload(tampered, None)) + .await?; + assert!( + status.is_invalid(), + "tampered state root is rejected: {status:?}" + ); + + let valid_hash = payload.block().hash(); + let status = node + .inner + .add_ons_handle + .beacon_engine_handle + .new_payload(MorphPayloadTypes::block_to_payload( + payload.block().clone(), + None, + )) + .await?; + assert!( + status.is_valid(), + "untampered block is accepted: {status:?}" + ); + + assert_eq!(traced_block(valid_hash).await?.number, 1); + assert!( + fire_blocks_with_hash(tampered_hash).is_empty(), + "a block failing validation must not be emitted" + ); + Ok(()) +} + +/// Morph replaces SELFDESTRUCT with an undefined instruction, so calling it halts the call without +/// destroying anything, and the trace must not report a self-destruct. +#[tokio::test(flavor = "multi_thread")] +async fn disabled_selfdestruct_is_not_reported() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + tracer_output(); + let target = address!("0x000000000000000000000000000000000000dead"); + // CALLER SELFDESTRUCT + let (mut nodes, _wallet) = TestNodeBuilder::new() + .with_account_code(target, "0x33ff") + .build() + .await?; + let node = nodes.pop().expect("one node"); + + let gas_limit = 100_000; + let tx_hash = send_to_pool(&node, eip1559_call(&signer(3), 0, target, 100, gas_limit)?).await?; + let data = assemble_and_import(&node, AssembleL2BlockParams::empty(1)).await?; + let block = traced_block(data.hash).await?; + let trace = &block.transaction_traces[0]; + assert_eq!(trace.hash, tx_hash.as_slice()); + + assert_eq!(trace.status, TransactionTraceStatus::Failed as i32); + assert_eq!(trace.gas_used, gas_limit, "a halt consumes all the gas"); + let root = &trace.calls[0]; + assert!(root.status_failed); + assert!(!root.suicide, "an undefined SELFDESTRUCT destroys nothing"); + assert!( + balance_deltas(trace, Reason::SuicideWithdraw).is_empty() + && balance_deltas(trace, Reason::SuicideRefund).is_empty() + ); + Ok(()) +} + +/// Staged-sync batch execution (`MorphEvmConfig::batch_executor`) must produce the exact same +/// Firehose protobuf `Block` as live Engine API import for blocks combining L1 messages, +/// MorphTx (ETH-fee), and standard EIP-1559 transactions. +#[tokio::test(flavor = "multi_thread")] +async fn staged_sync_batch_executor_matches_live_import() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + let node = start_node().await?; + + let l1_sender = address!("0x00000000000000000000000000000000000fee99"); + let l1_msg = L1MessageBuilder::new(0) + .with_sender(l1_sender) + .with_target(Address::with_last_byte(0x91)) + .build_encoded(); + + let morph_tx = MorphTxBuilder::new(TEST_CHAIN_ID, signer(0), 0) + .with_v1_eth_fee() + .with_to(Address::with_last_byte(0x92)) + .with_value(U256::from(333)) + .with_gas_limit(60_000) + .with_fees(20_000_000_000, 2_000_000_000) + .with_reference(b256!( + "0x99887766554433221100ffeeddccbbaa99887766554433221100ffeeddccbbaa" + )) + .with_memo(Bytes::from_static(b"staged-vs-live-parity")) + .build_signed()?; + + let eth_tx = eip1559_call(&signer(1), 0, Address::with_last_byte(0x93), 444, 50_000)?; + + send_to_pool(&node, morph_tx).await?; + send_to_pool(&node, eth_tx).await?; + + let data = assemble_and_import( + &node, + AssembleL2BlockParams { + number: 1, + transactions: vec![l1_msg], + timestamp: None, + }, + ) + .await?; + assert_eq!(data.transactions.len(), 3); + + let live_block = traced_block(data.hash).await?; + assert_eq!(live_block.transaction_traces.len(), 3); + assert_eq!( + live_block + .header + .as_ref() + .expect("header") + .morph_next_l1_msg_index, + Some(1) + ); + + let recovered = node + .inner + .provider + .recovered_block(data.hash.into(), Default::default())? + .ok_or_else(|| eyre::eyre!("missing imported block"))?; + + let genesis_state = node.inner.provider.history_by_block_number(0)?; + let db = StateProviderDatabase::new(genesis_state.into_evm_state_provider()); + let evm_config = + MorphEvmConfig::new(node.inner.provider.chain_spec(), MorphEvmFactory::default()); + let mut batch_executor = evm_config.batch_executor(db); + batch_executor.execute_and_trace_one(&recovered, None)?; + let _ = batch_executor.into_state(); + + let blocks = fire_blocks_with_hash(data.hash); + assert_eq!( + blocks.len(), + 2, + "staged-sync replay must emit one additional block" + ); + BlockInvariants::assert(&blocks[1]) + .map_err(|err| eyre::eyre!("staged-sync Firehose block invariants violated:\n{err}"))?; + assert_eq!( + blocks[1], live_block, + "staged-sync trace must match live Engine API import identically" + ); + Ok(()) +} + +async fn build_payload(node: &MorphTestNode) -> eyre::Result { + let head = node + .inner + .provider + .sealed_header_by_number_or_tag(alloy_rpc_types_eth::BlockNumberOrTag::Latest)? + .ok_or_else(|| eyre::eyre!("missing head"))?; + let attributes = MorphPayloadAttributes { + inner: PayloadAttributes { + timestamp: head.timestamp() + 1, + prev_randao: B256::ZERO, + suggested_fee_recipient: Address::ZERO, + withdrawals: Some(vec![]), + parent_beacon_block_root: Some(B256::ZERO), + slot_number: None, + target_gas_limit: None, + }, + transactions: Some(vec![]), + no_tx_pool: true, + gas_limit: None, + base_fee_per_gas: None, + }; + let payload_id = node + .inner + .payload_builder_handle + .send_new_payload(BuildNewPayload { + attributes, + parent_hash: head.hash(), + resources: Default::default(), + }) + .await? + .map_err(|error| eyre::eyre!("payload build failed: {error}"))?; + node.inner + .payload_builder_handle + .resolve_kind(payload_id, PayloadKind::WaitForPending) + .await + .ok_or_else(|| eyre::eyre!("no payload for {payload_id:?}"))? + .map_err(|error| eyre::eyre!("payload build error: {error}")) +} diff --git a/crates/payload/builder/src/builder.rs b/crates/payload/builder/src/builder.rs index f0baf720..a2cb6247 100644 --- a/crates/payload/builder/src/builder.rs +++ b/crates/payload/builder/src/builder.rs @@ -1188,7 +1188,7 @@ where // therefore carry no execution artifacts: the ones the CL does commit are executed // again on import, which costs nothing for a block without transactions. Blocks // with transactions keep the artifacts so their import remains a no-op. - let executed = has_transactions.then(|| { + let executed = (has_transactions && ctx.builder_config.include_executed_block).then(|| { let execution_output = BlockExecutionOutput { result: execution_result, state: execution_state, diff --git a/crates/payload/builder/src/config.rs b/crates/payload/builder/src/config.rs index a511e3d9..bc6ef4be 100644 --- a/crates/payload/builder/src/config.rs +++ b/crates/payload/builder/src/config.rs @@ -50,6 +50,13 @@ pub struct MorphBuilderConfig { /// /// Seeded from `--builder.gaslimit` / `--miner.gaslimit`. pub desired_gas_limit: Option, + + /// Whether a built payload carries its executed block. + /// + /// When it does, the node inserts the block into the engine tree as soon as it is built, so + /// the later import of that block skips execution. Disable it when every imported block must + /// be executed on import, as Firehose tracing requires. + pub include_executed_block: bool, } impl Default for MorphBuilderConfig { @@ -62,6 +69,7 @@ impl Default for MorphBuilderConfig { max_da_block_size: None, // No header gas target: copy parent gasLimit desired_gas_limit: None, + include_executed_block: true, } } } @@ -91,6 +99,12 @@ impl MorphBuilderConfig { self } + /// Sets whether built payloads carry their executed block. + pub const fn with_include_executed_block(mut self, include_executed_block: bool) -> Self { + self.include_executed_block = include_executed_block; + self + } + /// Header `gasLimit` for the next block. /// /// Explicit payload-attribute overrides (safe/derivation import) win. Otherwise the diff --git a/crates/primitives/Cargo.toml b/crates/primitives/Cargo.toml index d0c9a8b9..a95aa2c5 100644 --- a/crates/primitives/Cargo.toml +++ b/crates/primitives/Cargo.toml @@ -17,6 +17,8 @@ reth-codecs = { workspace = true, optional = true } reth-db-api = { workspace = true, optional = true } reth-zstd-compressors = { workspace = true, optional = true } reth-ethereum-primitives = { workspace = true, optional = true } +reth-firehose = { workspace = true, optional = true } +firehose-tracer = { workspace = true, optional = true } # Alloy alloy-consensus.workspace = true @@ -64,3 +66,4 @@ reth-codec = [ "dep:bytes", "reth-primitives-traits/reth-codec", ] +firehose = ["dep:reth-firehose", "dep:firehose-tracer"] diff --git a/crates/primitives/src/transaction/envelope.rs b/crates/primitives/src/transaction/envelope.rs index 4e334a06..f60afa00 100644 --- a/crates/primitives/src/transaction/envelope.rs +++ b/crates/primitives/src/transaction/envelope.rs @@ -233,6 +233,74 @@ impl alloy_consensus::transaction::SignerRecoverable for MorphTxEnvelope { } } +/// Signature values and Morph-specific transaction event mapping for Firehose tracing. +#[cfg(feature = "firehose")] +impl reth_firehose::mapper::SignatureFields for MorphTxEnvelope { + fn signature_fields(&self) -> (B256, B256, Bytes) { + use reth_firehose::mapper::u64_to_trimmed_bytes; + + let (signature, v) = match self { + Self::Legacy(tx) => { + let parity = tx.signature().v() as u64; + let v = match tx.tx().chain_id { + Some(chain_id) => chain_id * 2 + 35 + parity, + None => 27 + parity, + }; + (tx.signature(), v) + } + Self::Eip2930(tx) => (tx.signature(), tx.signature().v() as u64), + Self::Eip1559(tx) => (tx.signature(), tx.signature().v() as u64), + Self::Eip7702(tx) => (tx.signature(), tx.signature().v() as u64), + Self::Morph(tx) => (tx.signature(), tx.signature().v() as u64), + // L1 messages are relayed from L1 and carry no signature. + Self::L1Msg(_) => return (B256::ZERO, B256::ZERO, Bytes::new()), + }; + ( + signature.r().into(), + signature.s().into(), + u64_to_trimmed_bytes(v), + ) + } + + fn firehose_tx_type(&self, raw_type: u8) -> Result { + use firehose_tracer::types::TxType; + + match self { + Self::Morph(_) => Ok(TxType::Morph), + Self::L1Msg(_) => Ok(TxType::MorphL1Message), + _ => raw_type.try_into().map_err(|_| raw_type), + } + } + + fn populate_tx_event(&self, event: &mut firehose_tracer::types::TxEvent) { + use firehose_tracer::pb::sf::ethereum::r#type::v2::{ + BigInt, MorphL1MessageTrxInput, MorphTrxInput, + }; + + match self { + Self::Morph(signed) => { + let tx = signed.tx(); + event.morph_trx_input = Some(MorphTrxInput { + version: u32::from(tx.version), + fee_token_id: u32::from(tx.fee_token_id), + fee_limit: (!tx.fee_limit.is_zero()).then(|| BigInt { + bytes: tx.fee_limit.to_be_bytes_trimmed_vec(), + }), + reference: tx.reference.map(|r| r.0.to_vec()).unwrap_or_default(), + memo: tx.memo.as_ref().map(|m| m.to_vec()).unwrap_or_default(), + }); + } + Self::L1Msg(sealed) => { + event.v = None; + event.morph_l1_message_trx_input = Some(MorphL1MessageTrxInput { + queue_index: sealed.queue_index, + }); + } + _ => {} + } + } +} + #[cfg(feature = "reth-codec")] mod codec { use crate::L1_TX_TYPE_ID;