From 986b2626bcb1dd15e6e56d56a426ebc6ea994704 Mon Sep 17 00:00:00 2001 From: panos-xyz Date: Thu, 26 Nov 2026 16:34:11 +0800 Subject: [PATCH 1/4] fix(sequencer,engine,consensus): resolve v1.5.0 sequencer, engine API, consensus, and builder audit findings - M-C02 (node/validator): enforce first_queue_index >= parent.next_l1_msg_index across all hardforks (pre-Jade and post-Jade), rejecting cross-block L1 replay with cacheable MorphConsensusError::L1MessagesNotInOrder while preserving forward skips and post-Jade transient InvalidNextL1MessageIndex. - M-H09 (payload/builder): validate supplied L1 message queue_index == info.next_l1_message_index before EVM execution and use checked_add(1) to prevent u64::MAX wrap/panic. - M-H07 (engine-api, node/validator): validate unhashed next_l1_message_index before engine_handle.new_payload in validate_l2_block and import_l2_block_via_engine so AlreadySeen hits cannot bypass it (and without poisoning invalid_headers); run lightweight MorphConsensus + L1-index checks in MorphTreeEngineValidator::on_inserted_executed_block; unify expected_withdraw_trie_roots under a single Mutex and bypass cache insertion on live validate_payload and AlreadySeen/None-root conversions. - M-H08 (engine-api): respect emerald_active in payload_timestamp(None) so post-Emerald defaults to now.max(parent_timestamp) instead of parent_timestamp + 1. - M-H10 (payload/builder, revm/handler, rpc/transaction): enforce MorphTx hardfork gates (Emerald/Jade/Celadon) and TxMorph::validate() against target block timestamp for supplied and pool txs; gate MorphTx V2 on hardfork.is_celadon() in validate_morph_tx_authorization_list when !is_fee_charge_disabled() (preserving pre-Celadon Prague simulation); reject memo > 64 bytes and fee_token_id == 0 && fee_limit > 0 in try_into_tx_env. - M-M10 (engine-api): in set_block_tags, verify canonicality via provider.block_hash, enforce effective_finalized <= effective_safe <= canonical_head across partial updates using existing provider tags, route updates through engine_handle.fork_choice_updated (safe before finalized when both non-zero, serialized with import_l2_block_via_engine via fcu_lock) so tags persist to MDBX and update metrics, and preserve cached l1_finalized_hash when finalized_block_hash == B256::ZERO. - M-M11 (engine-api): serialize build_l2_payload with build_lock (tokio::sync::Mutex) to prevent concurrent deterministic PayloadId collisions. - M-M12 (evm, payload/builder): evict pool transactions failing with deterministic MorphInvalidTransaction token-fee errors (excluding InsufficientTokenBalance) when the sender has not executed an earlier tx in the same block. --- Cargo.lock | 5 +- crates/engine-api/Cargo.toml | 1 + crates/engine-api/src/builder.rs | 296 +++++- crates/evm/src/lib.rs | 2 +- crates/node/Cargo.toml | 2 +- crates/node/src/validator.rs | 325 +++++-- crates/node/tests/it/consensus.rs | 75 ++ crates/node/tests/it/engine.rs | 260 +++++- .../node/tests/it/invalid_payload_recovery.rs | 164 +++- crates/payload/builder/Cargo.toml | 2 + crates/payload/builder/src/builder.rs | 859 +++++++++++++++++- crates/revm/src/handler.rs | 52 +- crates/rpc/src/eth/transaction.rs | 83 +- 13 files changed, 1938 insertions(+), 188 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4937c224..f95ffb1f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5126,6 +5126,7 @@ dependencies = [ "reth-rpc-api", "serde_json", "thiserror 2.0.18", + "tokio", "tracing", ] @@ -5172,7 +5173,6 @@ dependencies = [ "alloy-signer", "alloy-signer-local", "clap", - "dashmap", "eyre", "futures", "jsonrpsee", @@ -5191,6 +5191,7 @@ dependencies = [ "parking_lot", "reth-chain-state", "reth-chainspec", + "reth-consensus", "reth-db", "reth-e2e-test-utils", "reth-engine-local", @@ -5239,6 +5240,7 @@ dependencies = [ "morph-evm", "morph-payload-types", "morph-primitives", + "morph-txpool", "reth-basic-payload-builder", "reth-chainspec", "reth-evm", @@ -5252,6 +5254,7 @@ dependencies = [ "reth-revm", "reth-storage-api", "reth-transaction-pool", + "reth-trie-common", "reth-trie-parallel", "revm", "thiserror 2.0.18", diff --git a/crates/engine-api/Cargo.toml b/crates/engine-api/Cargo.toml index e52b121d..a6630d7a 100644 --- a/crates/engine-api/Cargo.toml +++ b/crates/engine-api/Cargo.toml @@ -39,6 +39,7 @@ auto_impl.workspace = true jsonrpsee = { workspace = true, features = ["server", "macros"] } parking_lot.workspace = true thiserror.workspace = true +tokio = { workspace = true, features = ["sync"] } tracing.workspace = true [dev-dependencies] diff --git a/crates/engine-api/src/builder.rs b/crates/engine-api/src/builder.rs index 252a9b2c..979ddd09 100644 --- a/crates/engine-api/src/builder.rs +++ b/crates/engine-api/src/builder.rs @@ -50,6 +50,14 @@ pub struct RealMorphL2EngineApi { /// Tracks L1-derived finalized block tags for FCU updates. block_tag_tracker: Arc, + /// Serializes payload builds to prevent concurrent deterministic `PayloadId` + /// collisions in reth's `PayloadBuilderService`. + build_lock: tokio::sync::Mutex<()>, + + /// Serializes forkchoice and block-tag updates across `import_l2_block_via_engine` + /// and `set_block_tags` so tag updates cannot race concurrent reorgs. + fcu_lock: tokio::sync::Mutex<()>, + /// Prometheus metrics for custom Morph L2 Engine API endpoints and chain head health. metrics: MorphEngineApiMetrics, } @@ -138,13 +146,18 @@ fn payload_timestamp( } // Derivation rebuilds a block already committed to L1 and must reproduce it exactly. Some(timestamp) => timestamp, - None => std::cmp::max( - parent_timestamp + 1, - std::time::SystemTime::now() + None => { + let earliest = if emerald_active { + parent_timestamp + } else { + parent_timestamp + 1 + }; + let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() - .as_secs(), - ), + .as_secs(); + now.max(earliest) + } } } @@ -163,6 +176,8 @@ impl RealMorphL2EngineApi { chain_spec, engine_handle, block_tag_tracker, + build_lock: tokio::sync::Mutex::new(()), + fcu_lock: tokio::sync::Mutex::new(()), metrics: MorphEngineApiMetrics::default(), } } @@ -353,6 +368,23 @@ where } }; + // 2b. Validate `next_l1_message_index` before calling `new_payload`: the field is not + // covered by the block hash, so an `AlreadySeen` hit in the engine tree would + // otherwise return `Valid` without re-running `validate_payload`. + if let Err(err) = self.validate_next_l1_message_index(payload.block.as_ref()) { + tracing::warn!( + target: "morph::engine", + block_hash = %data.hash, + error = %err, + "invalid next_l1_message_index during validate_l2_block" + ); + self.metrics.validate_l2_block_failures_total.increment(1); + self.metrics + .validate_l2_block_duration_seconds + .record(validate_started.elapsed()); + return Ok(GenericResponse { success: false }); + } + let status = match self.engine_handle.new_payload(payload).await { Ok(status) => status, Err(err) => { @@ -624,42 +656,93 @@ where safe_block_hash: B256, finalized_block_hash: B256, ) -> EngineApiResult<()> { - // Match geth's SetBlockTags: look up the header by hash and call set_finalized / - // set_safe on the provider directly, skipping zero hashes. This avoids a full - // FCU round-trip through the async engine pipeline for what is purely a tag - // update, and correctly skips the update when the caller passes B256::ZERO. - // - // Order matters: set safe FIRST, then finalized. The Ethereum invariant - // `finalized.number <= safe.number` must hold at every observable point - // for an RPC reader. Updating finalized first and then safe leaves a - // window between the two writes where `eth_getBlockByNumber("finalized")` - // returns the new value but `eth_getBlockByNumber("safe")` returns the - // stale older value — a transient `finalized > safe` violation. Updating - // safe first keeps the invariant satisfied throughout (finalized stays - // at its older, smaller value while safe advances). + if safe_block_hash == B256::ZERO && finalized_block_hash == B256::ZERO { + return Ok(()); + } + + // Serialize tag updates against forkchoice imports so a concurrent reorg cannot + // invalidate a resolved hash or advance the canonical head mid-call. + let _fcu_guard = self.fcu_lock.lock().await; + let safe = if safe_block_hash != B256::ZERO { - Some(self.resolve_block_tag(safe_block_hash, "safe")?) + Some(self.resolve_canonical_block_tag(safe_block_hash, "safe")?) } else { None }; let finalized = if finalized_block_hash != B256::ZERO { - Some(self.resolve_block_tag(finalized_block_hash, "finalized")?) + Some(self.resolve_canonical_block_tag(finalized_block_hash, "finalized")?) } else { None }; - if safe.is_none() && finalized.is_none() { - return Ok(()); - } let canonical_head = self.current_head()?; + let existing_safe = self + .provider + .safe_block_number() + .map_err(|e| MorphEngineApiError::Database(e.to_string()))?; + let existing_finalized = self + .provider + .finalized_block_number() + .map_err(|e| MorphEngineApiError::Database(e.to_string()))?; + validate_resolved_block_tags( safe.as_ref().map(|header| header.number()), finalized.as_ref().map(|header| header.number()), + existing_safe, + existing_finalized, canonical_head.number, )?; - if let Some(sealed) = safe { - self.provider.set_safe(sealed); + // Route tag updates through reth's engine tree FCU without pre-mutating + // `CanonicalInMemoryState`. In reth's `update_finalized_block` / `update_safe_block`, + // `B256::ZERO` is a no-op (preserving the other tag), while a non-zero change schedules + // MDBX persistence (`save_safe_block_number` / `save_finalized_block_number`), updates + // `CanonicalInMemoryState`, and updates finalized/safe height metrics. + // + // When both tags are supplied, apply `safe` before `finalized` so concurrent RPC + // readers never observe a transient `finalized > safe` window. + if safe.is_some() && finalized.is_some() { + let safe_fcu = alloy_rpc_types_engine::ForkchoiceState { + head_block_hash: canonical_head.hash, + safe_block_hash, + finalized_block_hash: B256::ZERO, + }; + self.provider.on_forkchoice_update_received(&safe_fcu); + let safe_res = self + .engine_handle + .fork_choice_updated(safe_fcu, None) + .await + .map_err(|e| MorphEngineApiError::ExecutionFailed(e.to_string()))?; + ensure_payload_status_valid(&safe_res.payload_status, "forkchoiceUpdated")?; + + let finalized_fcu = alloy_rpc_types_engine::ForkchoiceState { + head_block_hash: canonical_head.hash, + safe_block_hash: B256::ZERO, + finalized_block_hash, + }; + self.provider.on_forkchoice_update_received(&finalized_fcu); + let finalized_res = self + .engine_handle + .fork_choice_updated(finalized_fcu, None) + .await + .map_err(|e| MorphEngineApiError::ExecutionFailed(e.to_string()))?; + ensure_payload_status_valid(&finalized_res.payload_status, "forkchoiceUpdated")?; + } else { + let forkchoice = alloy_rpc_types_engine::ForkchoiceState { + head_block_hash: canonical_head.hash, + safe_block_hash, + finalized_block_hash, + }; + self.provider.on_forkchoice_update_received(&forkchoice); + let fcu_res = self + .engine_handle + .fork_choice_updated(forkchoice, None) + .await + .map_err(|e| MorphEngineApiError::ExecutionFailed(e.to_string()))?; + ensure_payload_status_valid(&fcu_res.payload_status, "forkchoiceUpdated")?; + } + + if safe.is_some() { tracing::info!( target: "morph::engine", hash = %safe_block_hash, @@ -667,8 +750,11 @@ where ); } - if let Some(sealed) = finalized { - self.provider.set_finalized(sealed); + if finalized.is_some() { + // Cache the L1-derived finalized hash only after FCU succeeds; when + // `finalized_block_hash == B256::ZERO`, leave any previously cached hash intact. + self.block_tag_tracker + .record_finalized_hash(Some(finalized_block_hash)); tracing::info!( target: "morph::engine", hash = %finalized_block_hash, @@ -676,38 +762,41 @@ where ); } - // Cache the L1-derived finalized hash so subsequent FCU calls can forward it. - // Safe is not cached: FCU safe is supplied by each import caller, and the - // RPC-visible safe tag can also be advanced by set_block_tags. - self.block_tag_tracker - .record_finalized_hash(if finalized_block_hash != B256::ZERO { - Some(finalized_block_hash) - } else { - None - }); - Ok(()) } } impl RealMorphL2EngineApi { - /// Looks up a sealed header by hash. + /// Looks up a sealed header by hash and verifies that it belongs to the current + /// canonical chain. /// - /// Used by `set_block_tags` to validate both tag updates before mutating provider state. - fn resolve_block_tag( + /// Used by `set_block_tags` to validate both tag updates before mutating state. + fn resolve_canonical_block_tag( &self, hash: B256, tag_name: &str, ) -> EngineApiResult> where - Provider: HeaderProvider
, + Provider: HeaderProvider
+ BlockNumReader, { - self.provider + let header = self + .provider .sealed_header_by_hash(hash) .map_err(|e| MorphEngineApiError::Internal(e.to_string()))? .ok_or_else(|| { MorphEngineApiError::Internal(format!("{tag_name} block {hash} not found")) - }) + })?; + let canonical_hash = self + .provider + .block_hash(header.number()) + .map_err(|e| MorphEngineApiError::Database(e.to_string()))?; + if canonical_hash != Some(header.hash()) { + return Err(MorphEngineApiError::ValidationFailed(format!( + "{tag_name} block {hash} (number {}) is not canonical", + header.number() + ))); + } + Ok(header) } async fn build_l2_payload( @@ -727,6 +816,10 @@ impl RealMorphL2EngineApi { + Sync + 'static, { + // Serialize builds so overlapping requests with identical `(parent, timestamp, txs)` + // never collide on the deterministic `PayloadId` in reth's `PayloadBuilderService`. + let _build_guard = self.build_lock.lock().await; + tracing::debug!( target: "morph::engine", block_number = params.number, @@ -850,6 +943,75 @@ impl RealMorphL2EngineApi { }) } + /// Validates the unhashed `next_l1_message_index` header field against the parent header + /// and the block's leading L1 messages before calling `engine_handle.new_payload`. + /// + /// Because `next_l1_msg_index` is not part of the block hash, reth's `AlreadySeen` + /// short-circuit would otherwise return `Valid` for a tampered `next_l1_message_index` + /// whenever the block hash is already in `tree_state` (e.g., pre-inserted by + /// `assembleL2Block`) or in the DB. Checking it here rejects the tampered request + /// without invoking `new_payload` (so `invalid_headers` is never poisoned). + fn validate_next_l1_message_index(&self, block: &SealedBlock) -> EngineApiResult<()> + where + Provider: HeaderProvider
, + { + let Some(parent) = self + .provider + .sealed_header_by_hash(block.parent_hash()) + .map_err(|e| MorphEngineApiError::Database(e.to_string()))? + else { + return Ok(()); + }; + + let mut expected = parent.next_l1_msg_index; + let mut first_l1_msg = true; + for tx in block.body().transactions() { + if !tx.is_l1_msg() { + break; + } + let Some(queue_index) = tx.queue_index() else { + // Malformed L1 message is committed by the block hash; let the engine + // validator reject and cache it. + return Ok(()); + }; + if first_l1_msg { + first_l1_msg = false; + if queue_index < parent.next_l1_msg_index { + // Cross-block L1 replay is committed by the block hash; let the engine + // validator reject and cache it with `L1MessagesNotInOrder`. + return Ok(()); + } + } + expected = match queue_index.checked_add(1) { + Some(next) => next, + None => { + return Err(MorphEngineApiError::ValidationFailed(format!( + "invalid block.NextL1MsgIndex: expected {}, got {}", + u64::MAX, + block.header().next_l1_msg_index + ))); + } + }; + } + + let actual = block.header().next_l1_msg_index; + let is_jade = self + .chain_spec + .is_jade_active_at_timestamp(block.header().timestamp()); + let invalid = if is_jade { + actual != expected + } else { + actual < expected + }; + if invalid { + return Err(MorphEngineApiError::ValidationFailed(format!( + "invalid block.NextL1MsgIndex: expected {expected}, got {actual}" + ))); + } + + Ok(()) + } + async fn import_l2_block_via_engine( &self, data: ExecutableL2Data, @@ -861,6 +1023,7 @@ impl RealMorphL2EngineApi { + CanonChainTracker
, { let (payload, header) = self.execution_payload_from_executable_data(&data)?; + self.validate_next_l1_message_index(payload.block.as_ref())?; let payload_status = self .engine_handle @@ -869,6 +1032,10 @@ impl RealMorphL2EngineApi { .map_err(|e| MorphEngineApiError::ExecutionFailed(e.to_string()))?; ensure_payload_status_valid(&payload_status, "newPayload")?; + // Serialize FCU against `set_block_tags` so tag updates see a stable canonical head + // and this FCU observes any newly recorded L1 finalized hash. + let _fcu_guard = self.fcu_lock.lock().await; + // FCU safe/finalized must be canonical ancestors. Unsafe imports pass safe zero; // new_safe_l2_block passes the imported block itself, never a cached old safe. // Forward only the L1-derived finalized tag; zero is a no-op when it is absent, @@ -1036,6 +1203,8 @@ impl RealMorphL2EngineApi { fn validate_resolved_block_tags( safe_number: Option, finalized_number: Option, + existing_safe_number: Option, + existing_finalized_number: Option, canonical_head_number: u64, ) -> EngineApiResult<()> { if let Some(safe_number) = safe_number @@ -1054,7 +1223,10 @@ fn validate_resolved_block_tags( ))); } - if let (Some(safe_number), Some(finalized_number)) = (safe_number, finalized_number) + let effective_safe = safe_number.or(existing_safe_number); + let effective_finalized = finalized_number.or(existing_finalized_number); + + if let (Some(safe_number), Some(finalized_number)) = (effective_safe, effective_finalized) && finalized_number > safe_number { return Err(MorphEngineApiError::ValidationFailed(format!( @@ -1356,7 +1528,7 @@ mod tests { #[test] fn test_validate_resolved_block_tags_rejects_finalized_after_safe() { - let err = validate_resolved_block_tags(Some(10), Some(11), 11).unwrap_err(); + let err = validate_resolved_block_tags(Some(10), Some(11), None, None, 11).unwrap_err(); match err { MorphEngineApiError::ValidationFailed(msg) => { assert!(msg.contains("finalized block number 11 exceeds safe block number 10")); @@ -1367,7 +1539,7 @@ mod tests { #[test] fn test_validate_resolved_block_tags_rejects_safe_after_canonical_head() { - let err = validate_resolved_block_tags(Some(12), Some(11), 11).unwrap_err(); + let err = validate_resolved_block_tags(Some(12), Some(11), None, None, 11).unwrap_err(); match err { MorphEngineApiError::ValidationFailed(msg) => { assert!(msg.contains("safe block number 12 exceeds canonical head number 11")); @@ -1376,6 +1548,32 @@ mod tests { } } + #[test] + fn test_validate_resolved_block_tags_enforces_partial_update_ordering() { + // Updating finalized only past existing safe must fail. + let err = validate_resolved_block_tags(None, Some(11), Some(10), Some(8), 12).unwrap_err(); + match err { + MorphEngineApiError::ValidationFailed(msg) => { + assert!(msg.contains("finalized block number 11 exceeds safe block number 10")); + } + other => panic!("unexpected error: {other}"), + } + + // Updating safe only below existing finalized must fail. + let err = validate_resolved_block_tags(Some(7), None, Some(10), Some(8), 12).unwrap_err(); + match err { + MorphEngineApiError::ValidationFailed(msg) => { + assert!(msg.contains("finalized block number 8 exceeds safe block number 7")); + } + other => panic!("unexpected error: {other}"), + } + + // Partial updates preserving effective_finalized <= effective_safe <= head succeed. + assert!(validate_resolved_block_tags(None, Some(10), Some(10), Some(8), 12).is_ok()); + assert!(validate_resolved_block_tags(Some(12), None, Some(10), Some(8), 12).is_ok()); + assert!(validate_resolved_block_tags(None, Some(5), None, None, 12).is_ok()); + } + // ========================================================================= // apply_executable_data_overrides edge cases // ========================================================================= @@ -1486,8 +1684,14 @@ mod tests { fn test_payload_timestamp_defaults_after_parent() { // Ahead of the wall clock, so the parent decides the default. let parent_timestamp = 20_000_000_000; + // From Emerald on, default timestamp may share parent_timestamp. assert_eq!( payload_timestamp(None, parent_timestamp, true, TxPoolPolicy::Include), + parent_timestamp + ); + // Before Emerald, default timestamp must be strictly after parent_timestamp. + assert_eq!( + payload_timestamp(None, parent_timestamp, false, TxPoolPolicy::Include), parent_timestamp + 1 ); } diff --git a/crates/evm/src/lib.rs b/crates/evm/src/lib.rs index fc0d1f82..4e5de3a0 100644 --- a/crates/evm/src/lib.rs +++ b/crates/evm/src/lib.rs @@ -92,7 +92,7 @@ use crate::{block::MorphBlockExecutorFactory, evm::MorphEvm}; use morph_chainspec::MorphChainSpec; use morph_revm::evm::MorphContext; -pub use morph_revm::{MorphBlockEnv, MorphHaltReason}; +pub use morph_revm::{MorphBlockEnv, MorphHaltReason, MorphInvalidTransaction}; /// Morph EVM configuration and block executor factory. /// diff --git a/crates/node/Cargo.toml b/crates/node/Cargo.toml index ccdad592..27cd0c1c 100644 --- a/crates/node/Cargo.toml +++ b/crates/node/Cargo.toml @@ -28,6 +28,7 @@ reth-db.workspace = true reth-chain-state.workspace = true reth-node-core.workspace = true reth-chainspec.workspace = true +reth-consensus.workspace = true reth-engine-local.workspace = true reth-engine-tree.workspace = true reth-errors.workspace = true @@ -61,7 +62,6 @@ alloy-rpc-types-eth.workspace = true # Async eyre.workspace = true clap.workspace = true -dashmap.workspace = true futures.workspace = true parking_lot.workspace = true tokio = { workspace = true, features = ["sync", "rt"] } diff --git a/crates/node/src/validator.rs b/crates/node/src/validator.rs index 6e9b37e8..5a864cbd 100644 --- a/crates/node/src/validator.rs +++ b/crates/node/src/validator.rs @@ -3,7 +3,6 @@ use crate::MorphNode; use alloy_consensus::BlockHeader; use alloy_primitives::{B256, keccak256}; -use dashmap::DashMap; use morph_chainspec::{ L2_MESSAGE_QUEUE_ADDRESS, L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT, MorphChainSpec, MorphHardforks, @@ -14,6 +13,7 @@ use morph_primitives::{MorphHeader, MorphPrimitives, MorphTxEnvelope}; use parking_lot::Mutex; use reth_chain_state::ExecutedBlock; use reth_chainspec::EthChainSpec; +use reth_consensus::{Consensus, FullConsensus, HeaderValidator}; use reth_engine_tree::tree::payload_validator::TreeCtx; use reth_engine_tree::tree::{ BasicEngineValidator, CacheWaitDurations, EngineApiTreeState, EngineValidator, @@ -25,7 +25,7 @@ use reth_engine_tree::tree::{ StateRootJobOutcome, StateRootStrategy, }, }; -use reth_errors::{ConsensusError, ProviderResult}; +use reth_errors::{ConsensusError, ProviderError, ProviderResult}; use reth_evm::{ConfigureEvm, revm::context::Block as _}; use reth_node_api::{ AddOnsContext, FullNodeComponents, InvalidPayloadAttributesError, NewPayloadError, NodeTypes, @@ -47,7 +47,10 @@ use reth_tracing::tracing; use reth_transaction_pool::{ BestTransactions, BestTransactionsAttributes, PoolTransaction, TransactionPool, }; -use std::{collections::VecDeque, sync::Arc}; +use std::{ + collections::{HashMap, VecDeque}, + sync::Arc, +}; /// Builder for Morph engine validator (payload validation). /// @@ -126,6 +129,8 @@ where let post_execution_validator = validator.clone(); let provider = ctx.node.provider().clone(); + let consensus: Arc> = + Arc::new(ctx.node.consensus().clone()); let state_root_strategy: Arc< dyn StateRootStrategy, > = Arc::new(MorphStateRootStrategy::new(chain_spec.clone())); @@ -133,7 +138,7 @@ where let txpool_prewarming = tree_config.txpool_prewarming(); let mut validator = BasicEngineValidator::new( provider.clone(), - Arc::new(ctx.node.consensus().clone()), + consensus.clone(), ctx.node.evm_config().clone(), validator, tree_config, @@ -152,6 +157,7 @@ where validator, provider, chain_spec, + consensus, post_execution_validator, )) } @@ -235,6 +241,7 @@ where inner: BasicEngineValidator, provider: P, chain_spec: Arc, + consensus: Arc>, post_execution_validator: MorphEngineValidator, } @@ -246,12 +253,14 @@ where inner: BasicEngineValidator, provider: P, chain_spec: Arc, + consensus: Arc>, post_execution_validator: MorphEngineValidator, ) -> Self { Self { inner, provider, chain_spec, + consensus, post_execution_validator, } } @@ -262,30 +271,25 @@ where Evm: ConfigureEvm, P: BlockReader
, { - fn validate_next_l1_msg_index( + /// Enforces parent-aware L1 message queue invariants: + /// + /// 1. Across **all** hardforks (both pre-Jade and post-Jade), if the block contains + /// leading L1 messages, the first message's `queue_index` must be `>= parent.next_l1_msg_index`. + /// Violations are cross-block L1 message replays and return cacheable + /// [`MorphConsensusError::L1MessagesNotInOrder`] (since transactions are committed by the + /// block hash). Forward skips (`first_queue_index > parent.next_l1_msg_index`) remain + /// permitted. + /// 2. From Jade onward, `header.next_l1_msg_index` must match the exact derived index + /// (`parent.next_l1_msg_index` when no L1 messages are present, or `last_queue_index + 1` + /// otherwise). Mismatches return transient [`MorphConsensusError::InvalidNextL1MessageIndex`] + /// so an unhashed header field cannot poison `invalid_headers`. + fn validate_l1_msg_index_against_parent( &self, block: &SealedBlock, - ctx: &TreeCtx<'_, MorphPrimitives>, - ) -> Result<(), InsertBlockErrorKind> { - if !self - .chain_spec - .is_jade_active_at_timestamp(block.header().timestamp()) - { - return Ok(()); - } - - let parent_hash = block.parent_hash(); - let parent = match ctx.state().tree_state().sealed_header_by_hash(&parent_hash) { - Some(parent) => Some(parent), - None => self.provider.sealed_header_by_hash(parent_hash)?, - }; - let Some(parent) = parent else { - // The upstream validator reports the missing parent with the - // canonical provider error before executing the block. - return Ok(()); - }; - + parent: &MorphHeader, + ) -> Result<(), ConsensusError> { let mut expected = parent.next_l1_msg_index; + let mut first_l1_msg = true; for tx in block.body().transactions() { if !tx.is_l1_msg() { break; @@ -293,6 +297,17 @@ where let queue_index = tx.queue_index().ok_or_else(|| { ConsensusError::msg("L1 message transaction is missing queue index") })?; + if first_l1_msg { + first_l1_msg = false; + if queue_index < parent.next_l1_msg_index { + return Err(ConsensusError::other( + MorphConsensusError::L1MessagesNotInOrder { + expected: parent.next_l1_msg_index, + actual: queue_index, + }, + )); + } + } expected = queue_index.checked_add(1).ok_or_else(|| { ConsensusError::other(MorphConsensusError::InvalidNextL1MessageIndex { expected: u64::MAX, @@ -301,22 +316,45 @@ where })?; } + if !self + .chain_spec + .is_jade_active_at_timestamp(block.header().timestamp()) + { + return Ok(()); + } + // Typed so that `MorphConsensus::is_transient_error` keeps this rejection out of // reth's invalid-header cache: the field is not covered by the block hash, so // the cache entry would also match the honest block. let actual = block.header().next_l1_msg_index; if actual != expected { - return Err( - ConsensusError::other(MorphConsensusError::InvalidNextL1MessageIndex { - expected, - actual, - }) - .into(), - ); + return Err(ConsensusError::other( + MorphConsensusError::InvalidNextL1MessageIndex { expected, actual }, + )); } Ok(()) } + fn validate_next_l1_msg_index( + &self, + block: &SealedBlock, + ctx: &TreeCtx<'_, MorphPrimitives>, + ) -> Result<(), InsertBlockErrorKind> { + let parent_hash = block.parent_hash(); + let parent = match ctx.state().tree_state().sealed_header_by_hash(&parent_hash) { + Some(parent) => Some(parent), + None => self.provider.sealed_header_by_hash(parent_hash)?, + }; + let Some(parent) = parent else { + // The upstream validator reports the missing parent with the + // canonical provider error before executing the block. + return Ok(()); + }; + + self.validate_l1_msg_index_against_parent(block, parent.header()) + .map_err(Into::into) + } + fn validate_next_l1_msg_index_for_block( &self, block: &SealedBlock, @@ -327,6 +365,30 @@ where .map_err(|kind| InsertBlockError::new(block.clone(), kind).into()) } + /// Runs lightweight structural consensus validation before admitting a locally built + /// block via `InsertExecutedBlock`, ensuring pre-inserted blocks obey the same + /// header, parent, L1 queue, MorphTx, and DA payload rules as imported blocks. + fn validate_pre_inserted_block( + &self, + block: &RecoveredBlock, + ) -> ProviderResult<()> { + let sealed_header = block.sealed_header(); + self.consensus + .validate_header(sealed_header) + .map_err(ProviderError::other)?; + if let Some(parent) = self.provider.sealed_header_by_hash(block.parent_hash())? { + self.consensus + .validate_header_against_parent(sealed_header, &parent) + .map_err(ProviderError::other)?; + self.validate_l1_msg_index_against_parent(block.sealed_block(), parent.header()) + .map_err(ProviderError::other)?; + } + self.consensus + .validate_block_pre_execution(block.sealed_block()) + .map_err(ProviderError::other)?; + Ok(()) + } + fn validate_withdraw_trie_root( &self, output: reth_engine_tree::tree::ValidationOutput, @@ -347,6 +409,26 @@ where Ok(output) } + + fn validate_withdraw_trie_root_direct( + expected_withdraw_trie_root: Option, + output: reth_engine_tree::tree::ValidationOutput, + ) -> reth_engine_tree::tree::ValidationOutcome { + let expectation = MorphEngineValidator::expectation_from_root(expected_withdraw_trie_root); + if let Err(err) = + MorphEngineValidator::validate_withdraw_trie_root_expectation(expectation, || { + output.executed_block.hashed_state() + }) + { + return Err(InsertBlockError::consensus_error( + err, + output.executed_block.sealed_block().clone(), + ) + .into()); + } + + Ok(output) + } } impl EngineValidator @@ -368,29 +450,48 @@ where fn convert_payload_to_block( &self, - payload: MorphExecutionData, + mut payload: MorphExecutionData, ) -> Result, NewPayloadError> { + let block_hash = payload.block.hash(); + // Avoid leaking expectations into the cache when the block is already known + // or no non-zero cross-check root was supplied. + let is_zero_root = payload + .expected_withdraw_trie_root + .is_some_and(|root| root == B256::ZERO); + if is_zero_root { + self.post_execution_validator + .take_withdraw_trie_root_expectation(block_hash); + payload.expected_withdraw_trie_root = None; + } else if payload.expected_withdraw_trie_root.is_some() + && self + .provider + .sealed_header_by_hash(block_hash) + .ok() + .flatten() + .is_some() + { + payload.expected_withdraw_trie_root = None; + } self.inner.convert_payload_to_block(payload) } fn validate_payload( &mut self, - payload: MorphExecutionData, + mut payload: MorphExecutionData, ctx: TreeCtx<'_, MorphPrimitives>, ) -> reth_engine_tree::tree::ValidationOutcome { let block_hash = payload.block.hash(); - // `convert_payload_to_block` may already have registered a withdraw-root - // expectation for this hash. Clear it on every early reject path so a - // later re-import of the same hash does not observe a stale entry. - let l1_validation = self.validate_next_l1_msg_index_for_block(payload.block.as_ref(), &ctx); + // Extract the expectation directly onto the stack so the live `validate_payload` + // path never inserts into (or can leak from) `expected_withdraw_trie_roots`. + // Also clear any residual entry left by an earlier buffered conversion. + let expected_withdraw_trie_root = payload.expected_withdraw_trie_root.take(); self.post_execution_validator - .clear_withdraw_trie_root_expectation_on_error(block_hash, l1_validation)?; + .take_withdraw_trie_root_expectation(block_hash); - let validation = self.inner.validate_payload(payload, ctx); - let output = self - .post_execution_validator - .clear_withdraw_trie_root_expectation_on_error(block_hash, validation)?; - self.validate_withdraw_trie_root(output) + self.validate_next_l1_msg_index_for_block(payload.block.as_ref(), &ctx)?; + + let output = self.inner.validate_payload(payload, ctx)?; + Self::validate_withdraw_trie_root_direct(expected_withdraw_trie_root, output) } fn validate_block( @@ -414,6 +515,7 @@ where &self, block: BuiltPayloadExecutedBlock, ) -> ProviderResult> { + self.validate_pre_inserted_block(block.recovered_block.as_ref())?; self.inner.on_inserted_executed_block(block) } @@ -549,6 +651,12 @@ where } } +#[derive(Debug, Default)] +struct WithdrawTrieRootCache { + entries: HashMap, + order: VecDeque, +} + /// Morph engine validator for payload validation. /// /// This validator is used by the engine API to validate incoming payloads. @@ -556,8 +664,7 @@ where #[derive(Debug, Default, Clone)] #[non_exhaustive] pub struct MorphEngineValidator { - expected_withdraw_trie_roots: Arc>, - expected_withdraw_trie_root_order: Arc>>, + expected_withdraw_trie_roots: Arc>, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -574,25 +681,31 @@ impl MorphEngineValidator { Self::default() } + fn expectation_from_root(root: Option) -> WithdrawTrieRootExpectation { + match root { + Some(root) if !root.is_zero() => WithdrawTrieRootExpectation::Verify(root), + // Match morph-geth: zero means the caller did not provide this optional + // CL/EL cross-check value, not that the expected root is actually zero. + _ => WithdrawTrieRootExpectation::SkipValidation, + } + } + fn record_withdraw_trie_root_expectation( &self, block_hash: B256, expectation: WithdrawTrieRootExpectation, ) { - let is_new_entry = self - .expected_withdraw_trie_roots - .insert(block_hash, expectation) - .is_none(); + let mut cache = self.expected_withdraw_trie_roots.lock(); + let is_new_entry = cache.entries.insert(block_hash, expectation).is_none(); if is_new_entry { - let mut order = self.expected_withdraw_trie_root_order.lock(); - order.push_back(block_hash); + cache.order.push_back(block_hash); - while self.expected_withdraw_trie_roots.len() > Self::MAX_EXPECTED_WITHDRAW_TRIE_ROOTS { - let Some(evicted_hash) = order.pop_front() else { + while cache.entries.len() > Self::MAX_EXPECTED_WITHDRAW_TRIE_ROOTS { + let Some(evicted_hash) = cache.order.pop_front() else { break; }; - self.expected_withdraw_trie_roots.remove(&evicted_hash); + cache.entries.remove(&evicted_hash); } } } @@ -601,15 +714,11 @@ impl MorphEngineValidator { &self, block_hash: B256, ) -> Option { - let removed = self - .expected_withdraw_trie_roots - .remove(&block_hash) - .map(|(_, expected)| expected); + let mut cache = self.expected_withdraw_trie_roots.lock(); + let removed = cache.entries.remove(&block_hash); if removed.is_some() { - self.expected_withdraw_trie_root_order - .lock() - .retain(|hash| *hash != block_hash); + cache.order.retain(|hash| *hash != block_hash); } removed @@ -644,19 +753,10 @@ impl MorphEngineValidator { }) } - fn validate_withdraw_trie_root_update( - &self, - block_hash: B256, + fn validate_withdraw_trie_root_expectation( + expectation: WithdrawTrieRootExpectation, state_updates: impl FnOnce() -> Arc, ) -> Result<(), ConsensusError> { - let Some(expectation) = self.take_withdraw_trie_root_expectation(block_hash) else { - tracing::debug!( - target: "morph::engine_validator", - %block_hash, - "no withdraw trie root expectation registered; skipping CL cross-check" - ); - return Ok(()); - }; let WithdrawTrieRootExpectation::Verify(expected) = expectation else { return Ok(()); }; @@ -676,6 +776,22 @@ impl MorphEngineValidator { } Ok(()) } + + fn validate_withdraw_trie_root_update( + &self, + block_hash: B256, + state_updates: impl FnOnce() -> Arc, + ) -> Result<(), ConsensusError> { + let Some(expectation) = self.take_withdraw_trie_root_expectation(block_hash) else { + tracing::debug!( + target: "morph::engine_validator", + %block_hash, + "no withdraw trie root expectation registered; skipping CL cross-check" + ); + return Ok(()); + }; + Self::validate_withdraw_trie_root_expectation(expectation, state_updates) + } } impl PayloadValidator for MorphEngineValidator { @@ -688,13 +804,10 @@ impl PayloadValidator for MorphEngineValidator { let expected_withdraw_trie_root = payload.expected_withdraw_trie_root; let sealed_block = Arc::unwrap_or_clone(payload.block); - let expectation = match expected_withdraw_trie_root { - Some(root) if root != B256::ZERO => WithdrawTrieRootExpectation::Verify(root), - // Match morph-geth: zero means the caller did not provide this optional - // CL/EL cross-check value, not that the expected root is actually zero. - _ => WithdrawTrieRootExpectation::SkipValidation, - }; - self.record_withdraw_trie_root_expectation(sealed_block.hash(), expectation); + if expected_withdraw_trie_root.is_some() { + let expectation = Self::expectation_from_root(expected_withdraw_trie_root); + self.record_withdraw_trie_root_expectation(sealed_block.hash(), expectation); + } Ok(sealed_block) } @@ -770,10 +883,14 @@ mod tests { WithdrawTrieRootExpectation::Verify(B256::from([0xaa; 32])), ); } - assert_eq!( - validator.expected_withdraw_trie_roots.len(), - MorphEngineValidator::MAX_EXPECTED_WITHDRAW_TRIE_ROOTS - ); + { + let cache = validator.expected_withdraw_trie_roots.lock(); + assert_eq!( + cache.entries.len(), + MorphEngineValidator::MAX_EXPECTED_WITHDRAW_TRIE_ROOTS + ); + assert_eq!(cache.order.len(), cache.entries.len()); + } let oldest = key(0); let newest = key(MorphEngineValidator::MAX_EXPECTED_WITHDRAW_TRIE_ROOTS); @@ -782,23 +899,15 @@ mod tests { WithdrawTrieRootExpectation::Verify(B256::from([0xbb; 32])), ); + let cache = validator.expected_withdraw_trie_roots.lock(); assert_eq!( - validator.expected_withdraw_trie_roots.len(), + cache.entries.len(), MorphEngineValidator::MAX_EXPECTED_WITHDRAW_TRIE_ROOTS ); - assert!(!validator.expected_withdraw_trie_roots.is_empty()); - assert!( - validator - .expected_withdraw_trie_roots - .get(&newest) - .is_some() - ); - assert!( - validator - .expected_withdraw_trie_roots - .get(&oldest) - .is_none() - ); + assert_eq!(cache.order.len(), cache.entries.len()); + assert!(!cache.entries.is_empty()); + assert!(cache.entries.contains_key(&newest)); + assert!(!cache.entries.contains_key(&oldest)); } #[test] @@ -1058,6 +1167,26 @@ mod tests { ); } + #[test] + fn convert_payload_to_block_none_root_does_not_leak_cache_entry() { + let validator = MorphEngineValidator::new(); + let hash = B256::from([0x77; 32]); + let block = empty_recovered_block_with_hash(hash); + let payload = + morph_payload_types::MorphExecutionData::new(Arc::new(block.into_sealed_block())); + + validator + .convert_payload_to_block(payload) + .expect("payload conversion should succeed"); + + let cache = validator.expected_withdraw_trie_roots.lock(); + assert!( + cache.entries.is_empty(), + "None expected_withdraw_trie_root must not insert into cache" + ); + assert!(cache.order.is_empty()); + } + /// Verify expectation that mismatches an actually-updated slot must fail. #[test] fn validate_block_post_execution_rejects_mismatched_root() { diff --git a/crates/node/tests/it/consensus.rs b/crates/node/tests/it/consensus.rs index 21d6cc16..30ee6c25 100644 --- a/crates/node/tests/it/consensus.rs +++ b/crates/node/tests/it/consensus.rs @@ -441,6 +441,65 @@ async fn next_l1_msg_index_first_msg_skips_parent_allowed_pre_jade() -> eyre::Re Ok(()) } +/// Cross-block L1 message replay (`first_queue_index < parent.next_l1_msg_index`) must be +/// rejected post-Jade, even when in-block indices are contiguous and `header.next_l1_msg_index` +/// equals `last_queue_index + 1` and `>= parent.next_l1_msg_index`. +#[tokio::test(flavor = "multi_thread")] +async fn l1_message_cross_block_replay_rejected_post_jade() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + let (mut nodes, _wallet) = TestNodeBuilder::new() + .with_schedule(HardforkSchedule::AllActive) + .build() + .await?; + let mut node = nodes.pop().unwrap(); + + // Block 1 includes queue indices 0, 1 -> parent.next_l1_msg_index = 2. + advance_block_with_l1_messages(&mut node, L1MessageBuilder::build_sequential(0, 2)).await?; + + // Build a valid continuation block (queue 2, 3) then rewrite its L1 messages to replay + // index 1 (i.e. [1, 2], next_l1_msg_index = 3 >= parent's 2). + let base = build_block_no_submit(&mut node, L1MessageBuilder::build_sequential(2, 2)).await?; + let accepted = craft_and_try_import_block(&mut node, &base, |block| { + rewrite_l1_queue_indices_from(block, 1); + block.header.next_l1_msg_index = 3; + }) + .await?; + + assert!( + !accepted, + "post-Jade: cross-block L1 message replay ([1, 2] after parent next=2) must be rejected" + ); + Ok(()) +} + +/// Cross-block L1 message replay must also be rejected pre-Jade. +#[tokio::test(flavor = "multi_thread")] +async fn l1_message_cross_block_replay_rejected_pre_jade() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + let (mut nodes, _wallet) = TestNodeBuilder::new() + .with_schedule(HardforkSchedule::PreJade) + .build() + .await?; + let mut node = nodes.pop().unwrap(); + + // Block 1 includes queue indices 0, 1 -> parent.next_l1_msg_index = 2. + advance_block_with_l1_messages(&mut node, L1MessageBuilder::build_sequential(0, 2)).await?; + + // Rewrite block 2's L1 messages to replay [0, 1] with header.next_l1_msg_index = 2. + let base = build_block_no_submit(&mut node, L1MessageBuilder::build_sequential(2, 2)).await?; + let accepted = craft_and_try_import_block(&mut node, &base, |block| { + rewrite_l1_queue_indices_from(block, 0); + block.header.next_l1_msg_index = 2; + }) + .await?; + + assert!( + !accepted, + "pre-Jade: cross-block L1 message replay ([0, 1] after parent next=2) must be rejected" + ); + Ok(()) +} + /// Shift every leading L1 message's `queue_index` up by `delta`, re-sealing each tx. /// /// Used to craft a block whose L1 stream no longer continues the parent's queue index @@ -459,3 +518,19 @@ fn rewrite_l1_queue_indices(block: &mut morph_primitives::Block, delta: u64) { } } } + +/// Rewrite every leading L1 message's `queue_index` sequentially starting from `start`. +fn rewrite_l1_queue_indices_from(block: &mut morph_primitives::Block, start: u64) { + use alloy_consensus::Sealable; + use morph_primitives::MorphTxEnvelope; + + let mut next = start; + for tx in block.body.transactions.iter_mut() { + if let MorphTxEnvelope::L1Msg(sealed) = tx { + let mut inner = sealed.inner().clone(); + inner.queue_index = next; + next += 1; + *sealed = inner.seal_slow(); + } + } +} diff --git a/crates/node/tests/it/engine.rs b/crates/node/tests/it/engine.rs index 714ddc5e..981d32d4 100644 --- a/crates/node/tests/it/engine.rs +++ b/crates/node/tests/it/engine.rs @@ -22,7 +22,9 @@ use morph_primitives::MorphHeader; use reth_node_api::PayloadTypes; use reth_payload_builder::BuildNewPayload; use reth_payload_primitives::BuiltPayload; -use reth_provider::{BlockIdReader, BlockReaderIdExt}; +use reth_provider::{ + BlockIdReader, BlockReaderIdExt, ChainStateBlockReader, DatabaseProviderFactory, +}; use super::helpers::{ LOCAL_POLL_BUDGET, POLL_INTERVAL, assemble_l2_block, assemble_l2_block_v2, @@ -1253,3 +1255,259 @@ async fn empty_block_is_imported_without_execution_artifacts() -> eyre::Result<( Ok(()) } + +/// M-M10: `engine_setBlockTags` must: +/// 1. Reject non-canonical (orphaned) block hashes; +/// 2. Enforce `effective_finalized <= effective_safe <= canonical_head` across partial updates; +/// 3. Preserve the cached L1 finalized hash when `finalized_block_hash == B256::ZERO`; +/// 4. Persist updated `safe` and `finalized` tags to MDBX via the engine FCU pipeline. +#[tokio::test(flavor = "multi_thread")] +async fn set_block_tags_persists_to_mdbx_enforces_ordering_canonicality_and_preserves_zero_hash() +-> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let (mut nodes, _wallet) = TestNodeBuilder::new().build().await?; + let node = nodes.pop().unwrap(); + let client = node.auth_server_handle().http_client(); + + let base_ts = head_timestamp(&node)?; + + // Block 1 (canonical ancestor). + let b1 = assemble_l2_block( + &node, + AssembleL2BlockParams { + number: 1, + transactions: vec![], + timestamp: Some(base_ts + 1), + }, + ) + .await?; + import_l2_block(&node, b1.clone()).await?; + + // Import an orphaned sibling block at height 2, then reorg onto the canonical branch. + let orphan_2 = assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: b1.hash, + transactions: vec![], + timestamp: Some(base_ts + 2), + }, + ) + .await?; + import_l2_block(&node, orphan_2.clone()).await?; + + let canon_2 = assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: b1.hash, + transactions: vec![], + timestamp: Some(base_ts + 3), + }, + ) + .await?; + assert_ne!(canon_2.hash, orphan_2.hash); + import_l2_block(&node, canon_2.clone()).await?; + + let canon_3 = assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: canon_2.hash, + transactions: vec![], + timestamp: Some(base_ts + 4), + }, + ) + .await?; + import_l2_block(&node, canon_3.clone()).await?; + + let canon_4 = assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: canon_3.hash, + transactions: vec![], + timestamp: Some(base_ts + 5), + }, + ) + .await?; + import_l2_block(&node, canon_4.clone()).await?; + + // 1. Orphaned hash must be rejected as non-canonical (or not found). + let orphan_err = client + .request::<(), _>("engine_setBlockTags", (orphan_2.hash, B256::ZERO)) + .await + .expect_err("orphaned block hash must be rejected by engine_setBlockTags") + .to_string(); + assert!( + orphan_err.contains("not canonical") || orphan_err.contains("not found"), + "unexpected orphan rejection error: {orphan_err}" + ); + + // 2. Set safe = 2, finalized = 1. + client + .request::<(), _>("engine_setBlockTags", (canon_2.hash, b1.hash)) + .await?; + assert_eq!(node.inner.provider.safe_block_hash()?, Some(canon_2.hash)); + assert_eq!(node.inner.provider.finalized_block_hash()?, Some(b1.hash)); + + // Partial update: finalized = 3 > existing safe = 2 must fail. + let fin_gt_safe = client + .request::<(), _>("engine_setBlockTags", (B256::ZERO, canon_3.hash)) + .await + .expect_err("finalized > existing safe must fail") + .to_string(); + assert!( + fin_gt_safe.contains("finalized block number 3 exceeds safe block number 2"), + "unexpected partial finalized > safe error: {fin_gt_safe}" + ); + + // Advance safe = 3, finalized = 2. + client + .request::<(), _>("engine_setBlockTags", (canon_3.hash, canon_2.hash)) + .await?; + assert_eq!(node.inner.provider.safe_block_hash()?, Some(canon_3.hash)); + assert_eq!( + node.inner.provider.finalized_block_hash()?, + Some(canon_2.hash) + ); + + // Partial update: safe = 1 < existing finalized = 2 must fail. + let safe_lt_fin = client + .request::<(), _>("engine_setBlockTags", (b1.hash, B256::ZERO)) + .await + .expect_err("safe < existing finalized must fail") + .to_string(); + assert!( + safe_lt_fin.contains("finalized block number 2 exceeds safe block number 1"), + "unexpected partial safe < finalized error: {safe_lt_fin}" + ); + + // 3. Safe-only update (finalized == B256::ZERO) must advance safe to 4 while + // preserving finalized = 2 in both provider state and cached L1 finalized tracker. + client + .request::<(), _>("engine_setBlockTags", (canon_4.hash, B256::ZERO)) + .await?; + assert_eq!(node.inner.provider.safe_block_hash()?, Some(canon_4.hash)); + assert_eq!( + node.inner.provider.finalized_block_hash()?, + Some(canon_2.hash) + ); + + // 4. Advance additional blocks past reth's default persistence threshold (7) and + // memory buffer target (5) so block 4 is flushed to disk together with the queued + // safe=4 and finalized=2 MDBX checkpoints. + let mut parent_hash = canon_4.hash; + for offset in 6..=12u64 { + let next = assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash, + transactions: vec![], + timestamp: Some(base_ts + offset), + }, + ) + .await?; + parent_hash = next.hash; + import_l2_block(&node, next).await?; + } + + assert_eq!( + node.inner.provider.finalized_block_hash()?, + Some(canon_2.hash), + "cached L1 finalized hash must be preserved across subsequent imports" + ); + + let deadline = tokio::time::Instant::now() + LOCAL_POLL_BUDGET; + loop { + let db = node.inner.provider.database_provider_ro()?; + let db_finalized = db.last_finalized_block_number()?; + let db_safe = db.last_safe_block_number()?; + if db_finalized == Some(2) && db_safe == Some(4) { + break; + } + assert!( + tokio::time::Instant::now() < deadline, + "expected MDBX safe=Some(4) and finalized=Some(2), got safe={db_safe:?} finalized={db_finalized:?}" + ); + tokio::time::sleep(POLL_INTERVAL).await; + } + + Ok(()) +} + +/// M-M11: Concurrent `engine_assembleL2BlockV2` calls with identical inputs must serialize +/// cleanly instead of colliding on deterministic `PayloadId` in `PayloadBuilderService`. +#[tokio::test(flavor = "multi_thread")] +async fn concurrent_identical_assemble_l2_block_v2_calls_do_not_collide() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let (mut nodes, wallet) = TestNodeBuilder::new().build().await?; + let node = nodes.pop().unwrap(); + + let raw_tx = make_transfer_tx(wallet.chain_id, wallet.inner.clone(), wallet.inner_nonce).await; + let tx_hash = node.rpc.inject_tx(raw_tx).await?; + wait_until_pooled(&node, tx_hash).await?; + + let head = canonical_snapshot(&node)?; + let ts = head_timestamp(&node)? + 1; + + let calls = (0..8).map(|_| { + assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: head.hash, + transactions: vec![], + timestamp: Some(ts), + }, + ) + }); + + let results = futures::future::try_join_all(calls).await?; + assert_eq!(results.len(), 8); + for block in results { + assert_eq!(block.parent_hash, head.hash); + assert_eq!(block.number, head.number + 1); + assert_eq!(block.transactions.len(), 1); + } + + Ok(()) +} + +/// M-H10: `engine_newSafeL2Block` must reject a supplied MorphTx V2 before Celadon +/// activates, even when Prague is active (Jade) and the authorization list is empty. +#[tokio::test(flavor = "multi_thread")] +async fn new_safe_l2_block_rejects_v2_morph_tx_before_celadon() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let (mut nodes, wallet) = TestNodeBuilder::new() + .with_schedule(HardforkSchedule::PreCeladon) + .build() + .await?; + let node = nodes.pop().unwrap(); + + let v2_tx = MorphTxBuilder::new(wallet.chain_id, wallet.inner.clone(), wallet.inner_nonce) + .with_v2_eth_fee() + .build_signed()?; + + let head = canonical_snapshot(&node)?; + let safe_data = SafeL2Data { + number: 1, + gas_limit: 30_000_000, + base_fee_per_gas: Some(1_000_000), + timestamp: head_timestamp(&node)? + 1, + transactions: vec![v2_tx], + parent_hash: Some(head.hash), + }; + + let client = node.auth_server_handle().http_client(); + let err = client + .request::("engine_newSafeL2Block", (safe_data,)) + .await + .expect_err("pre-Celadon newSafeL2Block must reject supplied MorphTx V2") + .to_string(); + assert!( + err.contains("celadon") || err.contains("failed to get built payload"), + "unexpected pre-Celadon MorphTx V2 error: {err}" + ); + assert_eq!(canonical_snapshot(&node)?, head); + + Ok(()) +} diff --git a/crates/node/tests/it/invalid_payload_recovery.rs b/crates/node/tests/it/invalid_payload_recovery.rs index d67d5590..a9082125 100644 --- a/crates/node/tests/it/invalid_payload_recovery.rs +++ b/crates/node/tests/it/invalid_payload_recovery.rs @@ -4,13 +4,14 @@ use alloy_consensus::{BlockHeader, Sealable, transaction::TxHashRef}; use alloy_primitives::B256; use jsonrpsee::core::client::ClientT; use morph_node::test_utils::{TestNodeBuilder, make_transfer_tx}; -use morph_payload_types::{AssembleL2BlockParams, GenericResponse}; +use morph_payload_types::{AssembleL2BlockParams, AssembleL2BlockV2Params, GenericResponse}; use morph_primitives::MorphHeader; use reth_payload_primitives::BuiltPayload; -use reth_provider::{AccountReader, StateProviderFactory}; +use reth_provider::{AccountReader, BlockIdReader, StateProviderFactory}; use super::helpers::{ - assemble_l2_block, build_block_no_submit, canonical_snapshot, head_timestamp, import_l2_block, + LOCAL_POLL_BUDGET, POLL_INTERVAL, assemble_l2_block, assemble_l2_block_v2, + build_block_no_submit, canonical_snapshot, head_timestamp, import_l2_block, payload_with_receipts_root, wait_until_evicted, wait_until_pooled, }; @@ -181,3 +182,160 @@ async fn corrupted_next_l1_msg_index_does_not_poison_the_honest_block() -> eyre: Ok(()) } + +/// M-H07: Even when a non-empty block hash is already in `tree_state` (pre-inserted by +/// `assembleL2BlockV2`, so reth's `on_new_payload` would short-circuit on `AlreadySeen`), +/// tampering with the unhashed `next_l1_message_index` must be rejected by +/// `engine_validateL2Block`, `engine_newL2Block`, and `engine_newL2BlockV2` without +/// poisoning `invalid_headers` for the honest block. +#[tokio::test(flavor = "multi_thread")] +async fn tampered_next_l1_msg_index_rejected_when_block_already_seen() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let (mut nodes, wallet) = TestNodeBuilder::new().build().await?; + let node = nodes.pop().expect("one node requested"); + + let raw_tx = make_transfer_tx(wallet.chain_id, wallet.inner.clone(), wallet.inner_nonce).await; + let tx_hash = node.rpc.inject_tx(raw_tx).await?; + wait_until_pooled(&node, tx_hash).await?; + + let before = canonical_snapshot(&node)?; + let honest = assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: before.hash, + transactions: vec![], + timestamp: Some(head_timestamp(&node)? + 1), + }, + ) + .await?; + assert_eq!(honest.transactions.len(), 1); + + // Wait until the engine tree has pre-inserted the non-empty block so `AlreadySeen` + // is guaranteed to be armed in `tree_state`. + let deadline = tokio::time::Instant::now() + LOCAL_POLL_BUDGET; + loop { + if node + .inner + .provider + .pending_block_num_hash()? + .map(|p| p.hash) + == Some(honest.hash) + { + break; + } + assert!( + tokio::time::Instant::now() < deadline, + "precondition: non-empty candidate was not pre-inserted into tree_state" + ); + tokio::time::sleep(POLL_INTERVAL).await; + } + + let mut tampered = honest.clone(); + tampered.next_l1_message_index += 1; + + let client = node.auth_server_handle().http_client(); + + let validation: GenericResponse = client + .request("engine_validateL2Block", (tampered.clone(),)) + .await?; + assert!( + !validation.success, + "engine_validateL2Block must reject tampered next_l1_message_index on AlreadySeen block" + ); + + let err_v1 = client + .request::<(), _>("engine_newL2Block", (tampered.clone(),)) + .await + .expect_err("engine_newL2Block must reject tampered next_l1_message_index") + .to_string(); + assert!( + err_v1.contains("invalid block.NextL1MsgIndex"), + "unexpected engine_newL2Block error: {err_v1}" + ); + + let err_v2 = import_l2_block(&node, tampered) + .await + .expect_err("engine_newL2BlockV2 must reject tampered next_l1_message_index") + .to_string(); + assert!( + err_v2.contains("invalid block.NextL1MsgIndex"), + "unexpected engine_newL2BlockV2 error: {err_v2}" + ); + + assert_eq!( + canonical_snapshot(&node)?, + before, + "rejected tampered requests must leave canonical chain unchanged" + ); + + // The honest copy sharing the same block hash must still import cleanly. + let imported = import_l2_block(&node, honest.clone()).await?; + assert_eq!(imported.hash_slow(), honest.hash); + assert_eq!(canonical_snapshot(&node)?.hash, honest.hash); + + Ok(()) +} + +/// M-H07: A locally built non-empty block that violates consensus (e.g., future timestamp) +/// must be rejected by `on_inserted_executed_block` so it is NOT pre-inserted into +/// `tree_state` and cannot subsequently bypass validation via `AlreadySeen`. +#[tokio::test(flavor = "multi_thread")] +async fn pre_inserted_consensus_invalid_block_is_rejected_and_not_cached() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let (mut nodes, wallet) = TestNodeBuilder::new().build().await?; + let node = nodes.pop().expect("one node requested"); + + let raw_tx = make_transfer_tx(wallet.chain_id, wallet.inner.clone(), wallet.inner_nonce).await; + let tx_hash = node.rpc.inject_tx(raw_tx).await?; + wait_until_pooled(&node, tx_hash).await?; + + let before = canonical_snapshot(&node)?; + let future_timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs() + + 3600; + + let future_block = assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: before.hash, + transactions: vec![], + timestamp: Some(future_timestamp), + }, + ) + .await?; + assert_eq!( + future_block.transactions.len(), + 1, + "precondition: block must be non-empty so InsertExecutedBlock is emitted" + ); + + // Give the async engine tree task ample time to process InsertExecutedBlock; + // `on_inserted_executed_block` must reject the future-timestamp header. + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + assert_eq!( + node.inner.provider.pending_block_num_hash()?, + None, + "consensus-invalid future block must not be pre-inserted into tree_state" + ); + + // Importing it must fail consensus validation rather than hitting AlreadySeen. + let err = import_l2_block(&node, future_block) + .await + .expect_err("future-timestamp block must be rejected on import") + .to_string(); + assert!( + err.to_lowercase().contains("future"), + "expected future-timestamp consensus rejection, got: {err}" + ); + assert_eq!( + canonical_snapshot(&node)?, + before, + "canonical state must remain unchanged after rejecting future block" + ); + + Ok(()) +} diff --git a/crates/payload/builder/Cargo.toml b/crates/payload/builder/Cargo.toml index 9b614d4a..be804689 100644 --- a/crates/payload/builder/Cargo.toml +++ b/crates/payload/builder/Cargo.toml @@ -51,6 +51,8 @@ tracing.workspace = true thiserror.workspace = true [dev-dependencies] +morph-txpool.workspace = true +reth-trie-common.workspace = true [features] default = [] diff --git a/crates/payload/builder/src/builder.rs b/crates/payload/builder/src/builder.rs index fea02de9..d90b6a5f 100644 --- a/crates/payload/builder/src/builder.rs +++ b/crates/payload/builder/src/builder.rs @@ -2,23 +2,28 @@ use crate::metrics::MorphPayloadBuilderMetrics; use crate::{MorphBuilderConfig, MorphPayloadBuilderError, config::PayloadBuildingBreaker}; -use alloy_consensus::{BlockHeader, Transaction, Typed2718}; +use alloy_consensus::{BlockHeader, Transaction, Typed2718, transaction::TxHashRef}; use alloy_eips::eip2718::Encodable2718; -use alloy_primitives::{B256, Bytes, U256}; -use morph_chainspec::MorphChainSpec; -use morph_chainspec::{L2_MESSAGE_QUEUE_ADDRESS, L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT}; -use morph_evm::{MorphEvmConfig, MorphNextBlockEnvAttributes}; +use alloy_primitives::{Address, B256, Bytes, U256}; +use morph_chainspec::{ + L2_MESSAGE_QUEUE_ADDRESS, L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT, MorphChainSpec, + MorphHardforks, +}; +use morph_evm::{MorphEvmConfig, MorphInvalidTransaction, MorphNextBlockEnvAttributes}; use morph_payload_types::{ ExecutableL2Data, MorphBuiltPayload, MorphPayloadAttributes, MorphPayloadBuilderAttributes, }; -use morph_primitives::{MorphHeader, MorphTxEnvelope}; +use morph_primitives::{ + MorphHeader, MorphTxEnvelope, + transaction::morph_transaction::{MORPH_TX_VERSION_1, MORPH_TX_VERSION_2}, +}; use reth_basic_payload_builder::{ BuildArguments, BuildOutcome, BuildOutcomeKind, MissingPayloadBehaviour, PayloadBuilder, PayloadConfig, is_better_payload, }; use reth_chainspec::ChainSpecProvider; use reth_evm::{ - ConfigureEvm, Database, Evm, NextBlockEnvAttributes, + ConfigureEvm, Database, Evm, InvalidTxError, NextBlockEnvAttributes, block::{BlockExecutionError, BlockValidationError}, execute::{BlockBuilder, BlockBuilderOutcome}, }; @@ -32,8 +37,59 @@ use reth_revm::{database::StateProviderDatabase, db::State}; use reth_storage_api::{StateProvider, StateProviderFactory}; use reth_transaction_pool::{BestTransactionsAttributes, PoolTransaction, TransactionPool}; use revm::context_interface::Block as RevmBlock; +use std::collections::HashSet; use std::sync::Arc; +/// Returns true when `error` wraps a deterministic Morph token-fee error that cannot +/// succeed without an on-chain configuration or token-contract state change, so a failing +/// pool transaction should be evicted rather than left in `Pending` to burn up to 200k gas +/// on every subsequent block-building tick. +/// +/// Explicitly excludes [`MorphInvalidTransaction::InsufficientTokenBalance`], which is a +/// normal balance shortfall (and may be caused by an earlier transaction in the same block). +fn is_evictable_token_fee_error(error: &dyn InvalidTxError) -> bool { + let Some(morph_err) = (error as &dyn std::any::Any).downcast_ref::() + else { + return false; + }; + matches!( + morph_err, + MorphInvalidTransaction::TokenTransferFailed { .. } + | MorphInvalidTransaction::TokenBalanceQueryFailed + | MorphInvalidTransaction::TokenNotRegistered(_) + | MorphInvalidTransaction::TokenNotActive(_) + | MorphInvalidTransaction::InvalidTokenConfig(_) + ) +} + +/// Validates MorphTx (0x7F) hardfork activation gates and structural field rules against +/// the target block timestamp, matching `MorphConsensus::validate_block_pre_execution`. +fn validate_morph_tx_for_block( + tx: &MorphTxEnvelope, + chain_spec: &MorphChainSpec, + block_timestamp: u64, +) -> Result<(), String> { + let MorphTxEnvelope::Morph(signed) = tx else { + return Ok(()); + }; + let morph_tx = signed.tx(); + + if !chain_spec.is_emerald_active_at_timestamp(block_timestamp) { + return Err("MorphTx type is not yet active (emerald fork not reached)".into()); + } + if !chain_spec.is_jade_active_at_timestamp(block_timestamp) + && morph_tx.version == MORPH_TX_VERSION_1 + { + return Err("MorphTx version 1 is not yet active (jade fork not reached)".into()); + } + if !chain_spec.is_celadon_active_at_timestamp(block_timestamp) + && morph_tx.version == MORPH_TX_VERSION_2 + { + return Err("MorphTx version 2 is not yet active (celadon fork not reached)".into()); + } + morph_tx.validate().map_err(str::to_string) +} + /// Reads the withdraw trie root from the L2MessageQueue contract storage. fn read_withdraw_trie_root(db: &mut DB) -> Result { let value = db.storage( @@ -229,6 +285,7 @@ where build_payload_inner( cached_reads.as_db_mut(state), state_provider.as_ref(), + &self.pool, ctx, best, state_root_handle, @@ -369,21 +426,55 @@ impl MorphPayloadBuilderCtx { )); } - // L1 messages must precede every L2 transaction. Consensus rejects a violation - // post-execution (`validate_l1_messages_in_block`), but under a deterministic - // build the supplied list may legitimately contain L2 transactions, so catching - // the bad ordering here fails fast and names the actual problem — the caller's - // transaction list — instead of surfacing it as a block validation error after - // the whole block has been executed. - if recovered_tx.is_l1_msg() { + // L1 messages must precede every L2 transaction and carry strictly sequential + // queue indices. Validate ordering, queue index, overflow, and MorphTx hardfork / + // structural gates *before* EVM execution so invalid supplied transactions are + // rejected cleanly without mutating block state. + let is_l1_msg = recovered_tx.is_l1_msg(); + let next_l1_message_index = if is_l1_msg { if saw_l2_transaction { return Err(PayloadBuilderError::other( MorphPayloadBuilderError::L1MessageAfterRegularTx, )); } + let queue_index = recovered_tx.queue_index().ok_or_else(|| { + PayloadBuilderError::other( + MorphPayloadBuilderError::InvalidSuppliedTransaction { + error: "L1 message transaction is missing queue index".to_string(), + }, + ) + })?; + if queue_index != info.next_l1_message_index { + return Err(PayloadBuilderError::other( + MorphPayloadBuilderError::InvalidSuppliedTransaction { + error: format!( + "invalid L1 message queue index: expected {}, got {}", + info.next_l1_message_index, queue_index + ), + }, + )); + } + let next_index = queue_index.checked_add(1).ok_or_else(|| { + PayloadBuilderError::other( + MorphPayloadBuilderError::InvalidSuppliedTransaction { + error: format!("L1 message queue index overflow: {queue_index}"), + }, + ) + })?; + Some(next_index) } else { saw_l2_transaction = true; - } + if let Err(reason) = validate_morph_tx_for_block( + recovered_tx.inner(), + self.evm_config.chain_spec(), + self.attributes().timestamp, + ) { + return Err(PayloadBuilderError::other( + MorphPayloadBuilderError::InvalidSuppliedTransaction { error: reason }, + )); + } + None + }; let tx_gas = recovered_tx.gas_limit(); @@ -483,24 +574,10 @@ impl MorphPayloadBuilderCtx { .commit_tx_apply_duration_seconds .record(apply_started.elapsed()); - // For L1 messages, track the next L1 message index. + // For L1 messages, advance the next L1 message index. // L1 gas is prepaid on L1, so no fees are collected here. - let is_l1_msg = recovered_tx.is_l1_msg(); - if is_l1_msg { - // Ensure the queue index is strictly sequential - if let Some(queue_index) = recovered_tx.queue_index() { - if queue_index != info.next_l1_message_index { - return Err(PayloadBuilderError::other( - MorphPayloadBuilderError::InvalidSuppliedTransaction { - error: format!( - "invalid L1 message queue index: expected {}, got {}", - info.next_l1_message_index, queue_index - ), - }, - )); - } - info.next_l1_message_index = queue_index + 1; - } + if let Some(next_index) = next_l1_message_index { + info.next_l1_message_index = next_index; } else { // Calculate fees for L2 transactions: effective_tip * gas_used let effective_tip = recovered_tx @@ -528,19 +605,46 @@ impl MorphPayloadBuilderCtx { /// /// Returns `Ok(Some(()))` if the job was cancelled or breaker triggered, `Ok(None)` otherwise. /// Executed transaction bytes are appended to the provided vector. - fn execute_pool_transactions( + fn execute_pool_transactions( + &self, + builder: &mut impl BlockBuilder, + info: &mut ExecutionInfo, + executed_txs: &mut Vec, + best_txs: BestTxs, + pool: &Pool, + breaker: &PayloadBuildingBreaker, + ) -> Result, PayloadBuilderError> + where + BestTxs: PayloadTransactions>, + Pool: TransactionPool>, + { + self.execute_pool_transactions_with_evictor( + builder, + info, + executed_txs, + best_txs, + breaker, + |tx_hash| { + pool.remove_transactions(vec![tx_hash]); + }, + ) + } + + fn execute_pool_transactions_with_evictor( &self, builder: &mut impl BlockBuilder, info: &mut ExecutionInfo, executed_txs: &mut Vec, mut best_txs: BestTxs, breaker: &PayloadBuildingBreaker, + mut evict_from_pool: impl FnMut(B256), ) -> Result, PayloadBuilderError> where BestTxs: PayloadTransactions>, { let block_gas_limit = builder.evm().block().gas_limit(); let base_fee = builder.evm().block().basefee(); + let mut executed_senders: HashSet
= HashSet::new(); while let Some(tx) = best_txs.next(()) { // Check if the job was cancelled @@ -582,6 +686,26 @@ impl MorphPayloadBuilderCtx { continue; } + // Enforce MorphTx hardfork gates and structural validation against the target + // block's timestamp (a reorg build via assembleL2BlockV2 may target an older + // fork than the canonical head at which the pool admitted the tx). + if let Err(reason) = validate_morph_tx_for_block( + tx.inner(), + self.evm_config.chain_spec(), + self.attributes().timestamp, + ) { + tracing::debug!( + target: "payload_builder", + signer = %tx.signer(), + nonce = tx.nonce(), + block_timestamp = self.attributes().timestamp, + %reason, + "skipping pool MorphTx invalid for target block timestamp" + ); + best_txs.mark_invalid(tx.signer(), tx.nonce()); + continue; + } + // Skip transactions that cannot fit in remaining block gas or DA size. let tx_size = tx.encode_2718_len() as u64; if info.is_tx_over_limits(tx.gas_limit(), tx_size, block_gas_limit) { @@ -630,6 +754,19 @@ impl MorphPayloadBuilderCtx { "skipping invalid transaction and its descendants" ); best_txs.mark_invalid(tx.signer(), tx.nonce()); + if is_evictable_token_fee_error(error.as_ref()) + && !executed_senders.contains(&tx.signer()) + { + tracing::debug!( + target: "payload_builder", + tx_hash = %tx.tx_hash(), + signer = %tx.signer(), + nonce = tx.nonce(), + %error, + "evicting pool transaction after deterministic token-fee failure" + ); + evict_from_pool(*tx.tx_hash()); + } } continue; } @@ -659,6 +796,7 @@ impl MorphPayloadBuilderCtx { self.metrics .commit_tx_apply_duration_seconds .record(apply_started.elapsed()); + executed_senders.insert(tx.signer()); // Update execution info info.cumulative_gas_used += gas_used; @@ -742,9 +880,10 @@ impl ExecutionInfo { } /// Builds the payload on top of the state. -fn build_payload_inner<'a, DB, BestTxs>( +fn build_payload_inner<'a, DB, BestTxs, Pool>( db: DB, state_provider: &(impl StateProvider + ?Sized), + pool: &Pool, ctx: MorphPayloadBuilderCtx, best: impl FnOnce(BestTransactionsAttributes) -> BestTxs + Send + Sync + 'a, mut state_root_handle: Option, @@ -752,6 +891,7 @@ fn build_payload_inner<'a, DB, BestTxs>( where DB: Database, BestTxs: PayloadTransactions> + 'a, + Pool: TransactionPool>, { let build_started = Instant::now(); let attributes = ctx.attributes(); @@ -838,6 +978,7 @@ where &mut info, &mut executed_txs, best_txs, + pool, &breaker, )? .is_some() @@ -1299,4 +1440,654 @@ mod tests { let root = read_withdraw_trie_root(&mut db).unwrap(); assert_eq!(root, B256::from(U256::MAX)); } + + // ========================================================================= + // Shared scripted test helpers for M-H09, M-H10, and M-M12 + // ========================================================================= + + struct ScriptedBlockBuilder { + evm: ::Evm< + revm::database::CacheDB, + revm::inspector::NoOpInspector, + >, + outcomes: std::collections::HashMap>, + executed_count: usize, + } + + impl ScriptedBlockBuilder { + fn new( + outcomes: std::collections::HashMap>, + ) -> Self { + use reth_evm::{EvmEnv, EvmFactory as _}; + let mut evm_env = EvmEnv::new( + revm::context::CfgEnv::new_with_spec(morph_chainspec::MorphHardfork::Celadon), + morph_evm::MorphBlockEnv { + inner: revm::context::BlockEnv { + gas_limit: 30_000_000, + basefee: 1, + ..Default::default() + }, + }, + ); + evm_env.cfg_env.chain_id = 2818; + let evm = morph_evm::MorphEvmFactory::default().create_evm( + revm::database::CacheDB::new(revm::database::EmptyDB::default()), + evm_env, + ); + Self { + evm, + outcomes, + executed_count: 0, + } + } + } + + struct DummyExecutor; + impl reth_evm::block::BlockExecutor for DummyExecutor { + type Transaction = MorphTxEnvelope; + type Receipt = morph_primitives::MorphReceipt; + type Evm = ::Evm< + revm::database::CacheDB, + revm::inspector::NoOpInspector, + >; + type Result = morph_evm::MorphTxResult; + + fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> { + Ok(()) + } + fn execute_transaction_without_commit( + &mut self, + _tx: impl reth_evm::block::ExecutableTx, + ) -> Result { + unreachable!() + } + fn commit_transaction(&mut self, _output: Self::Result) -> reth_evm::execute::GasOutput { + unreachable!() + } + fn finish( + self, + ) -> Result< + ( + Self::Evm, + reth_evm::block::BlockExecutionResult, + ), + BlockExecutionError, + > { + unreachable!() + } + fn receipts(&self) -> &[Self::Receipt] { + &[] + } + fn evm_mut(&mut self) -> &mut Self::Evm { + unreachable!() + } + fn evm(&self) -> &Self::Evm { + unreachable!() + } + } + + impl BlockBuilder for ScriptedBlockBuilder { + type Primitives = morph_primitives::MorphPrimitives; + type Executor = DummyExecutor; + + fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> { + Ok(()) + } + + fn execute_transaction_with_commit_condition( + &mut self, + tx: impl reth_evm::execute::ExecutorTx, + _f: impl FnOnce( + &::Result, + ) -> reth_evm::block::CommitChanges, + ) -> Result, BlockExecutionError> { + self.executed_count += 1; + let (_tx_env, recovered) = tx.into_parts(); + let hash = *recovered.tx_hash(); + match self.outcomes.remove(&hash).expect("scripted outcome") { + Ok(gas_used) => Ok(Some(reth_evm::execute::GasOutput::new(gas_used))), + Err(err) => Err(BlockExecutionError::Validation( + BlockValidationError::InvalidTx { + hash, + error: Box::new(err), + }, + )), + } + } + + fn finish( + self, + _state_provider: impl StateProvider, + _state_root_precomputed: Option<(B256, reth_trie_common::updates::TrieUpdates)>, + ) -> Result, BlockExecutionError> { + unreachable!() + } + + fn executor_mut(&mut self) -> &mut Self::Executor { + unreachable!() + } + + fn executor(&self) -> &Self::Executor { + unreachable!() + } + + fn evm_mut(&mut self) -> &mut ::Evm { + &mut self.evm + } + + fn evm(&self) -> &::Evm { + &self.evm + } + + fn into_executor(self) -> Self::Executor { + unreachable!() + } + } + + struct ScriptedPoolTxs { + txs: std::collections::VecDeque, + marked_invalid: Vec<(Address, u64)>, + } + + impl PayloadTransactions for ScriptedPoolTxs { + type Transaction = morph_txpool::MorphPooledTransaction; + + fn next(&mut self, _ctx: ()) -> Option { + self.txs.pop_front() + } + + fn mark_invalid(&mut self, sender: Address, nonce: u64) { + self.marked_invalid.push((sender, nonce)); + } + } + + fn test_ctx_with_timestamp_and_txs( + timestamp: u64, + transactions: Vec, + ) -> MorphPayloadBuilderCtx { + let mut rpc_attrs = morph_payload_types::MorphPayloadAttributes::default(); + rpc_attrs.inner.timestamp = timestamp; + rpc_attrs.transactions = Some(transactions); + let attrs = MorphPayloadBuilderAttributes::try_new( + B256::ZERO, + rpc_attrs, + morph_payload_types::MORPH_PAYLOAD_BUILDER_VERSION, + ) + .unwrap(); + let payload_id = attrs.payload_id(); + MorphPayloadBuilderCtx { + evm_config: test_evm_config(), + config: PayloadConfig::new( + Arc::new(SealedHeader::seal_slow(MorphHeader::default())), + attrs, + payload_id, + ), + cancel: Default::default(), + best_payload: None, + builder_config: MorphBuilderConfig::default(), + metrics: MorphPayloadBuilderMetrics::default(), + } + } + + // ========================================================================= + // M-H09: Pre-execution queue_index validation & overflow protection tests + // ========================================================================= + + #[test] + fn test_execute_supplied_transactions_rejects_bad_queue_index_before_execution() { + use alloy_consensus::Sealable; + use morph_primitives::TxL1Msg; + + let l1_msg = TxL1Msg { + queue_index: 5, + gas_limit: 50_000, + to: Address::repeat_byte(0xaa), + value: U256::ZERO, + sender: Address::repeat_byte(0xbb), + input: Bytes::new(), + }; + let encoded = Bytes::from(MorphTxEnvelope::L1Msg(l1_msg.seal_slow()).encoded_2718()); + let ctx = test_ctx_with_timestamp_and_txs(1_800_000_000, vec![encoded]); + let mut builder = ScriptedBlockBuilder::new(std::collections::HashMap::new()); + let mut info = ExecutionInfo::new(0, None); + + let err = ctx + .execute_supplied_transactions(&mut builder, &mut info) + .expect_err("non-sequential queue_index must be rejected"); + assert!( + err.to_string() + .contains("invalid L1 message queue index: expected 0, got 5"), + "unexpected error: {err}" + ); + assert_eq!( + builder.executed_count, 0, + "bad queue_index must be rejected before EVM execution" + ); + } + + #[test] + fn test_execute_supplied_transactions_rejects_queue_index_overflow() { + use alloy_consensus::Sealable; + use morph_primitives::TxL1Msg; + + let l1_msg = TxL1Msg { + queue_index: u64::MAX, + gas_limit: 50_000, + to: Address::repeat_byte(0xaa), + value: U256::ZERO, + sender: Address::repeat_byte(0xbb), + input: Bytes::new(), + }; + let encoded = Bytes::from(MorphTxEnvelope::L1Msg(l1_msg.seal_slow()).encoded_2718()); + let ctx = test_ctx_with_timestamp_and_txs(1_800_000_000, vec![encoded]); + let mut builder = ScriptedBlockBuilder::new(std::collections::HashMap::new()); + let mut info = ExecutionInfo::new(u64::MAX, None); + + let err = ctx + .execute_supplied_transactions(&mut builder, &mut info) + .expect_err("u64::MAX queue_index overflow must be rejected cleanly"); + assert!( + err.to_string().contains("queue index overflow"), + "unexpected error: {err}" + ); + assert_eq!( + builder.executed_count, 0, + "overflowing queue_index must be rejected before EVM execution" + ); + } + + // ========================================================================= + // M-H10: MorphTx hardfork & structural validation tests + // ========================================================================= + + #[test] + fn test_validate_morph_tx_for_block_enforces_hardfork_gates_and_validate() { + use alloy_consensus::Signed; + use alloy_primitives::{Signature, TxKind}; + use morph_primitives::TxMorph; + + let chain_spec = morph_chainspec::MORPH_MAINNET.as_ref(); + // Mainnet fork timestamps: emerald=1767765600, jade=1775628000, celadon=1793772000 + let pre_emerald = 1_767_765_599; + let pre_jade = 1_775_627_999; + let pre_celadon = 1_793_771_999; + let celadon = 1_793_772_000; + + let wrap = |tx: TxMorph| { + MorphTxEnvelope::Morph(Signed::new_unchecked( + tx, + Signature::test_signature(), + B256::repeat_byte(0x01), + )) + }; + + let v0 = wrap(TxMorph { + chain_id: 2818, + gas_limit: 50_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + fee_token_id: 1, + version: 0, + ..Default::default() + }); + let v1 = wrap(TxMorph { + chain_id: 2818, + gas_limit: 50_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + fee_token_id: 0, + version: MORPH_TX_VERSION_1, + ..Default::default() + }); + let v2 = wrap(TxMorph { + chain_id: 2818, + gas_limit: 50_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + fee_token_id: 0, + version: MORPH_TX_VERSION_2, + ..Default::default() + }); + let bad_v1_fee_limit = wrap(TxMorph { + chain_id: 2818, + gas_limit: 50_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + fee_token_id: 0, + fee_limit: U256::from(100), + version: MORPH_TX_VERSION_1, + ..Default::default() + }); + + // Pre-Emerald rejects every MorphTx version. + assert!(validate_morph_tx_for_block(&v0, chain_spec, pre_emerald).is_err()); + assert!(validate_morph_tx_for_block(&v1, chain_spec, pre_emerald).is_err()); + assert!(validate_morph_tx_for_block(&v2, chain_spec, pre_emerald).is_err()); + + // Emerald (pre-Jade) permits V0, rejects V1 & V2. + assert!(validate_morph_tx_for_block(&v0, chain_spec, pre_jade).is_ok()); + assert!(validate_morph_tx_for_block(&v1, chain_spec, pre_jade).is_err()); + assert!(validate_morph_tx_for_block(&v2, chain_spec, pre_jade).is_err()); + + // Jade (pre-Celadon) permits V0 & V1, rejects V2. + assert!(validate_morph_tx_for_block(&v0, chain_spec, pre_celadon).is_ok()); + assert!(validate_morph_tx_for_block(&v1, chain_spec, pre_celadon).is_ok()); + assert!(validate_morph_tx_for_block(&v2, chain_spec, pre_celadon).is_err()); + + // Celadon permits V2, but structural `TxMorph::validate()` still rejects bad fields. + assert!(validate_morph_tx_for_block(&v2, chain_spec, celadon).is_ok()); + assert!(validate_morph_tx_for_block(&bad_v1_fee_limit, chain_spec, celadon).is_err()); + } + + #[test] + fn test_execute_pool_transactions_skips_pre_celadon_v2_without_executing_or_evicting() { + use alloy_consensus::Signed; + use alloy_primitives::{Signature, TxKind}; + use morph_primitives::TxMorph; + use morph_txpool::MorphPooledTransaction; + use reth_primitives_traits::Recovered; + + let sender_v2 = Address::repeat_byte(0x11); + let sender_v1 = Address::repeat_byte(0x22); + + let v2_tx = TxMorph { + chain_id: 2818, + nonce: 0, + gas_limit: 50_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + fee_token_id: 0, + version: MORPH_TX_VERSION_2, + ..Default::default() + }; + let v2_hash = B256::repeat_byte(0xaa); + let v2_rec = Recovered::new_unchecked( + MorphTxEnvelope::Morph(Signed::new_unchecked( + v2_tx, + Signature::test_signature(), + v2_hash, + )), + sender_v2, + ); + let v2_len = v2_rec.encode_2718_len(); + let v2_pooled = MorphPooledTransaction::new(v2_rec, v2_len); + + let v1_tx = TxMorph { + chain_id: 2818, + nonce: 0, + gas_limit: 50_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + fee_token_id: 0, + version: MORPH_TX_VERSION_1, + ..Default::default() + }; + let v1_hash = B256::repeat_byte(0xbb); + let v1_rec = Recovered::new_unchecked( + MorphTxEnvelope::Morph(Signed::new_unchecked( + v1_tx, + Signature::test_signature(), + v1_hash, + )), + sender_v1, + ); + let v1_len = v1_rec.encode_2718_len(); + let v1_pooled = MorphPooledTransaction::new(v1_rec, v1_len); + + // Only v1_hash has a scripted outcome; if v2 were executed it would panic. + let mut outcomes = std::collections::HashMap::new(); + outcomes.insert(v1_hash, Ok(21_000)); + let mut builder = ScriptedBlockBuilder::new(outcomes); + let mut info = ExecutionInfo::default(); + let mut executed_txs = Vec::new(); + let best_txs = ScriptedPoolTxs { + txs: std::collections::VecDeque::from([v2_pooled, v1_pooled]), + marked_invalid: Vec::new(), + }; + // Pre-Celadon, post-Jade timestamp on MORPH_MAINNET. + let ctx = test_ctx_with_timestamp_and_txs(1_793_771_999, vec![]); + let breaker = ctx.builder_config.breaker(30_000_000); + let mut evicted = Vec::new(); + + ctx.execute_pool_transactions_with_evictor( + &mut builder, + &mut info, + &mut executed_txs, + best_txs, + &breaker, + |hash| evicted.push(hash), + ) + .expect("pool execution should complete"); + + assert_eq!( + builder.executed_count, 1, + "only V1 should execute; V2 must be skipped pre-Celadon" + ); + assert_eq!(executed_txs.len(), 1); + assert!( + evicted.is_empty(), + "fork-gated skip during reorg build must not evict from pool" + ); + } + + #[test] + fn test_execute_supplied_transactions_rejects_pre_celadon_v2_before_execution() { + use alloy_consensus::Signed; + use alloy_primitives::{Signature, TxKind}; + use morph_primitives::TxMorph; + + let v2_tx = TxMorph { + chain_id: 2818, + nonce: 0, + gas_limit: 50_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + fee_token_id: 0, + version: MORPH_TX_VERSION_2, + ..Default::default() + }; + let encoded = Bytes::from( + MorphTxEnvelope::Morph(Signed::new_unchecked( + v2_tx, + Signature::test_signature(), + B256::repeat_byte(0xcc), + )) + .encoded_2718(), + ); + // Pre-Celadon timestamp on MORPH_MAINNET. + let ctx = test_ctx_with_timestamp_and_txs(1_793_771_999, vec![encoded]); + let mut builder = ScriptedBlockBuilder::new(std::collections::HashMap::new()); + let mut info = ExecutionInfo::default(); + + let err = ctx + .execute_supplied_transactions(&mut builder, &mut info) + .expect_err("pre-Celadon supplied MorphTx V2 must be rejected"); + assert!( + err.to_string().contains("celadon fork not reached"), + "unexpected error: {err}" + ); + assert_eq!( + builder.executed_count, 0, + "fork-invalid supplied MorphTx must be rejected before EVM execution" + ); + } + + // ========================================================================= + // M-M12: Deterministic token-fee failure pool eviction tests + // ========================================================================= + + #[test] + fn test_is_evictable_token_fee_error_classification() { + use revm::context::result::InvalidTransaction; + + // Deterministic token-fee failures MUST evict. + assert!(is_evictable_token_fee_error( + &MorphInvalidTransaction::TokenTransferFailed { + reason: "reverted".into(), + } + )); + assert!(is_evictable_token_fee_error( + &MorphInvalidTransaction::TokenBalanceQueryFailed + )); + assert!(is_evictable_token_fee_error( + &MorphInvalidTransaction::TokenNotRegistered(1) + )); + assert!(is_evictable_token_fee_error( + &MorphInvalidTransaction::TokenNotActive(1) + )); + assert!(is_evictable_token_fee_error( + &MorphInvalidTransaction::InvalidTokenConfig(1) + )); + + // InsufficientTokenBalance and standard ETH errors MUST NOT evict. + assert!(!is_evictable_token_fee_error( + &MorphInvalidTransaction::InsufficientTokenBalance { + required: U256::from(100), + available: U256::from(50), + } + )); + assert!(!is_evictable_token_fee_error( + &MorphInvalidTransaction::EthInvalidTransaction(InvalidTransaction::NonceTooLow { + tx: 0, + state: 1, + }) + )); + assert!(!is_evictable_token_fee_error( + &MorphInvalidTransaction::EthInvalidTransaction( + InvalidTransaction::LackOfFundForMaxFee { + fee: Box::new(U256::from(100)), + balance: Box::new(U256::ZERO), + } + ) + )); + } + + #[test] + fn test_execute_pool_transactions_evicts_only_unexecuted_senders_deterministic_token_errors() { + use alloy_consensus::{Signed, TxEip1559}; + use alloy_primitives::{Signature, TxKind}; + use morph_primitives::TxMorph; + use morph_txpool::MorphPooledTransaction; + use reth_primitives_traits::Recovered; + use std::collections::{HashMap, VecDeque}; + + let make_morph_tx = |signer: Address, nonce: u64, tag: u8| { + let tx = TxMorph { + chain_id: 2818, + nonce, + gas_limit: 50_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + fee_token_id: 1, + ..Default::default() + }; + let hash = B256::repeat_byte(tag); + let env = MorphTxEnvelope::Morph(Signed::new_unchecked( + tx, + Signature::test_signature(), + hash, + )); + let recovered = Recovered::new_unchecked(env, signer); + let len = recovered.encode_2718_len(); + (hash, MorphPooledTransaction::new(recovered, len)) + }; + + let make_eth_tx = |signer: Address, nonce: u64, tag: u8| { + let tx = TxEip1559 { + chain_id: 2818, + nonce, + gas_limit: 21_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + ..Default::default() + }; + let hash = B256::repeat_byte(tag); + let env = MorphTxEnvelope::Eip1559(Signed::new_unchecked( + tx, + Signature::test_signature(), + hash, + )); + let recovered = Recovered::new_unchecked(env, signer); + let len = recovered.encode_2718_len(); + (hash, MorphPooledTransaction::new(recovered, len)) + }; + + let sender_blacklisted = Address::repeat_byte(0x01); + let sender_low_bal = Address::repeat_byte(0x02); + let sender_already_executed = Address::repeat_byte(0x03); + let sender_inactive = Address::repeat_byte(0x04); + + let (h_transfer_fail, tx_transfer_fail) = make_morph_tx(sender_blacklisted, 0, 0x11); + let (h_low_bal, tx_low_bal) = make_morph_tx(sender_low_bal, 0, 0x22); + let (h_exec_ok, tx_exec_ok) = make_eth_tx(sender_already_executed, 0, 0x33); + let (h_exec_then_fail, tx_exec_then_fail) = make_morph_tx(sender_already_executed, 1, 0x34); + let (h_inactive, tx_inactive) = make_morph_tx(sender_inactive, 0, 0x44); + + let mut outcomes = HashMap::new(); + outcomes.insert( + h_transfer_fail, + Err(MorphInvalidTransaction::TokenTransferFailed { + reason: "blacklisted".into(), + }), + ); + outcomes.insert( + h_low_bal, + Err(MorphInvalidTransaction::InsufficientTokenBalance { + required: U256::from(100), + available: U256::from(10), + }), + ); + outcomes.insert(h_exec_ok, Ok(21_000)); + outcomes.insert( + h_exec_then_fail, + Err(MorphInvalidTransaction::TokenTransferFailed { + reason: "post-tx state change".into(), + }), + ); + outcomes.insert(h_inactive, Err(MorphInvalidTransaction::TokenNotActive(1))); + + let mut builder = ScriptedBlockBuilder::new(outcomes); + let mut info = ExecutionInfo::default(); + let mut executed_txs = Vec::new(); + let best_txs = ScriptedPoolTxs { + txs: VecDeque::from([ + tx_transfer_fail, + tx_low_bal, + tx_exec_ok, + tx_exec_then_fail, + tx_inactive, + ]), + marked_invalid: Vec::new(), + }; + // Post-Celadon timestamp so MorphTx hardfork gates pass. + let ctx = test_ctx_with_timestamp_and_txs(1_800_000_000, vec![]); + let breaker = ctx.builder_config.breaker(30_000_000); + let mut evicted = Vec::new(); + + ctx.execute_pool_transactions_with_evictor( + &mut builder, + &mut info, + &mut executed_txs, + best_txs, + &breaker, + |hash| evicted.push(hash), + ) + .expect("pool execution should complete"); + + // Only sender_blacklisted (TokenTransferFailed, unexecuted) and sender_inactive + // (TokenNotActive, unexecuted) should be evicted. + // - sender_low_bal (InsufficientTokenBalance) must NOT be evicted. + // - sender_already_executed nonce 1 (had nonce 0 succeed in this block) must NOT be evicted. + assert_eq!(evicted, vec![h_transfer_fail, h_inactive]); + assert_eq!(executed_txs.len(), 1); + } } diff --git a/crates/revm/src/handler.rs b/crates/revm/src/handler.rs index 4a701649..402bcaa9 100644 --- a/crates/revm/src/handler.rs +++ b/crates/revm/src/handler.rs @@ -419,11 +419,23 @@ where return Ok(()); } + // Enforce the Celadon hardfork gate for MorphTx V2 during real execution + // (including V2 with an empty authorization list). When fee charging is + // disabled (`eth_call` / `eth_estimateGas` simulation), preserve pre-Celadon + // Prague simulation compatibility (matching morph-geth `transaction_args.go:234`). + let hardfork = *evm.ctx_ref().cfg().spec(); + if !evm.ctx_ref().cfg().is_fee_charge_disabled() && !hardfork.is_celadon() { + return Err(MorphInvalidTransaction::EthInvalidTransaction( + InvalidTransaction::Eip7702NotSupported, + ) + .into()); + } + if auth_list_len == 0 { return Ok(()); } - let spec: SpecId = (*evm.ctx_ref().cfg().spec()).into(); + let spec: SpecId = hardfork.into(); if !spec.is_enabled_in(SpecId::PRAGUE) { return Err(MorphInvalidTransaction::EthInvalidTransaction( InvalidTransaction::Eip7702NotSupported, @@ -1844,6 +1856,44 @@ mod tests { )); } + #[test] + fn validate_env_rejects_v2_morph_tx_before_celadon_during_execution() { + // Jade has Prague/Osaka active, so `SpecId::PRAGUE` alone would miss the + // Celadon gate. Real execution (`disable_fee_charge = false`) must reject + // MorphTx V2 before Celadon both with and without authorizations. + for auths in [vec![], vec![Either::Left(sample_signed_authorization())]] { + let mut evm = evm_with_spec(MorphHardfork::Jade); + evm.tx = morph_tx_env_with_authorizations( + Some(MORPH_TX_VERSION_2), + TxKind::Call(Address::ZERO), + auths, + ); + + let err = validate_env_of(&mut evm).unwrap_err(); + assert!(matches!( + err, + EVMError::Transaction(MorphInvalidTransaction::EthInvalidTransaction( + InvalidTransaction::Eip7702NotSupported + )) + )); + } + } + + #[test] + fn validate_env_allows_v2_morph_tx_simulation_before_celadon() { + // RPC simulation (`disable_fee_charge = true`) preserves pre-Celadon Prague + // compatibility, matching morph-geth `transaction_args.go`. + let mut evm = evm_with_spec(MorphHardfork::Jade); + evm.cfg.disable_fee_charge = true; + evm.tx = morph_tx_env_with_authorizations( + Some(MORPH_TX_VERSION_2), + TxKind::Call(Address::ZERO), + vec![Either::Left(sample_signed_authorization())], + ); + + assert!(validate_env_of(&mut evm).is_ok()); + } + #[test] fn validate_env_keeps_accepting_v1_morph_tx_without_authorizations() { let mut evm = evm_with_spec(MorphHardfork::Celadon); diff --git a/crates/rpc/src/eth/transaction.rs b/crates/rpc/src/eth/transaction.rs index d3d0339a..50ed8c3e 100644 --- a/crates/rpc/src/eth/transaction.rs +++ b/crates/rpc/src/eth/transaction.rs @@ -8,7 +8,7 @@ use alloy_rpc_types_eth::AccessList; use reth_rpc_convert::{SignTxRequestError, SignableTxRequest, TryIntoSimTx, TryIntoTxEnv}; use reth_rpc_eth_types::EthApiError; -use morph_primitives::{MorphTxEnvelope, TxMorph}; +use morph_primitives::{MorphTxEnvelope, TxMorph, transaction::morph_transaction::MAX_MEMO_LENGTH}; use morph_revm::{MorphBlockEnv, MorphTxEnv}; use reth_evm::EvmEnv; @@ -135,13 +135,26 @@ impl TryIntoTxEnv for MorphTransactionReq let mut tx_env = MorphTxEnv::new(inner_tx_env); if is_morph_tx { - tx_env.fee_token_id = match fee_token_id { + let parsed_fee_token_id = match fee_token_id { Some(id) => Some( u16::try_from(id.to::()) .map_err(|_| EthApiError::InvalidParams("invalid token".to_string()))?, ), None => None, }; + if memo.as_ref().is_some_and(|m| m.len() > MAX_MEMO_LENGTH) { + return Err(EthApiError::InvalidParams( + "memo exceeds maximum length of 64 bytes".to_string(), + )); + } + if parsed_fee_token_id.unwrap_or(0) == 0 + && fee_limit.is_some_and(|limit| limit > U256::ZERO) + { + return Err(EthApiError::InvalidParams( + "MorphTx cannot have FeeLimit when FeeTokenID is 0".to_string(), + )); + } + tx_env.fee_token_id = parsed_fee_token_id; tx_env.fee_limit = fee_limit; tx_env.reference = reference; tx_env.memo = memo; @@ -1560,4 +1573,70 @@ mod tests { // = 500_000_000 + 1_000_000_000 = 1_500_000_000 assert_eq!(rpc_tx.effective_gas_price, Some(1_500_000_000)); } + + #[test] + fn try_into_tx_env_rejects_oversized_morph_tx_memo() { + let evm_env = create_evm_env(true); + + // Exactly MAX_MEMO_LENGTH (64) bytes is accepted. + let ok_req = MorphTransactionRequest { + inner: create_morph_transaction_request(), + fee_token_id: None, + fee_limit: None, + reference: None, + memo: Some(Bytes::from(vec![0xaa; MAX_MEMO_LENGTH])), + }; + assert!(ok_req.try_into_tx_env(&evm_env).is_ok()); + + // MAX_MEMO_LENGTH + 1 (65) bytes is rejected. + let bad_req = MorphTransactionRequest { + inner: create_morph_transaction_request(), + fee_token_id: None, + fee_limit: None, + reference: None, + memo: Some(Bytes::from(vec![0xaa; MAX_MEMO_LENGTH + 1])), + }; + let err = bad_req.try_into_tx_env(&evm_env).unwrap_err(); + match err { + EthApiError::InvalidParams(msg) => { + assert!(msg.contains("64 bytes"), "unexpected error: {msg}"); + } + other => panic!("expected InvalidParams, got {other:?}"), + } + } + + #[test] + fn try_into_tx_env_rejects_fee_limit_with_zero_fee_token_id() { + let evm_env = create_evm_env(true); + + for fee_token_id in [None, Some(U64::ZERO)] { + let bad_req = MorphTransactionRequest { + inner: create_morph_transaction_request(), + fee_token_id, + fee_limit: Some(U256::from(100)), + reference: Some(B256::repeat_byte(0x11)), + memo: None, + }; + let err = bad_req.try_into_tx_env(&evm_env).unwrap_err(); + match err { + EthApiError::InvalidParams(msg) => { + assert!( + msg.contains("FeeLimit") && msg.contains("FeeTokenID"), + "unexpected error: {msg}" + ); + } + other => panic!("expected InvalidParams, got {other:?}"), + } + } + + // Zero fee_limit with fee_token_id == 0 is permitted. + let ok_req = MorphTransactionRequest { + inner: create_morph_transaction_request(), + fee_token_id: Some(U64::ZERO), + fee_limit: Some(U256::ZERO), + reference: Some(B256::repeat_byte(0x11)), + memo: None, + }; + assert!(ok_req.try_into_tx_env(&evm_env).is_ok()); + } } From a386f3250d29fefcb00bad04ca1236905d3ef03a Mon Sep 17 00:00:00 2001 From: panos-xyz Date: Fri, 27 Nov 2026 15:07:42 +0800 Subject: [PATCH 2/4] fix(engine,validator,consensus,builder): align PR #240 validation, WTR, L1 index, and pool eviction with morph-geth - Exempt locally built blocks (MorphPayloadValidationMode::LocallyBuilt) and L1-derived safe blocks (MorphPayloadValidationMode::Safe) from wall-clock TimestampIsInFuture, 1/1024 GasLimit bounds, BaseFeeOverLimit, and local DA payload byte caps across both on_inserted_executed_block and validate_payload (and TimestampIsInPast under Safe), matching morph-geth's verified and NewSafeL2Block(safe=true) semantics while preserving structural invariants and leading L1 forward skips under no_tx_pool. - Validate non-zero withdraw_trie_root across locally verified blocks, in-memory tree_state AlreadySeen blocks, DB-persisted AlreadySeen blocks, and live blocks whose own diff did not touch L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT, without poisoning invalid_headers. - Restrict M-M12 pool eviction in execute_pool_transactions to builds on the current canonical head synchronized with the pool, seed executed_senders from supplied transactions, and re-verify failing MorphTx pre-execution/fee deduction against the clean parent state via MorphEvm::validate_only whenever earlier transactions have mutated in-block state. - Share a bounded TreeHeaderCache between MorphTreeEngineValidator and RealMorphL2EngineApi so unpersisted in-memory tree_state parent headers are resolved during next_l1_message_index checks, and allow Pre-Jade blocks without L1 messages to carry decreased/zero next_l1_msg_index across consensus, validator, and engine API layers. --- crates/consensus/src/validation.rs | 374 +++++++++---- crates/engine-api/src/builder.rs | 160 +++++- crates/evm/src/evm.rs | 15 + crates/node/src/add_ons.rs | 11 +- crates/node/src/test_utils.rs | 30 ++ crates/node/src/validator.rs | 497 +++++++++++++++--- crates/node/tests/it/engine.rs | 312 +++++++++++ .../node/tests/it/invalid_payload_recovery.rs | 451 ++++++++++++++-- crates/node/tests/it/morph_tx.rs | 242 +++++++++ crates/payload/builder/src/builder.rs | 362 ++++++++++++- crates/payload/types/src/lib.rs | 146 ++++- 11 files changed, 2351 insertions(+), 249 deletions(-) diff --git a/crates/consensus/src/validation.rs b/crates/consensus/src/validation.rs index 3f101eea..b9c5e52d 100644 --- a/crates/consensus/src/validation.rs +++ b/crates/consensus/src/validation.rs @@ -116,50 +116,32 @@ impl MorphConsensus { pub fn chain_spec(&self) -> &MorphChainSpec { &self.chain_spec } -} - -// ============================================================================ -// HeaderValidator Implementation -// ============================================================================ -impl HeaderValidator for MorphConsensus { - /// Validates a block header according to Morph L2 consensus rules. - /// - /// # Validation Steps - /// - /// 1. **Extra Data**: Must be empty (Morph L2 specific) - /// 2. **Nonce**: Must be 0 (post-merge Ethereum) - /// 3. **Ommers Hash**: Must be empty ommer root hash (post-merge) - /// 4. **Difficulty**: Must be 0 (post-merge) - /// 5. **Coinbase**: Must be zero address if FeeVault is enabled - /// 6. **Timestamp**: Must not be in the future - /// 7. **Gas Limit**: Must be <= MAX_GAS_LIMIT - /// 8. **Gas Used**: Must be <= gas limit - /// 9. **Base Fee**: Must always be set (EIP-1559 is always active) and <= 10 Gwei - fn validate_header(&self, header: &SealedHeader) -> Result<(), ConsensusError> { - // Extra data must be empty (Morph L2 specific - stricter than max length) + /// Validates structural header invariants that apply even to locally built and + /// L1-derived safe blocks (exempting wall-clock `TimestampIsInFuture`, `MAX_GAS_LIMIT`, + /// and `MORPH_MAXIMUM_BASE_FEE`). + pub fn validate_header_structural( + &self, + header: &SealedHeader, + ) -> Result<(), ConsensusError> { if !header.extra_data().is_empty() { return Err(ConsensusError::ExtraDataExceedsMax { len: header.extra_data().len(), }); } - // Nonce must be 0 (same as post-merge Ethereum) if !header.nonce().is_some_and(|nonce| nonce.is_zero()) { return Err(ConsensusError::TheMergeNonceIsNotZero); } - // Ommers hash must be empty (same as post-merge Ethereum) if header.ommers_hash() != EMPTY_OMMER_ROOT_HASH { return Err(ConsensusError::TheMergeOmmerRootIsNotEmpty); } - // Difficulty must be 0 (same as post-merge Ethereum) if !header.difficulty().is_zero() { return Err(ConsensusError::TheMergeDifficultyIsNotZero); } - // Coinbase must be zero if FeeVault is enabled (Morph L2 specific) if self.chain_spec.is_fee_vault_enabled() && header.beneficiary() != alloy_primitives::Address::ZERO { @@ -168,6 +150,140 @@ impl HeaderValidator for MorphConsensus { ))); } + if header.gas_used() > header.gas_limit() { + return Err(ConsensusError::HeaderGasUsedExceedsGasLimit { + gas_used: header.gas_used(), + gas_limit: header.gas_limit(), + }); + } + + if header.base_fee_per_gas().is_none() { + return Err(ConsensusError::BaseFeeMissing); + } + + Ok(()) + } + + /// Validates structural parent-header continuity (`parent_hash`, `number == parent + 1`, + /// and from Jade onward L1 message index monotonicity), exempting timestamp and 1/1024 + /// gas-limit bounds. + pub fn validate_header_against_parent_structural( + &self, + header: &SealedHeader, + parent: &SealedHeader, + ) -> Result<(), ConsensusError> { + validate_against_parent_hash_number(header.header(), parent)?; + + // From Jade onward, `next_l1_msg_index` must never decrease across blocks. + // Pre-Jade historical blocks without L1 messages are permitted to carry an older/zero + // `next_l1_msg_index` (matching morph-geth's `blockchain_l2.go` pre-Jade skip and + // `MorphTreeEngineValidator::validate_l1_msg_index_against_parent`); pre-Jade blocks + // that DO contain L1 messages remain constrained by `first_queue_index >= parent.next` + // and `header.next >= last_queue_index + 1`. + if self + .chain_spec + .is_jade_active_at_timestamp(header.timestamp()) + && header.next_l1_msg_index < parent.next_l1_msg_index + { + return Err(ConsensusError::other( + MorphConsensusError::InvalidNextL1MessageIndex { + expected: parent.next_l1_msg_index, + actual: header.next_l1_msg_index, + }, + )); + } + + Ok(()) + } + + /// Validates parent-header continuity and timestamp progression for locally assembled blocks + /// (exempting the 1/1024 gas-limit bound). + pub fn validate_header_against_parent_locally_built( + &self, + header: &SealedHeader, + parent: &SealedHeader, + ) -> Result<(), ConsensusError> { + self.validate_header_against_parent_structural(header, parent)?; + let is_emerald = self + .chain_spec + .is_emerald_active_at_timestamp(header.timestamp()); + validate_against_parent_timestamp(header.header(), parent.header(), is_emerald) + } + + /// Validates pre-execution body invariants except the local per-block DA byte limit + /// (`max_tx_payload_bytes_per_block`), matching morph-geth's `verified` and `NewSafeL2Block` + /// (`safe = true`) exemptions. + pub fn validate_block_pre_execution_without_da_limit( + &self, + block: &SealedBlock, + ) -> Result<(), ConsensusError> { + let ommers_len = block.body().ommers().map(|o| o.len()).unwrap_or_default(); + if ommers_len > 0 { + return Err(ConsensusError::msg("uncles not allowed")); + } + + if block.ommers_hash() != EMPTY_OMMER_ROOT_HASH { + return Err(ConsensusError::BodyOmmersHashDiff( + GotExpected { + got: block.ommers_hash(), + expected: EMPTY_OMMER_ROOT_HASH, + } + .into(), + )); + } + + if let Err(error) = block.ensure_transaction_root_valid() { + return Err(ConsensusError::BodyTransactionRootDiff(error.into())); + } + + if block.body().withdrawals().is_some() { + return Err(ConsensusError::other( + MorphConsensusError::WithdrawalsNonEmpty, + )); + } + + let is_emerald = self + .chain_spec + .is_emerald_active_at_timestamp(block.header().timestamp()); + let is_jade = self + .chain_spec + .is_jade_active_at_timestamp(block.header().timestamp()); + let is_celadon = self + .chain_spec + .is_celadon_active_at_timestamp(block.header().timestamp()); + validate_morph_txs(&block.body().transactions, is_emerald, is_jade, is_celadon)?; + + validate_l1_messages_in_block( + &block.body().transactions, + block.header().next_l1_msg_index, + is_jade, + )?; + + Ok(()) + } +} + +// ============================================================================ +// HeaderValidator Implementation +// ============================================================================ + +impl HeaderValidator for MorphConsensus { + /// Validates a block header according to Morph L2 consensus rules. + /// + /// # Validation Steps + /// + /// 1. **Extra Data**: Must be empty (Morph L2 specific) + /// 2. **Nonce**: Must be 0 (post-merge Ethereum) + /// 3. **Ommers Hash**: Must be empty ommer root hash (post-merge) + /// 4. **Difficulty**: Must be 0 (post-merge) + /// 5. **Coinbase**: Must be zero address if FeeVault is enabled + /// 6. **Timestamp**: Must not be in the future + /// 7. **Gas Limit**: Must be <= MAX_GAS_LIMIT + /// 8. **Gas Used**: Must be <= gas limit + /// 9. **Base Fee**: Must always be set (EIP-1559 is always active) and <= 10 Gwei + fn validate_header(&self, header: &SealedHeader) -> Result<(), ConsensusError> { + self.validate_header_structural(header)?; + // Check timestamp is not in the future let now = std::time::SystemTime::now() .duration_since(std::time::SystemTime::UNIX_EPOCH) @@ -188,15 +304,7 @@ impl HeaderValidator for MorphConsensus { }); } - // Gas used must be <= gas limit - if header.gas_used() > header.gas_limit() { - return Err(ConsensusError::HeaderGasUsedExceedsGasLimit { - gas_used: header.gas_used(), - gas_limit: header.gas_limit(), - }); - } - - // Validate base fee (always required, EIP-1559 is always active) + // Validate base fee upper bound (presence is checked in validate_header_structural) let base_fee = header .base_fee_per_gas() .ok_or(ConsensusError::BaseFeeMissing)?; @@ -222,8 +330,8 @@ impl HeaderValidator for MorphConsensus { header: &SealedHeader, parent: &SealedHeader, ) -> Result<(), ConsensusError> { - // Validate parent hash and block number - validate_against_parent_hash_number(header.header(), parent)?; + // Validate parent hash, block number, and (from Jade onward) L1 message index monotonicity + self.validate_header_against_parent_structural(header, parent)?; // Validate timestamp against parent (pre-Emerald: strict >, post-Emerald: >=) let is_emerald = self @@ -234,18 +342,6 @@ impl HeaderValidator for MorphConsensus { // Validate gas limit change validate_against_parent_gas_limit(header.header(), parent.header())?; - // Cross-block L1 message index monotonicity: next_l1_msg_index must never - // decrease across blocks. This is the header-only half of L1 message - // validation; the body-level half is in validate_block_pre_execution. - if header.next_l1_msg_index < parent.next_l1_msg_index { - return Err(ConsensusError::other( - MorphConsensusError::InvalidNextL1MessageIndex { - expected: parent.next_l1_msg_index, - actual: header.next_l1_msg_index, - }, - )); - } - Ok(()) } } @@ -282,34 +378,8 @@ impl Consensus for MorphConsensus { &self, block: &SealedBlock, ) -> Result<(), ConsensusError> { - // Check no uncles allowed (Morph L2 has no uncle blocks) - let ommers_len = block.body().ommers().map(|o| o.len()).unwrap_or_default(); - if ommers_len > 0 { - return Err(ConsensusError::msg("uncles not allowed")); - } - - // Check ommers hash must be empty root hash - if block.ommers_hash() != EMPTY_OMMER_ROOT_HASH { - return Err(ConsensusError::BodyOmmersHashDiff( - GotExpected { - got: block.ommers_hash(), - expected: EMPTY_OMMER_ROOT_HASH, - } - .into(), - )); - } - - // Check transaction root - if let Err(error) = block.ensure_transaction_root_valid() { - return Err(ConsensusError::BodyTransactionRootDiff(error.into())); - } - - // Check withdrawals are empty - if block.body().withdrawals().is_some() { - return Err(ConsensusError::other( - MorphConsensusError::WithdrawalsNonEmpty, - )); - } + // Check no uncles, ommers hash, tx root, withdrawals, MorphTx, and L1 message rules. + self.validate_block_pre_execution_without_da_limit(block)?; // Matches go-ethereum's BlockValidator.ValidateBody() → IsValidBlockSize(). validate_l2_tx_payload_size( @@ -317,30 +387,6 @@ impl Consensus for MorphConsensus { self.chain_spec.max_tx_payload_bytes_per_block(), )?; - // Validate MorphTx activation, version and field constraints. - // Matches go-ethereum's BlockValidator.ValidateBody() → ValidateMorphTxVersion(). - let is_emerald = self - .chain_spec - .is_emerald_active_at_timestamp(block.header().timestamp()); - let is_jade = self - .chain_spec - .is_jade_active_at_timestamp(block.header().timestamp()); - let is_celadon = self - .chain_spec - .is_celadon_active_at_timestamp(block.header().timestamp()); - validate_morph_txs(&block.body().transactions, is_emerald, is_jade, is_celadon)?; - - // Validate L1 messages ordering and internal consistency with header. - // This is the body-level half of L1 validation; it verifies that the L1 - // messages within this block are internally consistent with the header's - // next_l1_msg_index. The cross-block monotonicity check (ensuring - // next_l1_msg_index >= parent's value) is in validate_header_against_parent. - validate_l1_messages_in_block( - &block.body().transactions, - block.header().next_l1_msg_index, - is_jade, - )?; - Ok(()) } @@ -2491,4 +2537,132 @@ mod tests { Err(ConsensusError::BlockGasUsed { .. }) )); } + + #[test] + fn test_structural_and_locally_built_exemptions_preserve_hard_invariants() { + let consensus = MorphConsensus::new(create_test_chainspec_with_payload_limit(64)); + + let parent = SealedHeader::seal_slow(create_valid_morph_header(1000, 30_000_000, 100)); + + // Future timestamp, doubled gas_limit (> 1/1024), and base_fee > MORPH_MAXIMUM_BASE_FEE: + // full validation rejects each, while structural / locally-built exempts the intended checks. + let future_ts = u64::MAX - 10; + let mut child = create_valid_morph_header(future_ts, 60_000_000, 101); + child.inner.parent_hash = parent.hash(); + child.inner.base_fee_per_gas = Some(MORPH_MAXIMUM_BASE_FEE + 1); + let child_sealed = SealedHeader::seal_slow(child.clone()); + + assert!(matches!( + consensus.validate_header(&child_sealed), + Err(ConsensusError::TimestampIsInFuture { .. }) + )); + assert!(consensus.validate_header_structural(&child_sealed).is_ok()); + + assert!(matches!( + consensus.validate_header_against_parent(&child_sealed, &parent), + Err(ConsensusError::GasLimitInvalidIncrease { .. }) + )); + assert!( + consensus + .validate_header_against_parent_locally_built(&child_sealed, &parent) + .is_ok() + ); + assert!( + consensus + .validate_header_against_parent_structural(&child_sealed, &parent) + .is_ok() + ); + + // Timestamp behind parent: rejected for LocallyBuilt, exempted for Safe (structural). + let mut past_child = child; + past_child.inner.timestamp = 999; + let past_sealed = SealedHeader::seal_slow(past_child); + assert!(matches!( + consensus.validate_header_against_parent_locally_built(&past_sealed, &parent), + Err(ConsensusError::TimestampIsInPast { .. }) + )); + assert!( + consensus + .validate_header_against_parent_structural(&past_sealed, &parent) + .is_ok() + ); + + // Structural violations (e.g. non-empty extra_data or gas_used > gas_limit) still fail. + let mut bad_extra = create_valid_morph_header(1001, 30_000_000, 101); + bad_extra.inner.extra_data = Bytes::from_static(b"bad"); + assert!( + consensus + .validate_header_structural(&SealedHeader::seal_slow(bad_extra)) + .is_err() + ); + + // Oversized L2 payload: rejected by full pre-execution, accepted by without_da_limit. + let oversized_tx = create_legacy_tx_with_input(Bytes::from(vec![0xab; 256])); + let oversized_block = create_sealed_block(0, vec![oversized_tx]); + assert!( + consensus + .validate_block_pre_execution(&oversized_block) + .is_err() + ); + assert!( + consensus + .validate_block_pre_execution_without_da_limit(&oversized_block) + .is_ok() + ); + } + + #[test] + fn test_validate_header_against_parent_allows_pre_jade_decreased_l1_msg_index() { + let genesis_json = serde_json::json!({ + "config": { + "chainId": 1337, + "homesteadBlock": 0, + "eip150Block": 0, + "eip155Block": 0, + "eip158Block": 0, + "byzantiumBlock": 0, + "constantinopleBlock": 0, + "petersburgBlock": 0, + "istanbulBlock": 0, + "berlinBlock": 0, + "londonBlock": 0, + "bernoulliBlock": 0, + "curieBlock": 0, + "morph203Time": 0, + "viridianTime": 0, + "emeraldTime": 0, + "jadeForkTime": 2000, + "morph": {} + }, + "alloc": {} + }); + let genesis: Genesis = serde_json::from_value(genesis_json).unwrap(); + let consensus = MorphConsensus::new(Arc::new(MorphChainSpec::from(genesis))); + + let mut parent = create_valid_morph_header(1000, 30_000_000, 100); + parent.next_l1_msg_index = 10; + let parent_sealed = SealedHeader::seal_slow(parent); + + // Pre-Jade (timestamp 1001 < 2000): decreased next_l1_msg_index is allowed on headers. + let mut pre_jade_child = create_valid_morph_header(1001, 30_000_000, 101); + pre_jade_child.inner.parent_hash = parent_sealed.hash(); + pre_jade_child.next_l1_msg_index = 0; + let pre_jade_sealed = SealedHeader::seal_slow(pre_jade_child); + assert!( + consensus + .validate_header_against_parent(&pre_jade_sealed, &parent_sealed) + .is_ok() + ); + + // Post-Jade (timestamp 2000 >= 2000): decreased next_l1_msg_index is rejected. + let mut post_jade_child = create_valid_morph_header(2000, 30_000_000, 101); + post_jade_child.inner.parent_hash = parent_sealed.hash(); + post_jade_child.next_l1_msg_index = 0; + let post_jade_sealed = SealedHeader::seal_slow(post_jade_child); + assert!( + consensus + .validate_header_against_parent(&post_jade_sealed, &parent_sealed) + .is_err() + ); + } } diff --git a/crates/engine-api/src/builder.rs b/crates/engine-api/src/builder.rs index 979ddd09..8a13f073 100644 --- a/crates/engine-api/src/builder.rs +++ b/crates/engine-api/src/builder.rs @@ -14,16 +14,26 @@ use alloy_rpc_types_engine::{PayloadAttributes, PayloadStatus, PayloadStatusEnum use morph_chainspec::{MorphChainSpec, MorphHardforks}; use morph_payload_types::{ AssembleL2BlockParams, AssembleL2BlockV2Params, ExecutableL2Data, GenericResponse, - MorphBuiltPayload, MorphExecutionData, MorphPayloadTypes, SafeL2Data, + MorphBuiltPayload, MorphExecutionData, MorphPayloadTypes, MorphPayloadValidationMode, + SafeL2Data, TreeHeaderCache, }; use morph_primitives::{Block, BlockBody, MorphHeader, MorphTxEnvelope}; -use parking_lot::RwLock; +use parking_lot::{Mutex, RwLock}; use reth_payload_builder::{BuildNewPayload, PayloadBuilderHandle}; #[cfg(test)] use reth_primitives_traits::RecoveredBlock; use reth_primitives_traits::{FastInstant as Instant, SealedBlock, SealedHeader}; use reth_provider::{BlockNumReader, BlockReaderIdExt, CanonChainTracker, HeaderProvider}; -use std::sync::Arc; +use std::{ + collections::{HashMap, VecDeque}, + sync::Arc, +}; + +#[derive(Debug, Default)] +struct VerifiedBlocksCache { + entries: HashMap, + order: VecDeque, +} // ============================================================================= // Real Implementation @@ -50,6 +60,15 @@ pub struct RealMorphL2EngineApi { /// Tracks L1-derived finalized block tags for FCU updates. block_tag_tracker: Arc, + /// Shared cache of unpersisted in-memory `tree_state` headers populated by the + /// engine tree validator. + tree_headers: Arc, + + /// Locally assembled block hashes mapped to their computed `withdraw_trie_root`, + /// mirroring morph-geth's `api.verified` cache for `AssembleL2Block(V2)` -> + /// `ValidateL2Block` / `NewL2Block(V2)`. + verified_blocks: Mutex, + /// Serializes payload builds to prevent concurrent deterministic `PayloadId` /// collisions in reth's `PayloadBuilderService`. build_lock: tokio::sync::Mutex<()>, @@ -162,6 +181,8 @@ fn payload_timestamp( } impl RealMorphL2EngineApi { + const MAX_VERIFIED_BLOCKS: usize = 1024; + /// Creates a new [`RealMorphL2EngineApi`]. pub fn new( provider: Provider, @@ -176,12 +197,46 @@ impl RealMorphL2EngineApi { chain_spec, engine_handle, block_tag_tracker, + tree_headers: Arc::new(TreeHeaderCache::new()), + verified_blocks: Mutex::new(VerifiedBlocksCache::default()), build_lock: tokio::sync::Mutex::new(()), fcu_lock: tokio::sync::Mutex::new(()), metrics: MorphEngineApiMetrics::default(), } } + /// Attaches a shared [`TreeHeaderCache`] so unpersisted in-memory `tree_state` + /// headers are visible during parent lookups. + pub fn with_tree_headers(mut self, tree_headers: Arc) -> Self { + self.tree_headers = tree_headers; + self + } + + fn record_verified_block(&self, block_hash: B256, withdraw_trie_root: B256) { + let mut cache = self.verified_blocks.lock(); + let is_new = cache + .entries + .insert(block_hash, withdraw_trie_root) + .is_none(); + if is_new { + cache.order.push_back(block_hash); + while cache.entries.len() > Self::MAX_VERIFIED_BLOCKS { + let Some(evicted) = cache.order.pop_front() else { + break; + }; + cache.entries.remove(&evicted); + } + } + } + + fn verified_withdraw_trie_root(&self, block_hash: B256) -> Option { + self.verified_blocks + .lock() + .entries + .get(&block_hash) + .copied() + } + /// Updates `head_block_timegap_seconds` gauge after a successful block import. fn record_head_metrics(&self, block_timestamp: u64) { let now_secs = std::time::SystemTime::now() @@ -237,6 +292,7 @@ where self.metrics.assemble_l2_block_failures_total.increment(1); })?; let executable_data = built_payload.executable_data; + self.record_verified_block(executable_data.hash, executable_data.withdraw_trie_root); tracing::debug!( target: "morph::engine", @@ -260,9 +316,7 @@ where // looked up by hash and need not be the canonical head — that is the point of V2 // (the sequencer can build on a parent that diverges from its current head). let parent = self - .provider - .sealed_header_by_hash(parent_hash) - .map_err(|e| MorphEngineApiError::Database(e.to_string()))? + .lookup_sealed_header_by_hash(parent_hash)? .ok_or_else(|| { MorphEngineApiError::Internal(format!("parent block not found: {parent_hash}")) })?; @@ -290,6 +344,7 @@ where self.metrics.assemble_l2_block_failures_total.increment(1); })?; let executable_data = built_payload.executable_data; + self.record_verified_block(executable_data.hash, executable_data.withdraw_trie_root); tracing::debug!( target: "morph::engine", @@ -351,7 +406,7 @@ where } // 2. Convert and forward to reth engine tree (`newPayload` path). - let (payload, _) = match self.execution_payload_from_executable_data(&data) { + let (mut payload, _) = match self.execution_payload_from_executable_data(&data) { Ok(v) => v, Err(err) => { tracing::warn!( @@ -385,6 +440,27 @@ where return Ok(GenericResponse { success: false }); } + // 2c. Match morph-geth's `isVerified` branch: if this exact block hash was assembled + // locally, cross-check any non-zero `withdraw_trie_root` immediately and mark the + // payload `LocallyBuilt` so empty/reorg builds do not fail wall-clock checks. + if let Some(actual_wtr) = self.verified_withdraw_trie_root(payload.block.hash()) { + if !data.withdraw_trie_root.is_zero() && data.withdraw_trie_root != actual_wtr { + tracing::warn!( + target: "morph::engine", + block_hash = %data.hash, + expected = %actual_wtr, + actual = %data.withdraw_trie_root, + "validate_l2_block failed: wrong withdraw_trie_root on locally verified block" + ); + self.metrics.validate_l2_block_failures_total.increment(1); + self.metrics + .validate_l2_block_duration_seconds + .record(validate_started.elapsed()); + return Ok(GenericResponse { success: false }); + } + payload = payload.with_validation_mode(MorphPayloadValidationMode::LocallyBuilt); + } + let status = match self.engine_handle.new_payload(payload).await { Ok(status) => status, Err(err) => { @@ -488,7 +564,7 @@ where let block_hash = data.hash; let block_number = data.number; let block_timestamp = data.timestamp; - self.import_l2_block_via_engine(data, B256::ZERO) + self.import_l2_block_via_engine(data, B256::ZERO, MorphPayloadValidationMode::Full) .await .inspect_err(|_| { self.metrics.new_l2_block_failures_total.increment(1); @@ -528,9 +604,7 @@ where // chain onto this block. This is the centralized-sequencer import path, // where the sequencer may rebuild and replace recent blocks. let parent = self - .provider - .sealed_header_by_hash(data.parent_hash) - .map_err(|e| MorphEngineApiError::Database(e.to_string()))? + .lookup_sealed_header_by_hash(data.parent_hash)? .ok_or_else(|| { MorphEngineApiError::Internal(format!( "parent block not found: {}", @@ -556,7 +630,7 @@ where // FCU advances or reorgs the canonical head onto data.hash. let block_timestamp = data.timestamp; let header = self - .import_l2_block_via_engine(data, B256::ZERO) + .import_l2_block_via_engine(data, B256::ZERO, MorphPayloadValidationMode::Full) .await .inspect_err(|_| { self.metrics.new_l2_block_failures_total.increment(1); @@ -623,12 +697,16 @@ where let block_hash = executable_data.hash; // 3. Import the block through reth engine tree, marking the imported block safe - // in the same FCU. Do not mark it finalized: L1 derivation can still reorg this - // block, and finalized is only authoritative when supplied by BlockTagService via - // set_block_tags. Return the in-path header (do not rely on immediate DB - // visibility after FCU). + // in the same FCU. Pass `MorphPayloadValidationMode::Safe` to match morph-geth's + // `NewSafeL2Block` (`safe = true`), exempting `VerifyHeader` and `ValidateBody` + // DA byte-limit checks so follower clock skew or L1 batch parameter updates + // cannot stall L1 derivation. let header = self - .import_l2_block_via_engine(executable_data, block_hash) + .import_l2_block_via_engine( + executable_data, + block_hash, + MorphPayloadValidationMode::Safe, + ) .await .inspect_err(|_| { self.metrics.new_safe_l2_block_failures_total.increment(1); @@ -767,6 +845,23 @@ where } impl RealMorphL2EngineApi { + /// Looks up a sealed header by hash, checking the shared in-memory `tree_state` + /// header cache first before falling back to `self.provider` (canonical memory + DB). + fn lookup_sealed_header_by_hash( + &self, + hash: B256, + ) -> EngineApiResult>> + where + Provider: HeaderProvider
, + { + if let Some(header) = self.tree_headers.get(&hash) { + return Ok(Some(header)); + } + self.provider + .sealed_header_by_hash(hash) + .map_err(|e| MorphEngineApiError::Database(e.to_string())) + } + /// Looks up a sealed header by hash and verifies that it belongs to the current /// canonical chain. /// @@ -834,9 +929,7 @@ impl RealMorphL2EngineApi { let (parent_number, parent_hash, parent_timestamp) = match parent_override { Some(parent_hash) => { let parent = self - .provider - .sealed_header_by_hash(parent_hash) - .map_err(|e| MorphEngineApiError::Database(e.to_string()))? + .lookup_sealed_header_by_hash(parent_hash)? .ok_or_else(|| { MorphEngineApiError::Internal(format!( "parent block not found: {parent_hash}" @@ -955,11 +1048,7 @@ impl RealMorphL2EngineApi { where Provider: HeaderProvider
, { - let Some(parent) = self - .provider - .sealed_header_by_hash(block.parent_hash()) - .map_err(|e| MorphEngineApiError::Database(e.to_string()))? - else { + let Some(parent) = self.lookup_sealed_header_by_hash(block.parent_hash())? else { return Ok(()); }; @@ -994,14 +1083,18 @@ impl RealMorphL2EngineApi { }; } + let has_l1_msgs = !first_l1_msg; let actual = block.header().next_l1_msg_index; let is_jade = self .chain_spec .is_jade_active_at_timestamp(block.header().timestamp()); + // Pre-Jade historical blocks without L1 messages are exempt from parent-index + // comparison, matching morph-geth `blockchain_l2.go` and + // `MorphTreeEngineValidator::validate_l1_msg_index_against_parent`. let invalid = if is_jade { actual != expected } else { - actual < expected + has_l1_msgs && actual < expected }; if invalid { return Err(MorphEngineApiError::ValidationFailed(format!( @@ -1016,6 +1109,7 @@ impl RealMorphL2EngineApi { &self, data: ExecutableL2Data, safe_block_hash: B256, + mut validation_mode: MorphPayloadValidationMode, ) -> EngineApiResult where Provider: HeaderProvider
@@ -1025,6 +1119,20 @@ impl RealMorphL2EngineApi { let (payload, header) = self.execution_payload_from_executable_data(&data)?; self.validate_next_l1_message_index(payload.block.as_ref())?; + if validation_mode == MorphPayloadValidationMode::Full + && let Some(actual_wtr) = self.verified_withdraw_trie_root(payload.block.hash()) + { + if !data.withdraw_trie_root.is_zero() && data.withdraw_trie_root != actual_wtr { + return Err(MorphEngineApiError::ValidationFailed(format!( + "withdraw trie root mismatch: expected {}, got {}", + data.withdraw_trie_root, actual_wtr + ))); + } + validation_mode = MorphPayloadValidationMode::LocallyBuilt; + } + + let payload = payload.with_validation_mode(validation_mode); + let payload_status = self .engine_handle .new_payload(payload) diff --git a/crates/evm/src/evm.rs b/crates/evm/src/evm.rs index 32a67f87..8c4ee123 100644 --- a/crates/evm/src/evm.rs +++ b/crates/evm/src/evm.rs @@ -113,6 +113,21 @@ impl MorphEvm { pub fn cached_l1_data_fee(&self) -> alloy_primitives::U256 { self.inner.cached_l1_data_fee() } + + /// Runs only the handler's pre-execution validation and fee-deduction phase + /// (including call-mode alt-token `balanceOf` and `transfer`), without executing + /// the main transaction body. + pub fn validate_only( + &mut self, + tx: MorphTxEnv, + ) -> Result<(), EVMError> { + use alloy_evm::revm::{context::ContextSetters, handler::Handler}; + + self.inner.inner.ctx.set_tx(tx); + morph_revm::handler::MorphEvmHandler::new() + .validate(&mut self.inner) + .map(|_| ()) + } } impl Deref for MorphEvm diff --git a/crates/node/src/add_ons.rs b/crates/node/src/add_ons.rs index b3446bfe..ce99df16 100644 --- a/crates/node/src/add_ons.rs +++ b/crates/node/src/add_ons.rs @@ -61,6 +61,9 @@ pub struct MorphAddOns< /// Held as one unit because the limit is only ever enforced by the RPC that this storage /// installs; there is no way to configure one without the other. proof_history: Option<(MorphProofsStorage>, usize)>, + /// Shared cache of validated in-memory `tree_state` headers populated by the engine tree + /// validator and read by `RealMorphL2EngineApi`. + tree_headers: Arc, } impl MorphAddOns, MorphEthApiBuilder> @@ -73,16 +76,18 @@ where /// Creates a new [`MorphAddOns`] with default configuration. pub fn new() -> Self { let pvb = MorphEngineValidatorBuilder::default(); + let tree_headers = Arc::new(morph_payload_types::TreeHeaderCache::new()); Self { inner: RpcAddOns::new( MorphEthApiBuilder::default(), pvb.clone(), NoopEngineApiBuilder::default(), - MorphTreeEngineValidatorBuilder::new(pvb), + MorphTreeEngineValidatorBuilder::new(pvb).with_tree_headers(tree_headers.clone()), Identity::default(), Identity::default(), ), proof_history: None, + tree_headers, } } @@ -201,6 +206,7 @@ where let morph_rpc_ctx = MorphRpc::new(reference_index_handle, provider.clone()); let reference_rpc_handler = MorphRpcHandler::new(morph_rpc_ctx); let proof_history = self.proof_history; + let tree_headers = self.tree_headers; // Use launch_add_ons_with to register custom Engine API and eth_config self.inner @@ -286,7 +292,8 @@ where chain_spec, beacon_engine_handle, block_tag_tracker, - ); + ) + .with_tree_headers(tree_headers); // Create the RPC handler let handler = morph_engine_api::MorphL2EngineRpcHandler::new(engine_api); diff --git a/crates/node/src/test_utils.rs b/crates/node/src/test_utils.rs index 8874e847..cab7d580 100644 --- a/crates/node/src/test_utils.rs +++ b/crates/node/src/test_utils.rs @@ -282,6 +282,36 @@ impl TestNodeBuilder { self } + /// Override a storage slot for an account in the test genesis. + pub fn with_account_storage(mut self, address: Address, slot: B256, value: B256) -> Self { + let alloc = self + .genesis_json + .get_mut("alloc") + .and_then(serde_json::Value::as_object_mut) + .expect("test genesis alloc must be an object"); + let address = address.to_string().to_ascii_lowercase(); + let entry = alloc + .entry(address) + .or_insert_with(|| serde_json::json!({ "balance": "0x0" })); + let entry = entry + .as_object_mut() + .expect("test genesis account entry must be an object"); + let storage = entry + .entry("storage".to_string()) + .or_insert_with(|| serde_json::json!({})) + .as_object_mut() + .expect("test genesis account storage must be an object"); + storage.insert(slot.to_string(), serde_json::json!(value.to_string())); + self + } + + /// Override `config.morph.maxTxPayloadBytesPerBlock` in the test genesis. + pub fn with_genesis_max_tx_payload_bytes(mut self, max_bytes: u64) -> Self { + self.genesis_json["config"]["morph"]["maxTxPayloadBytesPerBlock"] = + serde_json::json!(max_bytes); + self + } + /// Set the number of nodes to start. /// /// When `num_nodes > 1`, all nodes are interconnected via a simulated P2P network. diff --git a/crates/node/src/validator.rs b/crates/node/src/validator.rs index 5a864cbd..1f031d07 100644 --- a/crates/node/src/validator.rs +++ b/crates/node/src/validator.rs @@ -2,18 +2,24 @@ use crate::MorphNode; use alloy_consensus::BlockHeader; -use alloy_primitives::{B256, keccak256}; +use alloy_primitives::B256; +#[cfg(test)] +use alloy_primitives::keccak256; use morph_chainspec::{ L2_MESSAGE_QUEUE_ADDRESS, L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT, MorphChainSpec, MorphHardforks, }; -use morph_consensus::MorphConsensusError; -use morph_payload_types::{MorphExecutionData, MorphPayloadTypes}; -use morph_primitives::{MorphHeader, MorphPrimitives, MorphTxEnvelope}; +use morph_consensus::{MorphConsensus, MorphConsensusError}; +use morph_payload_types::{ + MorphExecutionData, MorphPayloadTypes, MorphPayloadValidationMode, TreeHeaderCache, +}; +use morph_primitives::{ + Block, BlockBody, MorphHeader, MorphPrimitives, MorphReceipt, MorphTxEnvelope, +}; use parking_lot::Mutex; use reth_chain_state::ExecutedBlock; use reth_chainspec::EthChainSpec; -use reth_consensus::{Consensus, FullConsensus, HeaderValidator}; +use reth_consensus::{Consensus, FullConsensus, HeaderValidator, ReceiptRootBloom}; use reth_engine_tree::tree::payload_validator::TreeCtx; use reth_engine_tree::tree::{ BasicEngineValidator, CacheWaitDurations, EngineApiTreeState, EngineValidator, @@ -26,7 +32,11 @@ use reth_engine_tree::tree::{ }, }; use reth_errors::{ConsensusError, ProviderError, ProviderResult}; -use reth_evm::{ConfigureEvm, revm::context::Block as _}; +use reth_evm::{ + ConfigureEvm, + block::BlockExecutionResult, + revm::{context::Block as _, database::BundleState}, +}; use reth_node_api::{ AddOnsContext, FullNodeComponents, InvalidPayloadAttributesError, NewPayloadError, NodeTypes, PayloadAttributes, PayloadTypes, PayloadValidator, @@ -36,7 +46,7 @@ use reth_node_builder::{ rpc::{EngineValidatorBuilder, PayloadValidatorBuilder}, }; use reth_payload_primitives::BuiltPayloadExecutedBlock; -use reth_primitives_traits::{RecoveredBlock, SealedBlock}; +use reth_primitives_traits::{RecoveredBlock, SealedBlock, SealedHeader}; use reth_provider::{ BlockExecutionOutput, BlockNumReader, BlockReader, ChainSpecProvider, DatabaseProviderFactory, PruneCheckpointReader, StageCheckpointReader, StateProviderFactory, StateReader, @@ -79,15 +89,24 @@ where #[derive(Debug, Clone)] pub struct MorphTreeEngineValidatorBuilder { payload_validator_builder: PVB, + tree_headers: Arc, } impl MorphTreeEngineValidatorBuilder { /// Creates a new instance with the given payload validator builder. - pub const fn new(payload_validator_builder: PVB) -> Self { + pub fn new(payload_validator_builder: PVB) -> Self { Self { payload_validator_builder, + tree_headers: Arc::new(TreeHeaderCache::new()), } } + + /// Attaches a shared [`TreeHeaderCache`] so the custom Morph L2 Engine API can + /// resolve unpersisted in-memory `tree_state` headers. + pub fn with_tree_headers(mut self, tree_headers: Arc) -> Self { + self.tree_headers = tree_headers; + self + } } impl Default for MorphTreeEngineValidatorBuilder @@ -107,7 +126,7 @@ where <::Payload as PayloadTypes>::ExecutionData, >, >, - Node::Provider: ChainSpecProvider, + Node::Provider: ChainSpecProvider + StateProviderFactory, PVB: PayloadValidatorBuilder, { type EngineValidator = MorphTreeEngineValidator; @@ -129,8 +148,10 @@ where let post_execution_validator = validator.clone(); let provider = ctx.node.provider().clone(); - let consensus: Arc> = - Arc::new(ctx.node.consensus().clone()); + let engine_consensus = Arc::new(MorphEngineConsensus::new(MorphConsensus::new( + chain_spec.clone(), + ))); + let consensus: Arc> = engine_consensus.clone(); let state_root_strategy: Arc< dyn StateRootStrategy, > = Arc::new(MorphStateRootStrategy::new(chain_spec.clone())); @@ -138,7 +159,7 @@ where let txpool_prewarming = tree_config.txpool_prewarming(); let mut validator = BasicEngineValidator::new( provider.clone(), - consensus.clone(), + consensus, ctx.node.evm_config().clone(), validator, tree_config, @@ -157,8 +178,9 @@ where validator, provider, chain_spec, - consensus, + engine_consensus, post_execution_validator, + self.tree_headers, )) } } @@ -224,6 +246,143 @@ fn strict_morph_tree_config(tree_config: reth_node_api::TreeConfig) -> reth_node tree_config.with_skip_state_root(false) } +#[derive(Debug, Default)] +struct ValidationModeCache { + entries: HashMap, + order: VecDeque, +} + +/// Engine-tree consensus adapter that applies [`MorphPayloadValidationMode`] exemptions +/// per block hash when `BasicEngineValidator` validates locally built or L1-derived safe +/// payloads, while defaulting to full [`MorphConsensus`] validation for all untrusted blocks. +#[derive(Debug)] +struct MorphEngineConsensus { + inner: MorphConsensus, + modes: Mutex, +} + +impl MorphEngineConsensus { + const MAX_MODES: usize = 128; + + fn new(inner: MorphConsensus) -> Self { + Self { + inner, + modes: Mutex::new(ValidationModeCache::default()), + } + } + + const fn inner(&self) -> &MorphConsensus { + &self.inner + } + + fn set_mode(&self, block_hash: B256, mode: MorphPayloadValidationMode) { + let mut cache = self.modes.lock(); + if mode == MorphPayloadValidationMode::Full { + if cache.entries.remove(&block_hash).is_some() { + cache.order.retain(|hash| *hash != block_hash); + } + return; + } + let is_new = cache.entries.insert(block_hash, mode).is_none(); + if is_new { + cache.order.push_back(block_hash); + while cache.entries.len() > Self::MAX_MODES { + let Some(evicted) = cache.order.pop_front() else { + break; + }; + cache.entries.remove(&evicted); + } + } + } + + fn mode_for(&self, block_hash: B256) -> MorphPayloadValidationMode { + self.modes + .lock() + .entries + .get(&block_hash) + .copied() + .unwrap_or(MorphPayloadValidationMode::Full) + } +} + +impl HeaderValidator for MorphEngineConsensus { + fn validate_header(&self, header: &SealedHeader) -> Result<(), ConsensusError> { + match self.mode_for(header.hash()) { + MorphPayloadValidationMode::Full => self.inner.validate_header(header), + MorphPayloadValidationMode::LocallyBuilt | MorphPayloadValidationMode::Safe => { + self.inner.validate_header_structural(header) + } + } + } + + fn validate_header_against_parent( + &self, + header: &SealedHeader, + parent: &SealedHeader, + ) -> Result<(), ConsensusError> { + match self.mode_for(header.hash()) { + MorphPayloadValidationMode::Full => { + self.inner.validate_header_against_parent(header, parent) + } + MorphPayloadValidationMode::LocallyBuilt => self + .inner + .validate_header_against_parent_locally_built(header, parent), + MorphPayloadValidationMode::Safe => self + .inner + .validate_header_against_parent_structural(header, parent), + } + } +} + +impl Consensus for MorphEngineConsensus { + fn validate_body_against_header( + &self, + body: &BlockBody, + header: &SealedHeader, + ) -> Result<(), ConsensusError> { + self.inner.validate_body_against_header(body, header) + } + + fn validate_block_pre_execution( + &self, + block: &SealedBlock, + ) -> Result<(), ConsensusError> { + match self.mode_for(block.hash()) { + MorphPayloadValidationMode::Full => self.inner.validate_block_pre_execution(block), + MorphPayloadValidationMode::LocallyBuilt | MorphPayloadValidationMode::Safe => self + .inner + .validate_block_pre_execution_without_da_limit(block), + } + } + + fn is_transient_error(&self, error: &ConsensusError) -> bool { + self.inner.is_transient_error(error) + } +} + +impl FullConsensus for MorphEngineConsensus { + fn validate_block_post_execution( + &self, + block: &RecoveredBlock, + result: &BlockExecutionResult, + receipt_root_bloom: Option, + block_access_list_hash: Option, + ) -> Result<(), ConsensusError> { + self.inner.validate_block_post_execution( + block, + result, + receipt_root_bloom, + block_access_list_hash, + ) + } +} + +#[derive(Debug, Default)] +struct KnownWithdrawTrieRootCache { + entries: HashMap, + order: VecDeque, +} + /// Upstream engine validator plus Morph-specific validation hooks. /// /// State execution, caching and trie maintenance remain entirely upstream. This @@ -241,36 +400,163 @@ where inner: BasicEngineValidator, provider: P, chain_spec: Arc, - consensus: Arc>, + engine_consensus: Arc, post_execution_validator: MorphEngineValidator, + tree_headers: Arc, + known_withdraw_trie_roots: Mutex, } impl MorphTreeEngineValidator where Evm: ConfigureEvm, { - const fn new( + const MAX_KNOWN_WITHDRAW_TRIE_ROOTS: usize = 8192; + + fn new( inner: BasicEngineValidator, provider: P, chain_spec: Arc, - consensus: Arc>, + engine_consensus: Arc, post_execution_validator: MorphEngineValidator, + tree_headers: Arc, ) -> Self { Self { inner, provider, chain_spec, - consensus, + engine_consensus, post_execution_validator, + tree_headers, + known_withdraw_trie_roots: Mutex::new(KnownWithdrawTrieRootCache::default()), } } + + fn record_known_withdraw_trie_root(&self, block_hash: B256, root: B256) { + let mut cache = self.known_withdraw_trie_roots.lock(); + let is_new = cache.entries.insert(block_hash, root).is_none(); + if is_new { + cache.order.push_back(block_hash); + while cache.entries.len() > Self::MAX_KNOWN_WITHDRAW_TRIE_ROOTS { + let Some(evicted) = cache.order.pop_front() else { + break; + }; + cache.entries.remove(&evicted); + } + } + } + + fn get_known_withdraw_trie_root(&self, block_hash: B256) -> Option { + self.known_withdraw_trie_roots + .lock() + .entries + .get(&block_hash) + .copied() + } + + fn updated_withdraw_trie_root_from_bundle_state(bundle_state: &BundleState) -> Option { + bundle_state + .account(&L2_MESSAGE_QUEUE_ADDRESS) + .and_then(|account| { + account + .storage + .get(&L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT) + .map(|slot| B256::from(slot.present_value())) + }) + } } impl MorphTreeEngineValidator where Evm: ConfigureEvm, - P: BlockReader
, + P: BlockReader
+ StateProviderFactory, { + fn lookup_sealed_header( + &self, + hash: B256, + ) -> ProviderResult>> { + if let Some(header) = self.tree_headers.get(&hash) { + return Ok(Some(header)); + } + self.provider.sealed_header_by_hash(hash) + } + + fn resolve_post_block_withdraw_trie_root( + &self, + parent_hash: B256, + bundle_state: &BundleState, + ) -> ProviderResult { + if let Some(updated) = Self::updated_withdraw_trie_root_from_bundle_state(bundle_state) { + return Ok(updated); + } + if let Some(parent_root) = self.get_known_withdraw_trie_root(parent_hash) { + return Ok(parent_root); + } + let state = self.provider.state_by_block_hash(parent_hash)?; + let slot_val = state + .storage( + L2_MESSAGE_QUEUE_ADDRESS, + B256::from(L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT), + )? + .unwrap_or_default(); + Ok(B256::from(slot_val)) + } + + /// Validates `header.next_l1_msg_index` during `convert_payload_to_block` (which runs on + /// `AlreadySeen` hits for both `tree_state` and DB blocks) using both in-memory + /// `tree_headers` and `provider` to resolve the parent header. + fn validate_l1_msg_index_on_conversion( + &self, + block: &SealedBlock, + ) -> Result<(), NewPayloadError> { + let Some(parent) = self + .lookup_sealed_header(block.parent_hash()) + .map_err(|e| NewPayloadError::Other(Box::new(e)))? + else { + return Ok(()); + }; + + let mut expected = parent.next_l1_msg_index; + let mut first_l1_msg = true; + for tx in block.body().transactions() { + if !tx.is_l1_msg() { + break; + } + let Some(queue_index) = tx.queue_index() else { + return Ok(()); + }; + if first_l1_msg { + first_l1_msg = false; + if queue_index < parent.next_l1_msg_index { + return Ok(()); + } + } + expected = queue_index.checked_add(1).ok_or_else(|| { + NewPayloadError::Other(Box::new(MorphConsensusError::InvalidNextL1MessageIndex { + expected: u64::MAX, + actual: block.header().next_l1_msg_index, + })) + })?; + } + + let has_l1_msgs = !first_l1_msg; + let actual = block.header().next_l1_msg_index; + let is_jade = self + .chain_spec + .is_jade_active_at_timestamp(block.header().timestamp()); + let invalid = if is_jade { + actual != expected + } else { + has_l1_msgs && actual < expected + }; + if invalid { + return Err(NewPayloadError::Other(Box::new( + MorphConsensusError::InvalidNextL1MessageIndex { expected, actual }, + ))); + } + + Ok(()) + } + /// Enforces parent-aware L1 message queue invariants: /// /// 1. Across **all** hardforks (both pre-Jade and post-Jade), if the block contains @@ -343,7 +629,7 @@ where let parent_hash = block.parent_hash(); let parent = match ctx.state().tree_state().sealed_header_by_hash(&parent_hash) { Some(parent) => Some(parent), - None => self.provider.sealed_header_by_hash(parent_hash)?, + None => self.lookup_sealed_header(parent_hash)?, }; let Some(parent) = parent else { // The upstream validator reports the missing parent with the @@ -365,68 +651,69 @@ where .map_err(|kind| InsertBlockError::new(block.clone(), kind).into()) } - /// Runs lightweight structural consensus validation before admitting a locally built - /// block via `InsertExecutedBlock`, ensuring pre-inserted blocks obey the same - /// header, parent, L1 queue, MorphTx, and DA payload rules as imported blocks. + /// Runs structural consensus validation before admitting a locally built block via + /// `InsertExecutedBlock` (originating from either `assembleL2Block(V2)` or + /// `newSafeL2Block`), exempting wall-clock `TimestampIsInFuture`, `GasLimit` 1/1024 + /// bounds, `BaseFeeOverLimit`, and the local DA payload byte limit to match + /// morph-geth's `verified` and `NewSafeL2Block` (`safe = true`) paths. fn validate_pre_inserted_block( &self, block: &RecoveredBlock, ) -> ProviderResult<()> { + let consensus = self.engine_consensus.inner(); let sealed_header = block.sealed_header(); - self.consensus - .validate_header(sealed_header) + consensus + .validate_header_structural(sealed_header) .map_err(ProviderError::other)?; - if let Some(parent) = self.provider.sealed_header_by_hash(block.parent_hash())? { - self.consensus - .validate_header_against_parent(sealed_header, &parent) + if let Some(parent) = self.lookup_sealed_header(block.parent_hash())? { + consensus + .validate_header_against_parent_structural(sealed_header, &parent) .map_err(ProviderError::other)?; self.validate_l1_msg_index_against_parent(block.sealed_block(), parent.header()) .map_err(ProviderError::other)?; } - self.consensus - .validate_block_pre_execution(block.sealed_block()) + consensus + .validate_block_pre_execution_without_da_limit(block.sealed_block()) .map_err(ProviderError::other)?; Ok(()) } - fn validate_withdraw_trie_root( + fn verify_and_record_withdraw_trie_root( &self, + expectation: WithdrawTrieRootExpectation, output: reth_engine_tree::tree::ValidationOutput, ) -> reth_engine_tree::tree::ValidationOutcome { - let block = output.executed_block.recovered_block(); - if let Err(err) = self - .post_execution_validator - .validate_withdraw_trie_root_update(block.hash(), || { - output.executed_block.hashed_state() - }) - { - return Err(InsertBlockError::consensus_error( - err, - output.executed_block.sealed_block().clone(), + let sealed_block = output.executed_block.sealed_block(); + let block_hash = sealed_block.hash(); + let parent_hash = sealed_block.parent_hash(); + let actual = self + .resolve_post_block_withdraw_trie_root( + parent_hash, + &output.executed_block.execution_output.state, ) - .into()); - } - - Ok(output) - } + .map_err(|err| InsertBlockError::new(sealed_block.clone(), err.into()))?; - fn validate_withdraw_trie_root_direct( - expected_withdraw_trie_root: Option, - output: reth_engine_tree::tree::ValidationOutput, - ) -> reth_engine_tree::tree::ValidationOutcome { - let expectation = MorphEngineValidator::expectation_from_root(expected_withdraw_trie_root); - if let Err(err) = - MorphEngineValidator::validate_withdraw_trie_root_expectation(expectation, || { - output.executed_block.hashed_state() - }) + if let WithdrawTrieRootExpectation::Verify(expected) = expectation + && actual != expected { return Err(InsertBlockError::consensus_error( - err, - output.executed_block.sealed_block().clone(), + ConsensusError::other(MorphConsensusError::WithdrawTrieRootMismatch { + expected, + actual, + }), + sealed_block.clone(), ) .into()); } + self.record_known_withdraw_trie_root(block_hash, actual); + self.tree_headers.insert( + output + .executed_block + .recovered_block() + .sealed_header() + .clone(), + ); Ok(output) } } @@ -434,7 +721,7 @@ where impl EngineValidator for MorphTreeEngineValidator where - P: BlockReader
+ Send + Sync + 'static, + P: BlockReader
+ StateProviderFactory + Send + Sync + 'static, Evm: ConfigureEvm + 'static, BasicEngineValidator: EngineValidator, @@ -453,24 +740,54 @@ where mut payload: MorphExecutionData, ) -> Result, NewPayloadError> { let block_hash = payload.block.hash(); - // Avoid leaking expectations into the cache when the block is already known - // or no non-zero cross-check root was supplied. - let is_zero_root = payload - .expected_withdraw_trie_root - .is_some_and(|root| root == B256::ZERO); - if is_zero_root { - self.post_execution_validator - .take_withdraw_trie_root_expectation(block_hash); - payload.expected_withdraw_trie_root = None; - } else if payload.expected_withdraw_trie_root.is_some() - && self - .provider - .sealed_header_by_hash(block_hash) - .ok() - .flatten() - .is_some() - { - payload.expected_withdraw_trie_root = None; + self.validate_l1_msg_index_on_conversion(payload.block.as_ref())?; + + match payload.expected_withdraw_trie_root { + None => {} + Some(root) if root.is_zero() => { + self.post_execution_validator + .take_withdraw_trie_root_expectation(block_hash); + payload.expected_withdraw_trie_root = None; + } + Some(expected) => { + if let Some(actual) = self.get_known_withdraw_trie_root(block_hash) { + self.post_execution_validator + .take_withdraw_trie_root_expectation(block_hash); + payload.expected_withdraw_trie_root = None; + if actual != expected { + return Err(NewPayloadError::Other(Box::new( + MorphConsensusError::WithdrawTrieRootMismatch { expected, actual }, + ))); + } + } else if self + .provider + .sealed_header_by_hash(block_hash) + .map_err(|e| NewPayloadError::Other(Box::new(e)))? + .is_some() + { + let state = self + .provider + .state_by_block_hash(block_hash) + .map_err(|e| NewPayloadError::Other(Box::new(e)))?; + let slot_val = state + .storage( + L2_MESSAGE_QUEUE_ADDRESS, + B256::from(L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT), + ) + .map_err(|e| NewPayloadError::Other(Box::new(e)))? + .unwrap_or_default(); + let actual = B256::from(slot_val); + self.record_known_withdraw_trie_root(block_hash, actual); + self.post_execution_validator + .take_withdraw_trie_root_expectation(block_hash); + payload.expected_withdraw_trie_root = None; + if actual != expected { + return Err(NewPayloadError::Other(Box::new( + MorphConsensusError::WithdrawTrieRootMismatch { expected, actual }, + ))); + } + } + } } self.inner.convert_payload_to_block(payload) } @@ -489,9 +806,12 @@ where .take_withdraw_trie_root_expectation(block_hash); self.validate_next_l1_msg_index_for_block(payload.block.as_ref(), &ctx)?; + self.engine_consensus + .set_mode(block_hash, payload.validation_mode); let output = self.inner.validate_payload(payload, ctx)?; - Self::validate_withdraw_trie_root_direct(expected_withdraw_trie_root, output) + let expectation = MorphEngineValidator::expectation_from_root(expected_withdraw_trie_root); + self.verify_and_record_withdraw_trie_root(expectation, output) } fn validate_block( @@ -500,6 +820,8 @@ where ctx: TreeCtx<'_, MorphPrimitives>, ) -> reth_engine_tree::tree::ValidationOutcome { let block_hash = block.hash(); + self.engine_consensus + .set_mode(block_hash, MorphPayloadValidationMode::Full); let l1_validation = self.validate_next_l1_msg_index_for_block(&block, &ctx); self.post_execution_validator .clear_withdraw_trie_root_expectation_on_error(block_hash, l1_validation)?; @@ -508,7 +830,11 @@ where let output = self .post_execution_validator .clear_withdraw_trie_root_expectation_on_error(block_hash, validation)?; - self.validate_withdraw_trie_root(output) + let expectation = self + .post_execution_validator + .take_withdraw_trie_root_expectation(block_hash) + .unwrap_or(WithdrawTrieRootExpectation::SkipValidation); + self.verify_and_record_withdraw_trie_root(expectation, output) } fn on_inserted_executed_block( @@ -516,10 +842,22 @@ where block: BuiltPayloadExecutedBlock, ) -> ProviderResult> { self.validate_pre_inserted_block(block.recovered_block.as_ref())?; - self.inner.on_inserted_executed_block(block) + if let Ok(actual) = self.resolve_post_block_withdraw_trie_root( + block.recovered_block.parent_hash(), + &block.execution_output.state, + ) { + self.record_known_withdraw_trie_root(block.recovered_block.hash(), actual); + } + let executed = self.inner.on_inserted_executed_block(block)?; + self.tree_headers + .insert(executed.recovered_block().sealed_header().clone()); + Ok(executed) } fn on_canonical_head_changed(&self, hash: B256, state: &EngineApiTreeState) { + if let Some(header) = state.tree_state().sealed_header_by_hash(&hash) { + self.tree_headers.insert(header); + } self.inner.on_canonical_head_changed(hash, state); } @@ -735,6 +1073,7 @@ impl MorphEngineValidator { result } + #[cfg(test)] fn updated_withdraw_trie_root_from_sorted_hashed_state( state_updates: &reth_trie::HashedPostStateSorted, ) -> Option { @@ -753,6 +1092,7 @@ impl MorphEngineValidator { }) } + #[cfg(test)] fn validate_withdraw_trie_root_expectation( expectation: WithdrawTrieRootExpectation, state_updates: impl FnOnce() -> Arc, @@ -777,6 +1117,7 @@ impl MorphEngineValidator { Ok(()) } + #[cfg(test)] fn validate_withdraw_trie_root_update( &self, block_hash: B256, diff --git a/crates/node/tests/it/engine.rs b/crates/node/tests/it/engine.rs index 981d32d4..a19887f8 100644 --- a/crates/node/tests/it/engine.rs +++ b/crates/node/tests/it/engine.rs @@ -1511,3 +1511,315 @@ async fn new_safe_l2_block_rejects_v2_morph_tx_before_celadon() -> eyre::Result< Ok(()) } + +/// `engine_newSafeL2Block` must exempt `VerifyHeader` rules (`TimestampIsInFuture`, +/// `TimestampIsInPast`, 1/1024 `GasLimit` bound, and `BaseFeeOverLimit`) and the local +/// per-block DA byte cap (`max_tx_payload_bytes_per_block`) across empty, non-empty, and +/// derivation-reorg blocks, matching morph-geth's `NewSafeL2Block` (`safe = true`). +#[tokio::test(flavor = "multi_thread")] +async fn new_safe_l2_block_exempts_header_bounds_and_da_size_limit() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + // Set a tiny 128-byte consensus payload cap so any 256-byte L2 calldata tx would fail + // `MorphConsensus::validate_block_pre_execution` unless `Safe` mode exempts it. + let (mut nodes, wallet) = TestNodeBuilder::new() + .with_genesis_max_tx_payload_bytes(128) + .build() + .await?; + let node = nodes.pop().unwrap(); + let client = node.auth_server_handle().http_client(); + + let genesis = canonical_snapshot(&node)?; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + + // 1. Empty safe block (skips `InsertExecutedBlock`, goes through `new_payload -> validate_payload`): + // - timestamp 120s in the future, + // - gas_limit = 60_000_000 (2x genesis 30_000_000, > 1/1024 bound), + // - base_fee = 15 Gwei (> 10 Gwei `MORPH_MAXIMUM_BASE_FEE`). + let high_base_fee = 15_000_000_000u128; + let safe_block1 = SafeL2Data { + number: 1, + gas_limit: 60_000_000, + base_fee_per_gas: Some(high_base_fee), + timestamp: now + 120, + transactions: vec![], + parent_hash: Some(genesis.hash), + }; + let h1: MorphHeader = client + .request("engine_newSafeL2Block", (safe_block1,)) + .await?; + let h1_hash = h1.hash_slow(); + assert_eq!(canonical_snapshot(&node)?.hash, h1_hash); + assert_eq!(canonical_snapshot(&node)?.safe_hash, Some(h1_hash)); + + // 2. Non-empty safe block (goes through `on_inserted_executed_block`) with oversized L2 calldata + // (> 128-byte genesis DA limit), another 2x gas_limit jump, high base_fee, and future timestamp. + let oversized_tx0 = MorphTxBuilder::new(wallet.chain_id, wallet.inner.clone(), 0) + .with_v1_eth_fee() + .with_to(Address::with_last_byte(0x42)) + .with_data(vec![0xab; 256]) + .with_fees(25_000_000_000, 1_000_000_000) + .with_gas_limit(100_000) + .build_signed()?; + let safe_block2 = SafeL2Data { + number: 2, + gas_limit: 120_000_000, + base_fee_per_gas: Some(high_base_fee), + timestamp: now + 240, + transactions: vec![oversized_tx0.clone()], + parent_hash: Some(h1_hash), + }; + let h2: MorphHeader = client + .request("engine_newSafeL2Block", (safe_block2,)) + .await?; + assert_eq!(canonical_snapshot(&node)?.hash, h2.hash_slow()); + + // 3. Safe derivation reorg at `number <= canonical_head` (skips `InsertExecutedBlock` even + // though non-empty!) with `timestamp < parent.timestamp`, sharp gas_limit drop, and + // oversized L2 payload. + let safe_block2_reorg = SafeL2Data { + number: 2, + gas_limit: 20_000_000, + base_fee_per_gas: Some(high_base_fee), + timestamp: now + 115, + transactions: vec![oversized_tx0], + parent_hash: Some(h1_hash), + }; + let h2_reorg: MorphHeader = client + .request("engine_newSafeL2Block", (safe_block2_reorg,)) + .await?; + let h2_reorg_hash = h2_reorg.hash_slow(); + assert_ne!(h2_reorg_hash, h2.hash_slow()); + assert_eq!(canonical_snapshot(&node)?.hash, h2_reorg_hash); + assert_eq!(canonical_snapshot(&node)?.safe_hash, Some(h2_reorg_hash)); + + Ok(()) +} + +/// Verifies both fixes to `validate_next_l1_message_index`: +/// 1. Pre-Jade blocks with NO L1 messages and `next_l1_message_index < parent.next_l1_msg_index` +/// are accepted (live and `AlreadySeen`), while Pre-Jade blocks WITH L1 messages still reject +/// `next_l1_message_index < last_queue_index + 1`. +/// 2. Unpersisted in-memory `tree_state` parents (`provider.sealed_header_by_hash(parent) == None`) +/// are resolved via `TreeHeaderCache` so tampered `next_l1_message_index` on an `AlreadySeen` +/// child is rejected. +#[tokio::test(flavor = "multi_thread")] +async fn validate_next_l1_msg_index_pre_jade_empty_l1_and_unpersisted_tree_parent() +-> eyre::Result<()> { + reth_tracing::init_test_tracing(); + use reth_provider::HeaderProvider; + + // --- Part 1: Pre-Jade empty-L1-message block with decreased `next_l1_message_index` --- + let (mut pre_jade_nodes, _wallet) = TestNodeBuilder::new() + .with_schedule(HardforkSchedule::PreJade) + .build() + .await?; + let pre_jade = pre_jade_nodes.pop().unwrap(); + let pre_client = pre_jade.auth_server_handle().http_client(); + + let genesis = canonical_snapshot(&pre_jade)?; + let b1 = assemble_l2_block_v2( + &pre_jade, + AssembleL2BlockV2Params { + parent_hash: genesis.hash, + transactions: L1MessageBuilder::build_sequential(0, 2), + timestamp: Some(1), + }, + ) + .await?; + assert_eq!(b1.next_l1_message_index, 2); + import_l2_block(&pre_jade, b1.clone()).await?; + + // Build Block 2 with NO L1 messages, then set `next_l1_message_index = 0` (< parent's 2). + let mut b2_no_l1 = assemble_l2_block_v2( + &pre_jade, + AssembleL2BlockV2Params { + parent_hash: b1.hash, + transactions: vec![], + timestamp: Some(2), + }, + ) + .await?; + b2_no_l1.next_l1_message_index = 0; + + let v_res: GenericResponse = pre_client + .request("engine_validateL2Block", (b2_no_l1.clone(),)) + .await?; + assert!( + v_res.success, + "pre-Jade block without L1 messages must allow next_l1_message_index < parent" + ); + // AlreadySeen re-validation of the same Pre-Jade block (before FCU advances head) must also succeed. + let v_seen: GenericResponse = pre_client + .request("engine_validateL2Block", (b2_no_l1.clone(),)) + .await?; + assert!(v_seen.success); + + // Pre-Jade block on `b1` WITH L1 messages `[2, 3]` (`expected >= 4`) and `actual = 1` MUST + // fail both `validateL2Block` and `newL2BlockV2`. + let mut b2_with_l1 = assemble_l2_block_v2( + &pre_jade, + AssembleL2BlockV2Params { + parent_hash: b1.hash, + transactions: L1MessageBuilder::build_sequential(2, 2), + timestamp: Some(3), + }, + ) + .await?; + b2_with_l1.next_l1_message_index = 1; + let bad_with_l1: GenericResponse = pre_client + .request("engine_validateL2Block", (b2_with_l1.clone(),)) + .await?; + assert!(!bad_with_l1.success); + assert!(import_l2_block(&pre_jade, b2_with_l1).await.is_err()); + + let imported_b2 = import_l2_block(&pre_jade, b2_no_l1).await?; + assert_eq!(imported_b2.next_l1_msg_index, 0); + + // --- Part 2: Post-Jade unpersisted `tree_state` parent lookup via `TreeHeaderCache` --- + let (mut nodes, wallet) = TestNodeBuilder::new().with_num_nodes(2).build().await?; + let follower = nodes.pop().expect("two nodes requested"); + let sequencer = nodes.pop().expect("two nodes requested"); + + let seq_genesis = canonical_snapshot(&sequencer)?; + // Advance `follower` onto canonical chain `Genesis -> a1 -> a2` so side-branch `parent_p` + // (height 1) will stay non-canonical in `tree_state` (`provider.sealed_header_by_hash == None`). + let a1 = assemble_l2_block_v2( + &follower, + AssembleL2BlockV2Params { + parent_hash: seq_genesis.hash, + transactions: vec![], + timestamp: Some(10), + }, + ) + .await?; + import_l2_block(&follower, a1.clone()).await?; + let a2 = assemble_l2_block_v2( + &follower, + AssembleL2BlockV2Params { + parent_hash: a1.hash, + transactions: vec![], + timestamp: Some(11), + }, + ) + .await?; + import_l2_block(&follower, a2).await?; + + // Build side branch `Genesis -> parent_p (L1 msgs [0, 1]) -> child_c (tx0, non-empty)` on `sequencer`. + let parent_p = assemble_l2_block_v2( + &sequencer, + AssembleL2BlockV2Params { + parent_hash: seq_genesis.hash, + transactions: L1MessageBuilder::build_sequential(0, 2), + timestamp: Some(1), + }, + ) + .await?; + assert_eq!(parent_p.next_l1_message_index, 2); + import_l2_block(&sequencer, parent_p.clone()).await?; + + let raw_tx0 = make_transfer_tx(wallet.chain_id, wallet.inner.clone(), 0).await; + let tx0_hash = sequencer.rpc.inject_tx(raw_tx0).await?; + wait_until_pooled(&sequencer, tx0_hash).await?; + let child_c = assemble_l2_block_v2( + &sequencer, + AssembleL2BlockV2Params { + parent_hash: parent_p.hash, + transactions: vec![], + timestamp: Some(2), + }, + ) + .await?; + assert_eq!(child_c.next_l1_message_index, 2); + + // Insert `parent_p` and `child_c` into `follower`'s `tree_state` via `beacon_engine_handle.new_payload` + // WITHOUT FCU, so `parent_p` resides ONLY in `tree_state` (not in `CanonicalInMemoryState` or MDBX) + // and `child_c` is armed as `AlreadySeen` in `follower`'s `tree_state`. + let decode_sealed = + |data: &ExecutableL2Data| -> eyre::Result { + use alloy_consensus::proofs; + use reth_primitives_traits::SealedBlock; + let txs = data + .transactions + .iter() + .map(|raw| { + let mut slice = raw.as_ref(); + Ok(morph_primitives::MorphTxEnvelope::decode_2718(&mut slice)?) + }) + .collect::>>()?; + let header = MorphHeader { + inner: alloy_consensus::Header { + parent_hash: data.parent_hash, + beneficiary: data.miner, + state_root: data.state_root, + transactions_root: proofs::calculate_transaction_root(&txs), + receipts_root: data.receipts_root, + logs_bloom: alloy_primitives::Bloom::from_slice(&data.logs_bloom), + number: data.number, + gas_limit: data.gas_limit, + gas_used: data.gas_used, + timestamp: data.timestamp, + base_fee_per_gas: data.base_fee_per_gas.map(|f| f as u64), + ..Default::default() + }, + next_l1_msg_index: data.next_l1_message_index, + }; + let sealed = SealedBlock::seal_slow(morph_primitives::Block::new( + header, + morph_primitives::BlockBody { + transactions: txs, + ommers: vec![], + withdrawals: None, + }, + )); + assert_eq!(sealed.hash(), data.hash); + Ok(MorphPayloadTypes::block_to_payload(sealed, None)) + }; + + let p_status = follower + .inner + .add_ons_handle + .beacon_engine_handle + .new_payload(decode_sealed(&parent_p)?) + .await?; + assert!(p_status.is_valid()); + assert!( + follower + .inner + .provider + .sealed_header_by_hash(parent_p.hash)? + .is_none(), + "precondition: parent_p must reside only in tree_state, not in provider/MDBX" + ); + + let c_status = follower + .inner + .add_ons_handle + .beacon_engine_handle + .new_payload(decode_sealed(&child_c)?) + .await?; + assert!(c_status.is_valid()); + + // `child_c` is now `AlreadySeen` in `follower`'s `tree_state`, and its parent `parent_p` + // is only in `tree_state` (`TreeHeaderCache`): tampering `next_l1_message_index` on + // `engine_newL2BlockV2` MUST fail! + let mut child_c_tampered = child_c.clone(); + child_c_tampered.next_l1_message_index = 99; + let err = import_l2_block(&follower, child_c_tampered) + .await + .expect_err( + "newL2BlockV2 must reject tampered next_l1_message_index with tree_state parent", + ) + .to_string(); + assert!(err.contains("invalid block.NextL1MsgIndex"), "got: {err}"); + + // Honest `child_c` reorgs `follower` onto `Genesis -> parent_p -> child_c` cleanly. + let imported_c = import_l2_block(&follower, child_c.clone()).await?; + assert_eq!(imported_c.hash_slow(), child_c.hash); + assert_eq!(canonical_snapshot(&follower)?.hash, child_c.hash); + + Ok(()) +} diff --git a/crates/node/tests/it/invalid_payload_recovery.rs b/crates/node/tests/it/invalid_payload_recovery.rs index a9082125..d37e459e 100644 --- a/crates/node/tests/it/invalid_payload_recovery.rs +++ b/crates/node/tests/it/invalid_payload_recovery.rs @@ -277,31 +277,36 @@ async fn tampered_next_l1_msg_index_rejected_when_block_already_seen() -> eyre:: Ok(()) } -/// M-H07: A locally built non-empty block that violates consensus (e.g., future timestamp) -/// must be rejected by `on_inserted_executed_block` so it is NOT pre-inserted into -/// `tree_state` and cannot subsequently bypass validation via `AlreadySeen`. +/// Locally assembled blocks bypass the 0-second wall-clock `TimestampIsInFuture` check on the +/// assembling sequencer (matching morph-geth's `AssembleL2Block -> NewL2Block` `verified` path, +/// including HA switchover where `parent.timestamp > now` causes `payload_timestamp` to raise +/// the child timestamp past local wall-clock), while external followers that did not assemble +/// the block still enforce `TimestampIsInFuture`. #[tokio::test(flavor = "multi_thread")] -async fn pre_inserted_consensus_invalid_block_is_rejected_and_not_cached() -> eyre::Result<()> { +async fn locally_assembled_future_timestamp_accepted_on_assembler_and_rejected_on_follower() +-> eyre::Result<()> { reth_tracing::init_test_tracing(); - let (mut nodes, wallet) = TestNodeBuilder::new().build().await?; - let node = nodes.pop().expect("one node requested"); + let (mut nodes, wallet) = TestNodeBuilder::new().with_num_nodes(2).build().await?; + let follower = nodes.pop().expect("two nodes requested"); + let sequencer = nodes.pop().expect("two nodes requested"); - let raw_tx = make_transfer_tx(wallet.chain_id, wallet.inner.clone(), wallet.inner_nonce).await; - let tx_hash = node.rpc.inject_tx(raw_tx).await?; - wait_until_pooled(&node, tx_hash).await?; + let raw_tx0 = make_transfer_tx(wallet.chain_id, wallet.inner.clone(), 0).await; + let tx0_hash = sequencer.rpc.inject_tx(raw_tx0).await?; + wait_until_pooled(&sequencer, tx0_hash).await?; - let before = canonical_snapshot(&node)?; - let future_timestamp = std::time::SystemTime::now() + let genesis = canonical_snapshot(&sequencer)?; + let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() - .as_secs() - + 3600; + .as_secs(); + let future_timestamp = now + 3600; + // 1. Sequencer locally assembles a non-empty block ahead of local wall clock. let future_block = assemble_l2_block_v2( - &node, + &sequencer, AssembleL2BlockV2Params { - parent_hash: before.hash, + parent_hash: genesis.hash, transactions: vec![], timestamp: Some(future_timestamp), }, @@ -313,29 +318,415 @@ async fn pre_inserted_consensus_invalid_block_is_rejected_and_not_cached() -> ey "precondition: block must be non-empty so InsertExecutedBlock is emitted" ); - // Give the async engine tree task ample time to process InsertExecutedBlock; - // `on_inserted_executed_block` must reject the future-timestamp header. - tokio::time::sleep(std::time::Duration::from_millis(500)).await; + // Wait for `on_inserted_executed_block` to pre-insert the locally assembled block. + let deadline = tokio::time::Instant::now() + LOCAL_POLL_BUDGET; + loop { + if sequencer + .inner + .provider + .pending_block_num_hash()? + .map(|p| p.hash) + == Some(future_block.hash) + { + break; + } + assert!( + tokio::time::Instant::now() < deadline, + "locally assembled non-empty block must be pre-inserted into tree_state" + ); + tokio::time::sleep(POLL_INTERVAL).await; + } + + // Follower did NOT assemble `future_block`: both validate and import must reject it as future. + let follower_client = follower.auth_server_handle().http_client(); + let follower_validation: GenericResponse = follower_client + .request("engine_validateL2Block", (future_block.clone(),)) + .await?; + assert!( + !follower_validation.success, + "follower must reject untrusted future-timestamp block in engine_validateL2Block" + ); + let follower_err = import_l2_block(&follower, future_block.clone()) + .await + .expect_err("follower must reject untrusted future-timestamp block on import") + .to_string(); + assert!( + follower_err.to_lowercase().contains("future"), + "expected future-timestamp consensus rejection on follower, got: {follower_err}" + ); assert_eq!( - node.inner.provider.pending_block_num_hash()?, - None, - "consensus-invalid future block must not be pre-inserted into tree_state" + canonical_snapshot(&follower)?, + genesis, + "follower canonical state must remain unchanged" ); - // Importing it must fail consensus validation rather than hitting AlreadySeen. - let err = import_l2_block(&node, future_block) + // Sequencer locally assembled `future_block`: validate and import must succeed. + let seq_client = sequencer.auth_server_handle().http_client(); + let seq_validation: GenericResponse = seq_client + .request("engine_validateL2Block", (future_block.clone(),)) + .await?; + assert!(seq_validation.success); + let imported1 = import_l2_block(&sequencer, future_block.clone()).await?; + assert_eq!(imported1.hash_slow(), future_block.hash); + + // 2. HA clock-behind-parent path: `parent.timestamp == now + 3600 > now`. + // `assemble_l2_block_v2` with `timestamp: Some(now)` raises timestamp to `now + 3600`. + // Build an EMPTY block so `InsertExecutedBlock` is skipped and `import_l2_block` + // exercises `new_payload -> validate_payload` under `LocallyBuilt`. + let empty_ha_block = assemble_l2_block_v2( + &sequencer, + AssembleL2BlockV2Params { + parent_hash: future_block.hash, + transactions: vec![], + timestamp: Some(now), + }, + ) + .await?; + assert!(empty_ha_block.transactions.is_empty()); + assert_eq!(empty_ha_block.timestamp, future_timestamp); + let imported2 = import_l2_block(&sequencer, empty_ha_block.clone()).await?; + assert_eq!(imported2.hash_slow(), empty_ha_block.hash); + + // 3. Reorg locally-built path (`number <= canonical_head`, where reth also skips + // `InsertExecutedBlock` even for non-empty blocks): rebuild height 2 on `future_block`. + let raw_tx1 = make_transfer_tx(wallet.chain_id, wallet.inner.clone(), 1).await; + let tx1_hash = sequencer.rpc.inject_tx(raw_tx1).await?; + wait_until_pooled(&sequencer, tx1_hash).await?; + + let reorg_ha_block = assemble_l2_block_v2( + &sequencer, + AssembleL2BlockV2Params { + parent_hash: future_block.hash, + transactions: vec![], + timestamp: Some(now), + }, + ) + .await?; + assert_eq!(reorg_ha_block.transactions.len(), 1); + assert_eq!(reorg_ha_block.timestamp, future_timestamp); + let imported2_reorg = import_l2_block(&sequencer, reorg_ha_block.clone()).await?; + assert_eq!(imported2_reorg.hash_slow(), reorg_ha_block.hash); + assert_eq!(canonical_snapshot(&sequencer)?.hash, reorg_ha_block.hash); + + Ok(()) +} + +/// Forged non-zero `withdraw_trie_root` must be rejected across ALL known-block paths: +/// 1. `AlreadySeen` in `tree_state` via `assembleL2BlockV2` pre-insertion (untouched zero slot), +/// 2. Live execution AND `AlreadySeen` in `tree_state` on a follower when an earlier block set a +/// non-zero `withdraw_trie_root` and the target block did NOT touch the slot in its own diff, +/// 3. DB-persisted `AlreadySeen` after advancing past the persistence threshold, +/// while `B256::ZERO` (skip optional check) and the true root continue to succeed without +/// poisoning `invalid_headers`. +#[tokio::test(flavor = "multi_thread")] +async fn forged_withdraw_trie_root_rejected_across_all_known_block_paths() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + use morph_node::test_utils::MorphTxBuilder; + + // 7-byte runtime on L2MessageQueue (`0x5300...0001`): `SSTORE(CALLDATALOAD(0), CALLDATALOAD(32))`. + let (mut nodes, wallet) = TestNodeBuilder::new() + .with_account_code( + morph_chainspec::L2_MESSAGE_QUEUE_ADDRESS, + "0x6020355f355500", + ) + .with_num_nodes(2) + .build() + .await?; + let follower = nodes.pop().expect("two nodes requested"); + let sequencer = nodes.pop().expect("two nodes requested"); + + let seq_client = sequencer.auth_server_handle().http_client(); + let fol_client = follower.auth_server_handle().http_client(); + + // --- Path 1: Pre-inserted `tree_state` block with untouched zero withdraw slot --- + let raw_tx0 = make_transfer_tx(wallet.chain_id, wallet.inner.clone(), 0).await; + let tx0_hash = sequencer.rpc.inject_tx(raw_tx0).await?; + wait_until_pooled(&sequencer, tx0_hash).await?; + + let genesis = canonical_snapshot(&sequencer)?; + let block1 = assemble_l2_block_v2( + &sequencer, + AssembleL2BlockV2Params { + parent_hash: genesis.hash, + transactions: vec![], + timestamp: Some(head_timestamp(&sequencer)? + 1), + }, + ) + .await?; + assert_eq!(block1.withdraw_trie_root, B256::ZERO); + + let deadline = tokio::time::Instant::now() + LOCAL_POLL_BUDGET; + loop { + if sequencer + .inner + .provider + .pending_block_num_hash()? + .map(|p| p.hash) + == Some(block1.hash) + { + break; + } + assert!(tokio::time::Instant::now() < deadline); + tokio::time::sleep(POLL_INTERVAL).await; + } + + let forged_root = B256::repeat_byte(0xde); + let mut block1_forged = block1.clone(); + block1_forged.withdraw_trie_root = forged_root; + + let res: GenericResponse = seq_client + .request("engine_validateL2Block", (block1_forged.clone(),)) + .await?; + assert!( + !res.success, + "pre-inserted block with forged non-zero withdraw_trie_root must fail validateL2Block" + ); + assert!( + seq_client + .request::<(), _>("engine_newL2Block", (block1_forged.clone(),)) + .await + .is_err(), + "pre-inserted block with forged non-zero withdraw_trie_root must fail newL2Block" + ); + assert!( + import_l2_block(&sequencer, block1_forged).await.is_err(), + "pre-inserted block with forged non-zero withdraw_trie_root must fail newL2BlockV2" + ); + + // Honest block1 (withdraw_trie_root == ZERO) must still validate and import on both nodes. + let ok_res: GenericResponse = seq_client + .request("engine_validateL2Block", (block1.clone(),)) + .await?; + assert!(ok_res.success); + import_l2_block(&sequencer, block1.clone()).await?; + import_l2_block(&follower, block1.clone()).await?; + + // --- Path 2: Block 2 updates withdraw slot to R1; Block 3 leaves slot untouched --- + let real_root = B256::repeat_byte(0xab); + let mut wtr_calldata = Vec::with_capacity(64); + wtr_calldata.extend_from_slice( + B256::from(morph_chainspec::L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT).as_slice(), + ); + wtr_calldata.extend_from_slice(real_root.as_slice()); + let set_wtr_tx = MorphTxBuilder::new(wallet.chain_id, wallet.inner.clone(), 1) + .with_v1_eth_fee() + .with_to(morph_chainspec::L2_MESSAGE_QUEUE_ADDRESS) + .with_data(wtr_calldata) + .with_gas_limit(100_000) + .build_signed()?; + let set_wtr_hash = sequencer.rpc.inject_tx(set_wtr_tx).await?; + wait_until_pooled(&sequencer, set_wtr_hash).await?; + + let block2 = assemble_l2_block_v2( + &sequencer, + AssembleL2BlockV2Params { + parent_hash: block1.hash, + transactions: vec![], + timestamp: Some(block1.timestamp + 1), + }, + ) + .await?; + assert_eq!( + block2.withdraw_trie_root, real_root, + "assembled block2 must reflect updated withdraw_trie_root slot" + ); + import_l2_block(&sequencer, block2.clone()).await?; + import_l2_block(&follower, block2.clone()).await?; + + // Block 3 is empty (does NOT write slot 0 in its BundleState), so post-Block-3 root is still `real_root`. + let block3 = assemble_l2_block_v2( + &sequencer, + AssembleL2BlockV2Params { + parent_hash: block2.hash, + transactions: vec![], + timestamp: Some(block2.timestamp + 1), + }, + ) + .await?; + assert!(block3.transactions.is_empty()); + assert_eq!(block3.withdraw_trie_root, real_root); + import_l2_block(&sequencer, block3.clone()).await?; + + // On `follower` (which did NOT assemble `block3`): + // 2a. Live execution with forged non-zero root when slot 0 was untouched in Block 3 must fail! + let mut block3_forged = block3.clone(); + block3_forged.withdraw_trie_root = B256::repeat_byte(0xee); + let live_bad: GenericResponse = fol_client + .request("engine_validateL2Block", (block3_forged.clone(),)) + .await?; + assert!( + !live_bad.success, + "live validateL2Block must reject forged withdraw_trie_root even when slot was untouched in block" + ); + + // 2b. Validate `block3` with ZERO root on `follower` so `block3` enters `follower`'s `tree_state`. + let mut block3_zero = block3.clone(); + block3_zero.withdraw_trie_root = B256::ZERO; + let live_zero: GenericResponse = fol_client + .request("engine_validateL2Block", (block3_zero,)) + .await?; + assert!(live_zero.success); + + // 2c. Now `block3` hits `AlreadySeen` in `follower`'s `tree_state`: forged root must STILL fail! + let seen_bad: GenericResponse = fol_client + .request("engine_validateL2Block", (block3_forged.clone(),)) + .await?; + assert!( + !seen_bad.success, + "AlreadySeen in tree_state must reject forged non-zero withdraw_trie_root" + ); + assert!( + import_l2_block(&follower, block3_forged).await.is_err(), + "AlreadySeen import must reject forged non-zero withdraw_trie_root" + ); + + // Honest `real_root` must still validate and import cleanly on `follower`. + let seen_good: GenericResponse = fol_client + .request("engine_validateL2Block", (block3.clone(),)) + .await?; + assert!(seen_good.success); + import_l2_block(&follower, block3.clone()).await?; + + // --- Path 3: Advance blocks so `block2` is persisted to MDBX and verify DB AlreadySeen --- + let mut parent_hash = block3.hash; + let mut ts = block3.timestamp; + for _ in 0..6 { + ts += 1; + let next_blk = assemble_l2_block_v2( + &sequencer, + AssembleL2BlockV2Params { + parent_hash, + transactions: vec![], + timestamp: Some(ts), + }, + ) + .await?; + import_l2_block(&sequencer, next_blk.clone()).await?; + import_l2_block(&follower, next_blk.clone()).await?; + parent_hash = next_blk.hash; + } + + let mut block2_forged = block2.clone(); + block2_forged.withdraw_trie_root = B256::repeat_byte(0x99); + let db_err = import_l2_block(&follower, block2_forged) .await - .expect_err("future-timestamp block must be rejected on import") + .expect_err("persisted block must reject forged non-zero withdraw_trie_root") .to_string(); assert!( - err.to_lowercase().contains("future"), - "expected future-timestamp consensus rejection, got: {err}" + db_err.contains("withdraw trie root mismatch"), + "expected withdraw trie root mismatch on persisted block, got: {db_err}" ); - assert_eq!( - canonical_snapshot(&node)?, - before, - "canonical state must remain unchanged after rejecting future block" + let db_good = import_l2_block(&follower, block2.clone()).await?; + assert_eq!(db_good.hash_slow(), block2.hash); + + // --- Path 4: Cold-MDBX lookup (`known_withdraw_trie_roots` cache empty!) --- + // On a freshly booted node, genesis is persisted in MDBX (`provider.sealed_header_by_hash` + // returns `Some`) while `known_withdraw_trie_roots` is completely empty, exercising the + // cold-DB `state_by_block_hash` fallback in `MorphTreeEngineValidator::convert_payload_to_block`. + let genesis_wtr = B256::repeat_byte(0x77); + let (mut cold_nodes, _) = TestNodeBuilder::new() + .with_account_storage( + morph_chainspec::L2_MESSAGE_QUEUE_ADDRESS, + B256::from(morph_chainspec::L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT), + genesis_wtr, + ) + .build() + .await?; + let cold_node = cold_nodes.pop().unwrap(); + let cold_genesis = std::sync::Arc::new(reth_primitives_traits::SealedBlock::seal_slow( + reth_provider::BlockReader::block_by_number(&cold_node.inner.provider, 0)? + .expect("genesis block in MDBX"), + )); + let forged_genesis_payload = + morph_payload_types::MorphExecutionData::with_expected_withdraw_trie_root( + cold_genesis.clone(), + B256::repeat_byte(0x88), + ); + let cold_bad_status = cold_node + .inner + .add_ons_handle + .beacon_engine_handle + .new_payload(forged_genesis_payload) + .await?; + assert!( + cold_bad_status.is_invalid(), + "cold-MDBX block with forged withdraw_trie_root must be rejected: {cold_bad_status:?}" ); + let honest_genesis_payload = + morph_payload_types::MorphExecutionData::with_expected_withdraw_trie_root( + cold_genesis, + genesis_wtr, + ); + let cold_ok_status = cold_node + .inner + .add_ons_handle + .beacon_engine_handle + .new_payload(honest_genesis_payload) + .await?; + assert!( + cold_ok_status.is_valid(), + "cold-MDBX block with matching withdraw_trie_root must succeed: {cold_ok_status:?}" + ); + + Ok(()) +} + +/// Structural consensus violations (such as non-empty `extra_data` or `gas_used > gas_limit`) +/// must still be rejected even when `MorphPayloadValidationMode::LocallyBuilt` or `Safe` is set. +#[tokio::test(flavor = "multi_thread")] +async fn locally_built_and_safe_modes_still_reject_structural_consensus_violations() +-> eyre::Result<()> { + reth_tracing::init_test_tracing(); + use morph_payload_types::{MorphPayloadTypes, MorphPayloadValidationMode}; + use reth_node_api::PayloadTypes; + use reth_primitives_traits::SealedBlock; + + let (mut nodes, _wallet) = TestNodeBuilder::new().build().await?; + let mut node = nodes.pop().expect("one node requested"); + + let base_payload = build_block_no_submit(&mut node, vec![]).await?; + for mode in [ + MorphPayloadValidationMode::LocallyBuilt, + MorphPayloadValidationMode::Safe, + ] { + let mut bad_extra = morph_primitives::Block::new( + base_payload.block().header().clone(), + base_payload.block().body().clone(), + ); + bad_extra.header.inner.extra_data = alloy_primitives::Bytes::from_static(b"invalid"); + let payload_extra = + MorphPayloadTypes::block_to_payload(SealedBlock::seal_slow(bad_extra), None) + .with_validation_mode(mode); + let status = node + .inner + .add_ons_handle + .beacon_engine_handle + .new_payload(payload_extra) + .await?; + assert!( + status.is_invalid(), + "non-empty extra_data must be rejected in {mode:?} mode: {status:?}" + ); + + let mut bad_gas = morph_primitives::Block::new( + base_payload.block().header().clone(), + base_payload.block().body().clone(), + ); + bad_gas.header.inner.gas_used = bad_gas.header.inner.gas_limit + 1; + let payload_gas = + MorphPayloadTypes::block_to_payload(SealedBlock::seal_slow(bad_gas), None) + .with_validation_mode(mode); + let status = node + .inner + .add_ons_handle + .beacon_engine_handle + .new_payload(payload_gas) + .await?; + assert!( + status.is_invalid(), + "gas_used > gas_limit must be rejected in {mode:?} mode: {status:?}" + ); + } Ok(()) } diff --git a/crates/node/tests/it/morph_tx.rs b/crates/node/tests/it/morph_tx.rs index d5456a1e..2e75a179 100644 --- a/crates/node/tests/it/morph_tx.rs +++ b/crates/node/tests/it/morph_tx.rs @@ -1626,3 +1626,245 @@ async fn morph_tx_v2_self_delegation_executes_delegate_code_in_same_tx() -> eyre Ok(()) } + +// ============================================================================= +// M-M12 regression tests: Call-mode alt-token fee pool eviction safety +// ============================================================================= + +/// Building a candidate block via `engine_assembleL2BlockV2` on an older non-canonical +/// ancestor (where a Call-mode token was NOT yet active) must NOT evict a `MorphTx` that +/// IS valid on the current canonical head. +#[tokio::test(flavor = "multi_thread")] +async fn assemble_on_non_canonical_parent_does_not_evict_canonical_valid_morph_tx() +-> eyre::Result<()> { + reth_tracing::init_test_tracing(); + use alloy_consensus::TxReceipt; + use morph_payload_types::AssembleL2BlockV2Params; + use reth_provider::ReceiptProvider; + use reth_transaction_pool::TransactionPool; + + let registry = alloy_primitives::address!("5300000000000000000000000000000000000021"); + // Token 1 `decimals | isActive` packed slot in `test-genesis.json`: + // `0x1200` = decimals 18, `isActive = false`; `0x1201` = decimals 18, `isActive = true`. + let active_slot: B256 = + "0x53bdca72fa8d2e145a1b3bd11cde5bd75428acd18eac3d6adf4e06e7e637706f".parse()?; + let inactive_word = B256::from(U256::from(0x1200u64)); + let active_word = B256::from(U256::from(0x1201u64)); + + // 7-byte runtime on L2TokenRegistry: `SSTORE(CALLDATALOAD(0), CALLDATALOAD(32))` (`6020355f355500`). + let (mut nodes, wallet) = TestNodeBuilder::new() + .with_account_code(registry, "0x6020355f355500") + .with_account_storage(registry, active_slot, inactive_word) + .build() + .await?; + let node = nodes.pop().unwrap(); + let genesis = super::helpers::canonical_snapshot(&node)?; + + // Block 1: activate `TEST_TOKEN_ID` on canonical chain. + let mut activate_calldata = Vec::with_capacity(64); + activate_calldata.extend_from_slice(active_slot.as_slice()); + activate_calldata.extend_from_slice(active_word.as_slice()); + let activate_tx = MorphTxBuilder::new(wallet.chain_id, wallet.inner.clone(), 0) + .with_v1_eth_fee() + .with_to(registry) + .with_data(activate_calldata) + .with_gas_limit(100_000) + .build_signed()?; + let activate_hash = node.rpc.inject_tx(activate_tx).await?; + super::helpers::wait_until_pooled(&node, activate_hash).await?; + let block1 = super::helpers::assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: genesis.hash, + transactions: vec![], + timestamp: Some(1), + }, + ) + .await?; + super::helpers::import_l2_block(&node, block1.clone()).await?; + super::helpers::wait_until_evicted(&node, activate_hash).await?; + + // Inject a valid Call-mode MorphTx (`fee_token_id = 1`) from account 1 on canonical Block 1. + let signer1 = wallet_at_index(1, wallet.chain_id); + let morph_tx = MorphTxBuilder::new(wallet.chain_id, signer1, 0) + .with_v0_token_fee(TEST_TOKEN_ID) + .with_to(Address::with_last_byte(0x77)) + .build_signed()?; + let morph_tx_hash = node.rpc.inject_tx(morph_tx).await?; + super::helpers::wait_until_pooled(&node, morph_tx_hash).await?; + + // Assemble a candidate block on Genesis (Block 0), where `TEST_TOKEN_ID` is inactive + // (`MorphInvalidTransaction::TokenNotActive(1)`). + let stale_branch = super::helpers::assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: genesis.hash, + transactions: vec![], + timestamp: Some(10), + }, + ) + .await?; + assert!( + stale_branch.transactions.is_empty(), + "MorphTx must be skipped on stale parent where token was inactive" + ); + assert!( + node.inner.pool.contains(&morph_tx_hash), + "non-canonical parent build must NOT evict canonical-valid MorphTx from global pool" + ); + + // Assembling & importing Block 2 on canonical Block 1 must include and execute the MorphTx cleanly. + let block2 = super::helpers::assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: block1.hash, + transactions: vec![], + timestamp: Some(2), + }, + ) + .await?; + assert_eq!(block2.transactions.len(), 1); + super::helpers::import_l2_block(&node, block2).await?; + super::helpers::wait_until_evicted(&node, morph_tx_hash).await?; + let receipt = node + .inner + .provider + .receipt_by_hash(morph_tx_hash)? + .expect("MorphTx receipt must exist"); + assert!(receipt.status()); + + Ok(()) +} + +/// An earlier transaction in the same block (either a supplied L1 message or a higher-priority +/// pool transaction from another sender) mutating Call-mode token state so `transfer` reverts +/// (`MorphInvalidTransaction::TokenTransferFailed`) must NOT evict a `MorphTx` that is valid on +/// the clean canonical parent; once that mutation IS committed to the canonical parent, the now +/// genuinely-broken `MorphTx` IS evicted on subsequent canonical builds. +#[tokio::test(flavor = "multi_thread")] +async fn in_block_token_mutation_does_not_evict_morph_tx_valid_on_clean_parent() -> eyre::Result<()> +{ + reth_tracing::init_test_tracing(); + use morph_node::test_utils::L1MessageBuilder; + use morph_payload_types::AssembleL2BlockV2Params; + use reth_transaction_pool::TransactionPool; + + let registry = alloy_primitives::address!("5300000000000000000000000000000000000021"); + let token_addr_slot: B256 = + "0x53bdca72fa8d2e145a1b3bd11cde5bd75428acd18eac3d6adf4e06e7e637706d".parse()?; + let broken_token = Address::with_last_byte(0x99); + let mut broken_token_word = [0u8; 32]; + broken_token_word[12..].copy_from_slice(broken_token.as_slice()); + + // `broken_token`: `balanceOf(address)` (`0x70a08231`) returns `U256::MAX` so balance checks + // pass, while `transfer(address,uint256)` reverts -> `TokenTransferFailed`. + let broken_token_runtime = "0x5f3560e01c6370a08231146011575f5ffd5b5f195f5260205ff3"; + + let (mut nodes, wallet) = TestNodeBuilder::new() + .with_account_code(registry, "0x6020355f355500") + .with_account_code(broken_token, broken_token_runtime) + .build() + .await?; + let node = nodes.pop().unwrap(); + let genesis = super::helpers::canonical_snapshot(&node)?; + + // Inject a valid Call-mode MorphTx (`fee_token_id = 1`) from account 1 (moderate priority fee). + let signer1 = wallet_at_index(1, wallet.chain_id); + let morph_tx = MorphTxBuilder::new(wallet.chain_id, signer1, 0) + .with_v0_token_fee(TEST_TOKEN_ID) + .with_to(Address::with_last_byte(0x77)) + .with_fees(5_000_000_000, 1_000_000_000) + .build_signed()?; + let morph_tx_hash = node.rpc.inject_tx(morph_tx).await?; + super::helpers::wait_until_pooled(&node, morph_tx_hash).await?; + + let mut point_to_broken_calldata = Vec::with_capacity(64); + point_to_broken_calldata.extend_from_slice(token_addr_slot.as_slice()); + point_to_broken_calldata.extend_from_slice(&broken_token_word); + + // 1. Supplied L1 message mutates `L2TokenRegistry` mid-block so `MorphTx` hits + // `TokenTransferFailed` in-block, while still valid on clean Genesis parent. + let l1_mutator = L1MessageBuilder::new(0) + .with_sender(Address::with_last_byte(0xaa)) + .with_target(registry) + .with_data(point_to_broken_calldata.clone()) + .with_gas_limit(100_000) + .build_encoded(); + let l1_candidate = super::helpers::assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: genesis.hash, + transactions: vec![l1_mutator], + timestamp: Some(1), + }, + ) + .await?; + assert_eq!( + l1_candidate.transactions.len(), + 1, + "only the supplied L1 message should execute; MorphTx fails in-block" + ); + assert!( + node.inner.pool.contains(&morph_tx_hash), + "supplied L1 message state mutation must NOT evict MorphTx valid on clean parent" + ); + + // 2. Higher-priority pool tx from `wallet` (account 0) mutates `L2TokenRegistry` mid-block. + let high_prio_mutator = MorphTxBuilder::new(wallet.chain_id, wallet.inner.clone(), 0) + .with_v1_eth_fee() + .with_to(registry) + .with_data(point_to_broken_calldata) + .with_fees(50_000_000_000, 50_000_000_000) + .with_gas_limit(100_000) + .build_signed()?; + let mutator_hash = node.rpc.inject_tx(high_prio_mutator).await?; + super::helpers::wait_until_pooled(&node, mutator_hash).await?; + + let pool_candidate = super::helpers::assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: genesis.hash, + transactions: vec![], + timestamp: Some(2), + }, + ) + .await?; + assert_eq!( + pool_candidate.transactions.len(), + 1, + "only the high-priority mutator tx should execute" + ); + assert!( + node.inner.pool.contains(&morph_tx_hash), + "in-block state mutation by another sender's pool tx must NOT evict MorphTx valid on clean parent" + ); + + // 3. Once `pool_candidate` IS imported as canonical Block 1, `TEST_TOKEN_ID` now fails + // `TokenTransferFailed` on the clean canonical parent itself, so assembling Block 2 + // on Block 1 MUST evict `morph_tx_hash` from the global pool. + super::helpers::import_l2_block(&node, pool_candidate.clone()).await?; + super::helpers::wait_until_evicted(&node, mutator_hash).await?; + + let deadline = tokio::time::Instant::now() + super::helpers::LOCAL_POLL_BUDGET; + while node.inner.pool.block_info().last_seen_block_hash != pool_candidate.hash { + assert!(tokio::time::Instant::now() < deadline); + tokio::time::sleep(super::helpers::POLL_INTERVAL).await; + } + + let block2 = super::helpers::assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: pool_candidate.hash, + transactions: vec![], + timestamp: Some(3), + }, + ) + .await?; + assert!(block2.transactions.is_empty()); + assert!( + !node.inner.pool.contains(&morph_tx_hash), + "genuinely broken MorphTx on clean canonical head MUST be evicted" + ); + + Ok(()) +} diff --git a/crates/payload/builder/src/builder.rs b/crates/payload/builder/src/builder.rs index d90b6a5f..2b4fb74f 100644 --- a/crates/payload/builder/src/builder.rs +++ b/crates/payload/builder/src/builder.rs @@ -3,7 +3,7 @@ use crate::metrics::MorphPayloadBuilderMetrics; use crate::{MorphBuilderConfig, MorphPayloadBuilderError, config::PayloadBuildingBreaker}; use alloy_consensus::{BlockHeader, Transaction, Typed2718, transaction::TxHashRef}; -use alloy_eips::eip2718::Encodable2718; +use alloy_eips::{BlockId, eip2718::Encodable2718}; use alloy_primitives::{Address, B256, Bytes, U256}; use morph_chainspec::{ L2_MESSAGE_QUEUE_ADDRESS, L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT, MorphChainSpec, @@ -32,7 +32,7 @@ use reth_execution_types::BlockExecutionOutput; use reth_payload_builder::PayloadId; use reth_payload_primitives::{BuiltPayloadExecutedBlock, PayloadBuilderError}; use reth_payload_util::{BestPayloadTransactions, NoopPayloadTransactions, PayloadTransactions}; -use reth_primitives_traits::{FastInstant as Instant, RecoveredBlock, SealedHeader}; +use reth_primitives_traits::{FastInstant as Instant, Recovered, RecoveredBlock, SealedHeader}; use reth_revm::{database::StateProviderDatabase, db::State}; use reth_storage_api::{StateProvider, StateProviderFactory}; use reth_transaction_pool::{BestTransactionsAttributes, PoolTransaction, TransactionPool}; @@ -250,12 +250,26 @@ where payload_id, }; + // Only evict failing pool transactions when building on the current canonical head + // AND the pool has not moved onto a different head: a non-canonical parent (e.g., + // `assembleL2BlockV2` rebuilding on an older block before a token was activated) + // must never remove transactions that are valid on the canonical chain. + let canonical_head_hash = self + .client + .block_hash_for_id(BlockId::latest()) + .ok() + .flatten(); + let pool_seen_hash = self.pool.block_info().last_seen_block_hash; + let can_evict_from_pool = canonical_head_hash == Some(parent_hash) + && (pool_seen_hash.is_zero() || pool_seen_hash == parent_hash); + let ctx = MorphPayloadBuilderCtx { evm_config: self.evm_config.clone(), config: builder_config, cancel, best_payload, builder_config: self.config.clone(), + can_evict_from_pool, metrics: MorphPayloadBuilderMetrics::default(), }; @@ -355,6 +369,9 @@ struct MorphPayloadBuilderCtx { best_payload: Option, /// Builder configuration with limits. builder_config: MorphBuilderConfig, + /// Whether this build targets the current canonical head synchronized with the pool, + /// permitting deterministic token-fee eviction from the global pool. + can_evict_from_pool: bool, /// Prometheus metrics for this payload build job. metrics: MorphPayloadBuilderMetrics, } @@ -411,6 +428,7 @@ impl MorphPayloadBuilderCtx { let supplied_tx_count = self.attributes().transactions.len(); let mut executed_txs: Vec = Vec::with_capacity(supplied_tx_count); let mut saw_l2_transaction = false; + let mut first_l1_msg = true; for (tx_idx, tx_with_encoded) in self.attributes().transactions.iter().enumerate() { // The transaction is already recovered in `try_new` via `try_into_recovered()`. @@ -444,7 +462,20 @@ impl MorphPayloadBuilderCtx { }, ) })?; - if queue_index != info.next_l1_message_index { + // Sequencer assembly (`!no_tx_pool`) requires exact continuity with + // `info.next_l1_message_index` (matching morph-geth's `miner/worker.go`). + // Deterministic L1 derivation (`no_tx_pool`) permits the leading L1 message + // to skip past `parent.next_l1_msg_index` when L1 messages were skipped, + // while still rejecting cross-block replays (`<`) and requiring strict + // sequential indices for subsequent L1 messages in the same block. + let allow_forward_skip = self.attributes().no_tx_pool && first_l1_msg; + first_l1_msg = false; + let invalid_queue_index = if allow_forward_skip { + queue_index < info.next_l1_message_index + } else { + queue_index != info.next_l1_message_index + }; + if invalid_queue_index { return Err(PayloadBuilderError::other( MorphPayloadBuilderError::InvalidSuppliedTransaction { error: format!( @@ -591,6 +622,10 @@ impl MorphPayloadBuilderCtx { // L1-message gas to the block gas pool. Regular transactions do return unused gas. info.gas_pool_used += if is_l1_msg { tx_gas } else { gas_used }; + // Track sender only after successful execution so later pool txs from the same + // sender are never evicted if they fail against in-block mutated sender state. + info.executed_senders.insert(recovered_tx.signer()); + // Increment transaction count info.transaction_count += 1; @@ -605,9 +640,12 @@ impl MorphPayloadBuilderCtx { /// /// Returns `Ok(Some(()))` if the job was cancelled or breaker triggered, `Ok(None)` otherwise. /// Executed transaction bytes are appended to the provided vector. + #[expect(clippy::too_many_arguments)] fn execute_pool_transactions( &self, builder: &mut impl BlockBuilder, + state_provider: &(impl StateProvider + ?Sized), + next_block_attrs: &MorphNextBlockEnvAttributes, info: &mut ExecutionInfo, executed_txs: &mut Vec, best_txs: BestTxs, @@ -624,12 +662,31 @@ impl MorphPayloadBuilderCtx { executed_txs, best_txs, breaker, + |tx| { + let Ok(evm_env) = self + .evm_config + .next_evm_env(self.parent(), next_block_attrs) + else { + return false; + }; + let tx_env = self.evm_config.tx_env(tx); + let mut clean_evm = self + .evm_config + .evm_with_env(StateProviderDatabase::new(state_provider), evm_env); + match clean_evm.validate_only(tx_env) { + Err(revm::context::result::EVMError::Transaction(morph_err)) => { + is_evictable_token_fee_error(&morph_err) + } + _ => false, + } + }, |tx_hash| { pool.remove_transactions(vec![tx_hash]); }, ) } + #[expect(clippy::too_many_arguments)] fn execute_pool_transactions_with_evictor( &self, builder: &mut impl BlockBuilder, @@ -637,6 +694,7 @@ impl MorphPayloadBuilderCtx { executed_txs: &mut Vec, mut best_txs: BestTxs, breaker: &PayloadBuildingBreaker, + mut confirm_eviction_on_clean_parent: impl FnMut(&Recovered) -> bool, mut evict_from_pool: impl FnMut(B256), ) -> Result, PayloadBuilderError> where @@ -644,7 +702,6 @@ impl MorphPayloadBuilderCtx { { let block_gas_limit = builder.evm().block().gas_limit(); let base_fee = builder.evm().block().basefee(); - let mut executed_senders: HashSet
= HashSet::new(); while let Some(tx) = best_txs.next(()) { // Check if the job was cancelled @@ -754,8 +811,11 @@ impl MorphPayloadBuilderCtx { "skipping invalid transaction and its descendants" ); best_txs.mark_invalid(tx.signer(), tx.nonce()); - if is_evictable_token_fee_error(error.as_ref()) - && !executed_senders.contains(&tx.signer()) + if self.can_evict_from_pool + && is_evictable_token_fee_error(error.as_ref()) + && !info.executed_senders.contains(&tx.signer()) + && (info.transaction_count == 0 + || confirm_eviction_on_clean_parent(&tx)) { tracing::debug!( target: "payload_builder", @@ -796,7 +856,7 @@ impl MorphPayloadBuilderCtx { self.metrics .commit_tx_apply_duration_seconds .record(apply_started.elapsed()); - executed_senders.insert(tx.signer()); + info.executed_senders.insert(tx.signer()); // Update execution info info.cumulative_gas_used += gas_used; @@ -837,13 +897,15 @@ struct ExecutionInfo { next_l1_message_index: u64, /// Number of transactions executed (including both sequencer and pool transactions). transaction_count: u64, + /// Senders that have already executed at least one transaction (supplied or pool) in this block. + executed_senders: HashSet
, /// Maximum DA block size from the builder config. max_da_block_size: Option, } impl ExecutionInfo { /// Creates a new [`ExecutionInfo`] with the initial next L1 message index from parent. - const fn new(next_l1_message_index: u64, max_da_block_size: Option) -> Self { + fn new(next_l1_message_index: u64, max_da_block_size: Option) -> Self { Self { cumulative_gas_used: 0, gas_pool_used: 0, @@ -851,6 +913,7 @@ impl ExecutionInfo { total_fees: U256::ZERO, next_l1_message_index, transaction_count: 0, + executed_senders: HashSet::new(), max_da_block_size, } } @@ -930,7 +993,7 @@ where // Create block builder let mut builder = ctx .evm_config - .builder_for_next_block(&mut db, ctx.parent(), next_block_attrs) + .builder_for_next_block(&mut db, ctx.parent(), next_block_attrs.clone()) .map_err(PayloadBuilderError::other)?; // If the engine tree provided a sparse-trie state root handle, wire the @@ -975,6 +1038,8 @@ where if ctx .execute_pool_transactions( &mut builder, + state_provider, + &next_block_attrs, &mut info, &mut executed_txs, best_txs, @@ -1342,6 +1407,7 @@ mod tests { cancel: Default::default(), best_payload, builder_config: MorphBuilderConfig::default(), + can_evict_from_pool: true, metrics: MorphPayloadBuilderMetrics::default(), } } @@ -1625,6 +1691,7 @@ mod tests { cancel: Default::default(), best_payload: None, builder_config: MorphBuilderConfig::default(), + can_evict_from_pool: true, metrics: MorphPayloadBuilderMetrics::default(), } } @@ -1861,6 +1928,7 @@ mod tests { &mut executed_txs, best_txs, &breaker, + |_| true, |hash| evicted.push(hash), ) .expect("pool execution should complete"); @@ -2079,6 +2147,7 @@ mod tests { &mut executed_txs, best_txs, &breaker, + |_| true, |hash| evicted.push(hash), ) .expect("pool execution should complete"); @@ -2090,4 +2159,279 @@ mod tests { assert_eq!(evicted, vec![h_transfer_fail, h_inactive]); assert_eq!(executed_txs.len(), 1); } + + #[test] + fn test_execute_pool_transactions_does_not_evict_when_non_canonical_or_caused_by_in_block_state() + { + use alloy_consensus::{Sealable, Signed, TxEip1559}; + use alloy_primitives::{Signature, TxKind}; + use morph_primitives::{TxL1Msg, TxMorph}; + use morph_txpool::MorphPooledTransaction; + use reth_primitives_traits::Recovered; + use std::collections::{HashMap, VecDeque}; + + let make_morph_tx = |signer: Address, nonce: u64, tag: u8| { + let tx = TxMorph { + chain_id: 2818, + nonce, + gas_limit: 50_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + fee_token_id: 1, + ..Default::default() + }; + let hash = B256::repeat_byte(tag); + let env = MorphTxEnvelope::Morph(Signed::new_unchecked( + tx, + Signature::test_signature(), + hash, + )); + let recovered = Recovered::new_unchecked(env, signer); + let len = recovered.encode_2718_len(); + (hash, MorphPooledTransaction::new(recovered, len)) + }; + + let make_eth_tx = |signer: Address, nonce: u64, tag: u8| { + let tx = TxEip1559 { + chain_id: 2818, + nonce, + gas_limit: 21_000, + max_fee_per_gas: 100, + max_priority_fee_per_gas: 10, + to: TxKind::Call(Address::repeat_byte(0xee)), + ..Default::default() + }; + let hash = B256::repeat_byte(tag); + let env = MorphTxEnvelope::Eip1559(Signed::new_unchecked( + tx, + Signature::test_signature(), + hash, + )); + let recovered = Recovered::new_unchecked(env, signer); + let len = recovered.encode_2718_len(); + (hash, MorphPooledTransaction::new(recovered, len)) + }; + + // 1. Non-canonical parent build (`can_evict_from_pool == false`): never evicts even + // at `transaction_count == 0`. + let sender_a = Address::repeat_byte(0x10); + let (h_stale_inactive, tx_stale_inactive) = make_morph_tx(sender_a, 0, 0xa1); + let mut outcomes = HashMap::new(); + outcomes.insert( + h_stale_inactive, + Err(MorphInvalidTransaction::TokenNotActive(1)), + ); + let mut builder = ScriptedBlockBuilder::new(outcomes); + let mut info = ExecutionInfo::default(); + let mut executed_txs = Vec::new(); + let mut ctx = test_ctx_with_timestamp_and_txs(1_800_000_000, vec![]); + ctx.can_evict_from_pool = false; + let breaker = ctx.builder_config.breaker(30_000_000); + let mut evicted = Vec::new(); + + ctx.execute_pool_transactions_with_evictor( + &mut builder, + &mut info, + &mut executed_txs, + ScriptedPoolTxs { + txs: VecDeque::from([tx_stale_inactive]), + marked_invalid: Vec::new(), + }, + &breaker, + |_| panic!("clean-parent check should not run when can_evict_from_pool is false"), + |hash| evicted.push(hash), + ) + .expect("pool execution should complete"); + assert!( + evicted.is_empty(), + "non-canonical parent build must never evict from global pool" + ); + + // 2. In-block state mutation by an earlier transaction from another sender: + // `h_mutated_in_block` is valid on clean parent (`confirm == false` -> NOT evicted), + // whereas `h_broken_on_parent` also fails on clean parent (`confirm == true` -> evicted). + let sender_mutator = Address::repeat_byte(0x20); + let sender_victim = Address::repeat_byte(0x21); + let sender_broken = Address::repeat_byte(0x22); + let (h_mutator, tx_mutator) = make_eth_tx(sender_mutator, 0, 0xb1); + let (h_mutated_in_block, tx_mutated_in_block) = make_morph_tx(sender_victim, 0, 0xb2); + let (h_broken_on_parent, tx_broken_on_parent) = make_morph_tx(sender_broken, 0, 0xb3); + + let mut outcomes = HashMap::new(); + outcomes.insert(h_mutator, Ok(21_000)); + outcomes.insert( + h_mutated_in_block, + Err(MorphInvalidTransaction::TokenTransferFailed { + reason: "paused mid-block".into(), + }), + ); + outcomes.insert( + h_broken_on_parent, + Err(MorphInvalidTransaction::TokenBalanceQueryFailed), + ); + let mut builder = ScriptedBlockBuilder::new(outcomes); + let mut info = ExecutionInfo::default(); + let mut executed_txs = Vec::new(); + let ctx = test_ctx_with_timestamp_and_txs(1_800_000_000, vec![]); + let breaker = ctx.builder_config.breaker(30_000_000); + let mut evicted = Vec::new(); + + ctx.execute_pool_transactions_with_evictor( + &mut builder, + &mut info, + &mut executed_txs, + ScriptedPoolTxs { + txs: VecDeque::from([tx_mutator, tx_mutated_in_block, tx_broken_on_parent]), + marked_invalid: Vec::new(), + }, + &breaker, + |tx| *tx.tx_hash() == h_broken_on_parent, + |hash| evicted.push(hash), + ) + .expect("pool execution should complete"); + assert_eq!( + evicted, + vec![h_broken_on_parent], + "only tx confirmed invalid on clean parent may be evicted after earlier txs ran" + ); + + // 3. Supplied L1 message from `sender_l1` seeds `info.executed_senders`, preventing + // eviction of a subsequent failing pool tx from `sender_l1`. + let sender_l1 = Address::repeat_byte(0x30); + let l1_msg = TxL1Msg { + queue_index: 0, + gas_limit: 50_000, + to: Address::repeat_byte(0xaa), + value: U256::ZERO, + sender: sender_l1, + input: Bytes::new(), + }; + let l1_sealed = l1_msg.seal_slow(); + let l1_hash = l1_sealed.hash(); + let l1_encoded = Bytes::from(MorphTxEnvelope::L1Msg(l1_sealed).encoded_2718()); + let (h_l1_sender_pool_tx, tx_l1_sender_pool_tx) = make_morph_tx(sender_l1, 0, 0xc1); + + let mut outcomes = HashMap::new(); + outcomes.insert(l1_hash, Ok(21_000)); + outcomes.insert( + h_l1_sender_pool_tx, + Err(MorphInvalidTransaction::TokenTransferFailed { + reason: "l1 msg changed sender state".into(), + }), + ); + let mut builder = ScriptedBlockBuilder::new(outcomes); + let mut info = ExecutionInfo::default(); + let ctx = test_ctx_with_timestamp_and_txs(1_800_000_000, vec![l1_encoded]); + let mut executed_txs = ctx + .execute_supplied_transactions(&mut builder, &mut info) + .expect("supplied L1 msg should execute"); + assert!(info.executed_senders.contains(&sender_l1)); + + let breaker = ctx.builder_config.breaker(30_000_000); + let mut evicted = Vec::new(); + ctx.execute_pool_transactions_with_evictor( + &mut builder, + &mut info, + &mut executed_txs, + ScriptedPoolTxs { + txs: VecDeque::from([tx_l1_sender_pool_tx]), + marked_invalid: Vec::new(), + }, + &breaker, + |_| true, + |hash| evicted.push(hash), + ) + .expect("pool execution should complete"); + assert!( + evicted.is_empty(), + "sender with executed supplied L1 message in block must not be evicted" + ); + } + + #[test] + fn test_execute_supplied_transactions_no_tx_pool_allows_leading_l1_forward_skip_only() { + use alloy_consensus::Sealable; + use morph_primitives::TxL1Msg; + use std::collections::HashMap; + + let make_l1 = |queue_index: u64| { + let sealed = TxL1Msg { + queue_index, + gas_limit: 50_000, + to: Address::repeat_byte(0xaa), + value: U256::ZERO, + sender: Address::repeat_byte(0xbb), + input: Bytes::new(), + } + .seal_slow(); + let hash = sealed.hash(); + let bytes = Bytes::from(MorphTxEnvelope::L1Msg(sealed).encoded_2718()); + (hash, bytes) + }; + + let make_no_pool_ctx = |txs: Vec| { + let mut rpc_attrs = morph_payload_types::MorphPayloadAttributes::default(); + rpc_attrs.inner.timestamp = 1_800_000_000; + rpc_attrs.transactions = Some(txs); + rpc_attrs.no_tx_pool = true; + let attrs = MorphPayloadBuilderAttributes::try_new( + B256::ZERO, + rpc_attrs, + morph_payload_types::MORPH_PAYLOAD_BUILDER_VERSION, + ) + .unwrap(); + let payload_id = attrs.payload_id(); + MorphPayloadBuilderCtx { + evm_config: test_evm_config(), + config: PayloadConfig::new( + Arc::new(SealedHeader::seal_slow(MorphHeader::default())), + attrs, + payload_id, + ), + cancel: Default::default(), + best_payload: None, + builder_config: MorphBuilderConfig::default(), + can_evict_from_pool: false, + metrics: MorphPayloadBuilderMetrics::default(), + } + }; + + // Forward skip on leading L1 msg (parent next=2, msgs=[5, 6]) succeeds under `no_tx_pool`. + let (h5, b5) = make_l1(5); + let (h6, b6) = make_l1(6); + let mut outcomes = HashMap::new(); + outcomes.insert(h5, Ok(21_000)); + outcomes.insert(h6, Ok(21_000)); + let mut builder = ScriptedBlockBuilder::new(outcomes); + let mut info = ExecutionInfo::new(2, None); + let ctx = make_no_pool_ctx(vec![b5.clone(), b6]); + let executed = ctx + .execute_supplied_transactions(&mut builder, &mut info) + .expect("leading forward skip in deterministic safe build must succeed"); + assert_eq!(executed.len(), 2); + assert_eq!(info.next_l1_message_index, 7); + + // Cross-block replay (`queue_index = 1 < parent next = 2`) still fails. + let (_h1, b1) = make_l1(1); + let mut builder = ScriptedBlockBuilder::new(HashMap::new()); + let mut info = ExecutionInfo::new(2, None); + let ctx = make_no_pool_ctx(vec![b1]); + assert!( + ctx.execute_supplied_transactions(&mut builder, &mut info) + .is_err() + ); + + // Non-contiguous second L1 message (`[5, 8]`) still fails. + let (_h8, b8) = make_l1(8); + let mut outcomes = HashMap::new(); + outcomes.insert(h5, Ok(21_000)); + let mut builder = ScriptedBlockBuilder::new(outcomes); + let mut info = ExecutionInfo::new(2, None); + let ctx = make_no_pool_ctx(vec![b5, b8]); + assert!( + ctx.execute_supplied_transactions(&mut builder, &mut info) + .is_err() + ); + } } diff --git a/crates/payload/types/src/lib.rs b/crates/payload/types/src/lib.rs index aa621bc3..df353f96 100644 --- a/crates/payload/types/src/lib.rs +++ b/crates/payload/types/src/lib.rs @@ -21,10 +21,13 @@ mod safe_l2_data; use alloy_consensus::BlockHeader as _; use alloy_eips::eip4895::Withdrawal; use alloy_primitives::{B256, Bytes}; -use morph_primitives::Block; +use morph_primitives::{Block, MorphHeader}; use reth_payload_primitives::{BuiltPayload, ExecutionPayload, PayloadTypes}; -use reth_primitives_traits::{NodePrimitives, SealedBlock}; -use std::sync::Arc; +use reth_primitives_traits::{NodePrimitives, SealedBlock, SealedHeader}; +use std::{ + collections::{HashMap, VecDeque}, + sync::{Arc, Mutex}, +}; // Feature unification: Ensure reth-ethereum-primitives' serde features are enabled // for transitive dependencies (via reth-payload-primitives → reth-chain-state). @@ -52,7 +55,76 @@ pub use safe_l2_data::SafeL2Data; #[non_exhaustive] pub struct MorphPayloadTypes; -/// Execution data for Morph node: a sealed block plus an optional expected withdraw trie root. +/// Consensus validation mode applied when importing a [`MorphExecutionData`] payload. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum MorphPayloadValidationMode { + /// Standard untrusted payload validation (`VerifyHeader` + `ValidateBody` + execution). + #[default] + Full, + /// Locally assembled block (`AssembleL2Block` / `AssembleL2BlockV2` `verified` path in + /// morph-geth). Skips wall-clock `TimestampIsInFuture`, `GasLimit` 1/1024 bound, and local + /// DA payload byte limit. + LocallyBuilt, + /// L1-derived safe block (`NewSafeL2Block` with `safe = true` in morph-geth). Skips + /// `VerifyHeader` (`TimestampIsInFuture`, `TimestampIsInPast`, `GasLimit` bounds, + /// `BaseFeeOverLimit`) and `ValidateBody`'s local DA payload byte limit. + Safe, +} + +/// Bounded in-memory cache of validated [`SealedHeader`] entries currently held in +/// the engine tree, shared between the tree validator and the custom Morph L2 Engine API so +/// unpersisted in-memory parent headers are visible before MDBX persistence. +#[derive(Debug, Default)] +pub struct TreeHeaderCache { + inner: Mutex, +} + +#[derive(Debug, Default)] +struct TreeHeaderCacheInner { + entries: HashMap>, + order: VecDeque, +} + +impl TreeHeaderCache { + /// Maximum number of sealed headers retained in memory. + pub const MAX_ENTRIES: usize = 8192; + + /// Creates an empty [`TreeHeaderCache`]. + pub fn new() -> Self { + Self::default() + } + + /// Records a validated sealed header in the cache. + pub fn insert(&self, header: SealedHeader) { + let hash = header.hash(); + let mut inner = self + .inner + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let is_new = inner.entries.insert(hash, header).is_none(); + if is_new { + inner.order.push_back(hash); + while inner.entries.len() > Self::MAX_ENTRIES { + let Some(evicted) = inner.order.pop_front() else { + break; + }; + inner.entries.remove(&evicted); + } + } + } + + /// Looks up a sealed header by block hash. + pub fn get(&self, hash: &B256) -> Option> { + self.inner + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .entries + .get(hash) + .cloned() + } +} + +/// Execution data for Morph node: a sealed block plus optional cross-check metadata. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct MorphExecutionData { /// The built block. @@ -60,6 +132,9 @@ pub struct MorphExecutionData { /// Optional expected withdraw trie root supplied by custom engine APIs. #[serde(default, skip_serializing_if = "Option::is_none")] pub expected_withdraw_trie_root: Option, + /// Validation mode governing consensus header/body exemptions. + #[serde(default)] + pub validation_mode: MorphPayloadValidationMode, } impl MorphExecutionData { @@ -68,6 +143,7 @@ impl MorphExecutionData { Self { block, expected_withdraw_trie_root: None, + validation_mode: MorphPayloadValidationMode::Full, } } @@ -79,8 +155,18 @@ impl MorphExecutionData { Self { block, expected_withdraw_trie_root: Some(expected_withdraw_trie_root), + validation_mode: MorphPayloadValidationMode::Full, } } + + /// Sets the consensus validation mode for this payload. + pub const fn with_validation_mode( + mut self, + validation_mode: MorphPayloadValidationMode, + ) -> Self { + self.validation_mode = validation_mode; + self + } } impl From for MorphExecutionData { @@ -247,5 +333,57 @@ mod tests { let data = MorphPayloadTypes::block_to_payload(block, None); assert_eq!(data.block_hash(), hash); assert!(data.expected_withdraw_trie_root.is_none()); + assert_eq!(data.validation_mode, MorphPayloadValidationMode::Full); + } + + #[test] + fn test_execution_data_validation_mode_builder() { + let block = Arc::new(create_test_block()); + let data = MorphExecutionData::new(block); + assert_eq!(data.validation_mode, MorphPayloadValidationMode::Full); + + let local = data + .clone() + .with_validation_mode(MorphPayloadValidationMode::LocallyBuilt); + assert_eq!( + local.validation_mode, + MorphPayloadValidationMode::LocallyBuilt + ); + + let safe = data.with_validation_mode(MorphPayloadValidationMode::Safe); + assert_eq!(safe.validation_mode, MorphPayloadValidationMode::Safe); + } + + #[test] + fn test_tree_header_cache_insert_get_and_bounded_eviction() { + let cache = TreeHeaderCache::new(); + let mut first_hash = B256::ZERO; + let mut last_hash = B256::ZERO; + + for number in 0..=(TreeHeaderCache::MAX_ENTRIES as u64) { + let header = SealedHeader::seal_slow(MorphHeader { + inner: Header { + number, + ..Default::default() + }, + next_l1_msg_index: number + 1, + }); + if number == 0 { + first_hash = header.hash(); + } + if number == TreeHeaderCache::MAX_ENTRIES as u64 { + last_hash = header.hash(); + } + cache.insert(header); + } + + assert!( + cache.get(&first_hash).is_none(), + "oldest entry must be evicted once MAX_ENTRIES is exceeded" + ); + assert_eq!( + cache.get(&last_hash).unwrap().next_l1_msg_index, + TreeHeaderCache::MAX_ENTRIES as u64 + 1 + ); } } From 3896cab599acfde87154af358adb1afa40698642 Mon Sep 17 00:00:00 2001 From: panos-xyz Date: Fri, 27 Nov 2026 15:57:10 +0800 Subject: [PATCH 3/4] fix(validator,builder,payload-types): harden mode retention, WTR resolution, serde skip, and pool eviction recheck --- crates/node/src/validator.rs | 207 ++++++++++++++---- .../node/tests/it/invalid_payload_recovery.rs | 136 ++++++++++++ crates/node/tests/it/morph_tx.rs | 32 ++- crates/payload/builder/src/builder.rs | 125 ++++++++++- crates/payload/types/src/lib.rs | 30 ++- 5 files changed, 470 insertions(+), 60 deletions(-) diff --git a/crates/node/src/validator.rs b/crates/node/src/validator.rs index 1f031d07..4c963b0b 100644 --- a/crates/node/src/validator.rs +++ b/crates/node/src/validator.rs @@ -262,7 +262,7 @@ struct MorphEngineConsensus { } impl MorphEngineConsensus { - const MAX_MODES: usize = 128; + const MAX_MODES: usize = 1024; fn new(inner: MorphConsensus) -> Self { Self { @@ -275,22 +275,30 @@ impl MorphEngineConsensus { &self.inner } - fn set_mode(&self, block_hash: B256, mode: MorphPayloadValidationMode) { - let mut cache = self.modes.lock(); + fn record_mode(&self, block_hash: B256, mode: MorphPayloadValidationMode) { if mode == MorphPayloadValidationMode::Full { - if cache.entries.remove(&block_hash).is_some() { - cache.order.retain(|hash| *hash != block_hash); - } + // `Full` is the default when absent. Never delete or downgrade an existing + // `LocallyBuilt` or `Safe` entry: `BasicEngineValidator` runs + // `spawn_convert_and_validate` on a background thread, and buffered + // `Safe` / `LocallyBuilt` payloads later pass through `validate_block`. return; } - let is_new = cache.entries.insert(block_hash, mode).is_none(); - if is_new { - cache.order.push_back(block_hash); - while cache.entries.len() > Self::MAX_MODES { - let Some(evicted) = cache.order.pop_front() else { - break; - }; - cache.entries.remove(&evicted); + let mut cache = self.modes.lock(); + match cache.entries.get_mut(&block_hash) { + Some(existing) => { + if mode > *existing { + *existing = mode; + } + } + None => { + cache.entries.insert(block_hash, mode); + cache.order.push_back(block_hash); + while cache.entries.len() > Self::MAX_MODES { + let Some(evicted) = cache.order.pop_front() else { + break; + }; + cache.entries.remove(&evicted); + } } } } @@ -480,10 +488,36 @@ where self.provider.sealed_header_by_hash(hash) } + /// Walks in-memory `tree_state` ancestors from `parent_hash` without hitting MDBX so + /// unpersisted side-branch parents still resolve their `withdraw_trie_root` even if + /// evicted from `KnownWithdrawTrieRootCache`. + fn find_tree_ancestor_withdraw_trie_root( + &self, + parent_hash: B256, + ctx: &TreeCtx<'_, MorphPrimitives>, + ) -> (Option, B256) { + let mut cur = parent_hash; + loop { + if let Some(root) = self.get_known_withdraw_trie_root(cur) { + return (Some(root), cur); + } + let Some(executed) = ctx.state().tree_state().executed_block_by_hash(cur) else { + return (None, cur); + }; + if let Some(updated) = + Self::updated_withdraw_trie_root_from_bundle_state(&executed.execution_output.state) + { + return (Some(updated), cur); + } + cur = executed.recovered_block().parent_hash(); + } + } + fn resolve_post_block_withdraw_trie_root( &self, parent_hash: B256, bundle_state: &BundleState, + tree_hint: Option<(Option, B256)>, ) -> ProviderResult { if let Some(updated) = Self::updated_withdraw_trie_root_from_bundle_state(bundle_state) { return Ok(updated); @@ -491,14 +525,21 @@ where if let Some(parent_root) = self.get_known_withdraw_trie_root(parent_hash) { return Ok(parent_root); } - let state = self.provider.state_by_block_hash(parent_hash)?; + if let Some((Some(ancestor_root), _)) = tree_hint { + self.record_known_withdraw_trie_root(parent_hash, ancestor_root); + return Ok(ancestor_root); + } + let fallback_hash = tree_hint.map_or(parent_hash, |(_, ancestor_hash)| ancestor_hash); + let state = self.provider.state_by_block_hash(fallback_hash)?; let slot_val = state .storage( L2_MESSAGE_QUEUE_ADDRESS, B256::from(L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT), )? .unwrap_or_default(); - Ok(B256::from(slot_val)) + let actual = B256::from(slot_val); + self.record_known_withdraw_trie_root(parent_hash, actual); + Ok(actual) } /// Validates `header.next_l1_msg_index` during `convert_payload_to_block` (which runs on @@ -681,6 +722,7 @@ where fn verify_and_record_withdraw_trie_root( &self, expectation: WithdrawTrieRootExpectation, + tree_hint: Option<(Option, B256)>, output: reth_engine_tree::tree::ValidationOutput, ) -> reth_engine_tree::tree::ValidationOutcome { let sealed_block = output.executed_block.sealed_block(); @@ -690,6 +732,7 @@ where .resolve_post_block_withdraw_trie_root( parent_hash, &output.executed_block.execution_output.state, + tree_hint, ) .map_err(|err| InsertBlockError::new(sealed_block.clone(), err.into()))?; @@ -741,6 +784,8 @@ where ) -> Result, NewPayloadError> { let block_hash = payload.block.hash(); self.validate_l1_msg_index_on_conversion(payload.block.as_ref())?; + self.engine_consensus + .record_mode(block_hash, payload.validation_mode); match payload.expected_withdraw_trie_root { None => {} @@ -765,26 +810,45 @@ where .map_err(|e| NewPayloadError::Other(Box::new(e)))? .is_some() { - let state = self - .provider - .state_by_block_hash(block_hash) - .map_err(|e| NewPayloadError::Other(Box::new(e)))?; - let slot_val = state - .storage( - L2_MESSAGE_QUEUE_ADDRESS, - B256::from(L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT), - ) - .map_err(|e| NewPayloadError::Other(Box::new(e)))? - .unwrap_or_default(); - let actual = B256::from(slot_val); - self.record_known_withdraw_trie_root(block_hash, actual); - self.post_execution_validator - .take_withdraw_trie_root_expectation(block_hash); - payload.expected_withdraw_trie_root = None; - if actual != expected { - return Err(NewPayloadError::Other(Box::new( - MorphConsensusError::WithdrawTrieRootMismatch { expected, actual }, - ))); + match self.provider.state_by_block_hash(block_hash) { + Ok(state) => { + let slot_val = state + .storage( + L2_MESSAGE_QUEUE_ADDRESS, + B256::from(L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT), + ) + .map_err(|e| NewPayloadError::Other(Box::new(e)))? + .unwrap_or_default(); + let actual = B256::from(slot_val); + self.record_known_withdraw_trie_root(block_hash, actual); + self.post_execution_validator + .take_withdraw_trie_root_expectation(block_hash); + payload.expected_withdraw_trie_root = None; + if actual != expected { + return Err(NewPayloadError::Other(Box::new( + MorphConsensusError::WithdrawTrieRootMismatch { + expected, + actual, + }, + ))); + } + } + Err( + ProviderError::StateAtBlockPruned(_) + | ProviderError::StateForHashNotFound(_), + ) => { + tracing::warn!( + target: "morph::engine_validator", + %block_hash, + "skipping withdraw_trie_root check on persisted block with pruned historical state" + ); + self.post_execution_validator + .take_withdraw_trie_root_expectation(block_hash); + payload.expected_withdraw_trie_root = None; + } + Err(err) => { + return Err(NewPayloadError::Other(Box::new(err))); + } } } } @@ -798,6 +862,7 @@ where ctx: TreeCtx<'_, MorphPrimitives>, ) -> reth_engine_tree::tree::ValidationOutcome { let block_hash = payload.block.hash(); + let parent_hash = payload.block.parent_hash(); // Extract the expectation directly onto the stack so the live `validate_payload` // path never inserts into (or can leak from) `expected_withdraw_trie_roots`. // Also clear any residual entry left by an earlier buffered conversion. @@ -806,12 +871,13 @@ where .take_withdraw_trie_root_expectation(block_hash); self.validate_next_l1_msg_index_for_block(payload.block.as_ref(), &ctx)?; + let tree_hint = Some(self.find_tree_ancestor_withdraw_trie_root(parent_hash, &ctx)); self.engine_consensus - .set_mode(block_hash, payload.validation_mode); + .record_mode(block_hash, payload.validation_mode); let output = self.inner.validate_payload(payload, ctx)?; let expectation = MorphEngineValidator::expectation_from_root(expected_withdraw_trie_root); - self.verify_and_record_withdraw_trie_root(expectation, output) + self.verify_and_record_withdraw_trie_root(expectation, tree_hint, output) } fn validate_block( @@ -820,11 +886,11 @@ where ctx: TreeCtx<'_, MorphPrimitives>, ) -> reth_engine_tree::tree::ValidationOutcome { let block_hash = block.hash(); - self.engine_consensus - .set_mode(block_hash, MorphPayloadValidationMode::Full); + let parent_hash = block.parent_hash(); let l1_validation = self.validate_next_l1_msg_index_for_block(&block, &ctx); self.post_execution_validator .clear_withdraw_trie_root_expectation_on_error(block_hash, l1_validation)?; + let tree_hint = Some(self.find_tree_ancestor_withdraw_trie_root(parent_hash, &ctx)); let validation = self.inner.validate_block(block, ctx); let output = self @@ -834,7 +900,7 @@ where .post_execution_validator .take_withdraw_trie_root_expectation(block_hash) .unwrap_or(WithdrawTrieRootExpectation::SkipValidation); - self.verify_and_record_withdraw_trie_root(expectation, output) + self.verify_and_record_withdraw_trie_root(expectation, tree_hint, output) } fn on_inserted_executed_block( @@ -842,12 +908,12 @@ where block: BuiltPayloadExecutedBlock, ) -> ProviderResult> { self.validate_pre_inserted_block(block.recovered_block.as_ref())?; - if let Ok(actual) = self.resolve_post_block_withdraw_trie_root( + let actual = self.resolve_post_block_withdraw_trie_root( block.recovered_block.parent_hash(), &block.execution_output.state, - ) { - self.record_known_withdraw_trie_root(block.recovered_block.hash(), actual); - } + None, + )?; + self.record_known_withdraw_trie_root(block.recovered_block.hash(), actual); let executed = self.inner.on_inserted_executed_block(block)?; self.tree_headers .insert(executed.recovered_block().sealed_header().clone()); @@ -1643,4 +1709,55 @@ mod tests { .is_ok() ); } + + #[test] + fn morph_engine_consensus_mode_records_monotonically_without_downgrade_or_full_deletion() { + let consensus = MorphEngineConsensus::new(MorphConsensus::new(Arc::new( + morph_chainspec::MORPH_MAINNET.as_ref().clone(), + ))); + let hash = B256::from([0x91; 32]); + + assert_eq!(consensus.mode_for(hash), MorphPayloadValidationMode::Full); + + // `Full` never inserts into the bounded cache. + consensus.record_mode(hash, MorphPayloadValidationMode::Full); + assert!(consensus.modes.lock().entries.is_empty()); + + // `LocallyBuilt` is retained and not deleted by a concurrent/subsequent `Full` call. + consensus.record_mode(hash, MorphPayloadValidationMode::LocallyBuilt); + assert_eq!( + consensus.mode_for(hash), + MorphPayloadValidationMode::LocallyBuilt + ); + consensus.record_mode(hash, MorphPayloadValidationMode::Full); + assert_eq!( + consensus.mode_for(hash), + MorphPayloadValidationMode::LocallyBuilt, + "untrusted Full validation must never clobber LocallyBuilt mode" + ); + + // `Safe` upgrades `LocallyBuilt` and is never downgraded back to `LocallyBuilt` or `Full`. + consensus.record_mode(hash, MorphPayloadValidationMode::Safe); + assert_eq!(consensus.mode_for(hash), MorphPayloadValidationMode::Safe); + consensus.record_mode(hash, MorphPayloadValidationMode::LocallyBuilt); + assert_eq!(consensus.mode_for(hash), MorphPayloadValidationMode::Safe); + consensus.record_mode(hash, MorphPayloadValidationMode::Full); + assert_eq!(consensus.mode_for(hash), MorphPayloadValidationMode::Safe); + + // Bounded FIFO eviction at MAX_MODES (1024). + for idx in 0..=MorphEngineConsensus::MAX_MODES { + let mut raw = [0u8; 32]; + raw[..8].copy_from_slice(&(idx as u64).to_be_bytes()); + consensus.record_mode(B256::from(raw), MorphPayloadValidationMode::LocallyBuilt); + } + assert_eq!( + consensus.modes.lock().entries.len(), + MorphEngineConsensus::MAX_MODES + ); + assert_eq!( + consensus.mode_for(hash), + MorphPayloadValidationMode::Full, + "oldest mode entry must be evicted once MAX_MODES is exceeded" + ); + } } diff --git a/crates/node/tests/it/invalid_payload_recovery.rs b/crates/node/tests/it/invalid_payload_recovery.rs index d37e459e..acf5efc8 100644 --- a/crates/node/tests/it/invalid_payload_recovery.rs +++ b/crates/node/tests/it/invalid_payload_recovery.rs @@ -730,3 +730,139 @@ async fn locally_built_and_safe_modes_still_reject_structural_consensus_violatio Ok(()) } + +/// When a `Safe` payload arrives while its parent is not yet in the engine tree, +/// `EngineApiTreeHandler` converts it via `convert_payload_to_block`, buffers the +/// `SealedBlock`, and later validates it via `MorphTreeEngineValidator::validate_block` +/// once the parent connects (`try_connect_buffered_blocks`). The `Safe` validation +/// mode must survive buffering (and not be clobbered by `validate_block`), otherwise +/// valid L1-derived blocks with future timestamps, >1/1024 gas-limit jumps, high base +/// fees, or oversized DA payloads would be rejected and poison `invalid_headers`. +#[tokio::test(flavor = "multi_thread")] +async fn buffered_safe_payload_preserves_validation_mode_when_parent_connects() -> eyre::Result<()> +{ + reth_tracing::init_test_tracing(); + use alloy_primitives::Address; + use alloy_rpc_types_engine::ForkchoiceState; + use jsonrpsee::core::client::ClientT; + use morph_node::test_utils::MorphTxBuilder; + use morph_payload_types::{MorphPayloadTypes, MorphPayloadValidationMode, SafeL2Data}; + use morph_primitives::MorphHeader; + use reth_node_api::PayloadTypes; + use reth_primitives_traits::SealedBlock; + use reth_provider::BlockReader; + + let (mut producer_nodes, wallet) = TestNodeBuilder::new() + .with_genesis_max_tx_payload_bytes(128) + .build() + .await?; + let producer = producer_nodes.pop().unwrap(); + let prod_client = producer.auth_server_handle().http_client(); + + let (mut follower_nodes, _) = TestNodeBuilder::new() + .with_genesis_max_tx_payload_bytes(128) + .build() + .await?; + let follower = follower_nodes.pop().unwrap(); + + let genesis = canonical_snapshot(&producer)?; + assert_eq!(genesis.hash, canonical_snapshot(&follower)?.hash); + + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + + // Build Block 1 (normal empty block) on `producer`. + let safe_b1 = SafeL2Data { + number: 1, + gas_limit: 30_000_000, + base_fee_per_gas: Some(1_000_000), + timestamp: genesis.number + 1, + transactions: vec![], + parent_hash: Some(genesis.hash), + }; + let h1: MorphHeader = prod_client + .request("engine_newSafeL2Block", (safe_b1,)) + .await?; + let b1_hash = h1.hash_slow(); + let sealed_b1 = SealedBlock::seal_slow( + producer + .inner + .provider + .block_by_number(1)? + .expect("block 1 in producer"), + ); + + // Build Block 2 on `producer` requiring `Safe` exemptions on every axis: + // - future timestamp (`now + 180`), + // - 2x gas_limit jump (`60_000_000`, > 1/1024 bound), + // - base_fee > MORPH_MAXIMUM_BASE_FEE (`15 Gwei`), + // - 256-byte L2 calldata (`> 128`-byte genesis DA payload limit). + let oversized_tx = MorphTxBuilder::new(wallet.chain_id, wallet.inner.clone(), 0) + .with_v1_eth_fee() + .with_to(Address::with_last_byte(0x42)) + .with_data(vec![0xcd; 256]) + .with_fees(25_000_000_000, 1_000_000_000) + .with_gas_limit(100_000) + .build_signed()?; + let safe_b2 = SafeL2Data { + number: 2, + gas_limit: 60_000_000, + base_fee_per_gas: Some(15_000_000_000), + timestamp: now + 180, + transactions: vec![oversized_tx], + parent_hash: Some(b1_hash), + }; + let h2: MorphHeader = prod_client + .request("engine_newSafeL2Block", (safe_b2,)) + .await?; + let b2_hash = h2.hash_slow(); + let sealed_b2 = SealedBlock::seal_slow( + producer + .inner + .provider + .block_by_number(2)? + .expect("block 2 in producer"), + ); + + // 1. Submit Block 2 (`Safe`) to `follower` BEFORE Block 1 so `follower` buffers it via + // `convert_payload_to_block` -> `self.state.buffer` (`Syncing`). + let follower_engine = &follower.inner.add_ons_handle.beacon_engine_handle; + let b2_safe_payload = MorphPayloadTypes::block_to_payload(sealed_b2, None) + .with_validation_mode(MorphPayloadValidationMode::Safe); + let b2_buffered_status = follower_engine.new_payload(b2_safe_payload).await?; + assert!( + b2_buffered_status.is_syncing(), + "disconnected Safe block 2 must buffer as Syncing: {b2_buffered_status:?}" + ); + + // 2. Now submit Block 1 (`Full`) to `follower`: `try_connect_buffered_blocks` immediately + // validates buffered Block 2 through `MorphTreeEngineValidator::validate_block`. + let b1_payload = MorphPayloadTypes::block_to_payload(sealed_b1, None); + let b1_status = follower_engine.new_payload(b1_payload).await?; + assert!( + b1_status.is_valid(), + "connecting parent block 1 must succeed: {b1_status:?}" + ); + + // 3. Forkchoice update to Block 2 must succeed (`Valid`), proving buffered Block 2 + // kept its `Safe` exemptions during `validate_block` and did not poison `invalid_headers`. + let fcu = follower_engine + .fork_choice_updated( + ForkchoiceState { + head_block_hash: b2_hash, + safe_block_hash: b2_hash, + finalized_block_hash: alloy_primitives::B256::ZERO, + }, + None, + ) + .await?; + assert!( + fcu.is_valid(), + "FCU to connected Safe block 2 must be Valid (not LinksToRejectedPayload): {fcu:?}" + ); + assert_eq!(canonical_snapshot(&follower)?.hash, b2_hash); + + Ok(()) +} diff --git a/crates/node/tests/it/morph_tx.rs b/crates/node/tests/it/morph_tx.rs index 2e75a179..6be1e665 100644 --- a/crates/node/tests/it/morph_tx.rs +++ b/crates/node/tests/it/morph_tx.rs @@ -1747,7 +1747,7 @@ async fn in_block_token_mutation_does_not_evict_morph_tx_valid_on_clean_parent() reth_tracing::init_test_tracing(); use morph_node::test_utils::L1MessageBuilder; use morph_payload_types::AssembleL2BlockV2Params; - use reth_transaction_pool::TransactionPool; + use reth_transaction_pool::{TransactionPool, TransactionPoolExt}; let registry = alloy_primitives::address!("5300000000000000000000000000000000000021"); let token_addr_slot: B256 = @@ -1851,7 +1851,14 @@ async fn in_block_token_mutation_does_not_evict_morph_tx_valid_on_clean_parent() tokio::time::sleep(super::helpers::POLL_INTERVAL).await; } - let block2 = super::helpers::assemble_l2_block_v2( + // 3a. Simulate the async txpool maintenance lag window right after FCU advanced the + // canonical head to `pool_candidate.hash` while `pool.block_info().last_seen_block_hash` + // still points at `genesis.hash`: eviction is suppressed for that lagged tick. + let mut lagged_info = node.inner.pool.block_info(); + lagged_info.last_seen_block_hash = genesis.hash; + node.inner.pool.set_block_info(lagged_info); + + let lagged_block2 = super::helpers::assemble_l2_block_v2( &node, AssembleL2BlockV2Params { parent_hash: pool_candidate.hash, @@ -1860,6 +1867,27 @@ async fn in_block_token_mutation_does_not_evict_morph_tx_valid_on_clean_parent() }, ) .await?; + assert!(lagged_block2.transactions.is_empty()); + assert!( + node.inner.pool.contains(&morph_tx_hash), + "pool maintenance lag window (pool last_seen_block_hash != parent_hash) must suppress eviction" + ); + + // 3b. Once `pool.block_info().last_seen_block_hash` catches up to `pool_candidate.hash`, + // the next canonical build evicts the genuinely broken MorphTx cleanly. + let mut synced_info = node.inner.pool.block_info(); + synced_info.last_seen_block_hash = pool_candidate.hash; + node.inner.pool.set_block_info(synced_info); + + let block2 = super::helpers::assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: pool_candidate.hash, + transactions: vec![], + timestamp: Some(4), + }, + ) + .await?; assert!(block2.transactions.is_empty()); assert!( !node.inner.pool.contains(&morph_tx_hash), diff --git a/crates/payload/builder/src/builder.rs b/crates/payload/builder/src/builder.rs index 2b4fb74f..b54e1e62 100644 --- a/crates/payload/builder/src/builder.rs +++ b/crates/payload/builder/src/builder.rs @@ -62,6 +62,23 @@ fn is_evictable_token_fee_error(error: &dyn InvalidTxError) -> bool { ) } +/// Returns true when `parent_hash` is still the current canonical head and the pool's +/// `last_seen_block_hash` has not moved onto a different head. +fn is_synchronized_canonical_parent( + client: &Client, + pool: &Pool, + parent_hash: B256, +) -> bool +where + Pool: TransactionPool, + Client: StateProviderFactory, +{ + let canonical_head_hash = client.block_hash_for_id(BlockId::latest()).ok().flatten(); + let pool_seen_hash = pool.block_info().last_seen_block_hash; + canonical_head_hash == Some(parent_hash) + && (pool_seen_hash.is_zero() || pool_seen_hash == parent_hash) +} + /// Validates MorphTx (0x7F) hardfork activation gates and structural field rules against /// the target block timestamp, matching `MorphConsensus::validate_block_pre_execution`. fn validate_morph_tx_for_block( @@ -254,14 +271,8 @@ where // AND the pool has not moved onto a different head: a non-canonical parent (e.g., // `assembleL2BlockV2` rebuilding on an older block before a token was activated) // must never remove transactions that are valid on the canonical chain. - let canonical_head_hash = self - .client - .block_hash_for_id(BlockId::latest()) - .ok() - .flatten(); - let pool_seen_hash = self.pool.block_info().last_seen_block_hash; - let can_evict_from_pool = canonical_head_hash == Some(parent_hash) - && (pool_seen_hash.is_zero() || pool_seen_hash == parent_hash); + let can_evict_from_pool = + is_synchronized_canonical_parent(&self.client, &self.pool, parent_hash); let ctx = MorphPayloadBuilderCtx { evm_config: self.evm_config.clone(), @@ -299,6 +310,7 @@ where build_payload_inner( cached_reads.as_db_mut(state), state_provider.as_ref(), + &self.client, &self.pool, ctx, best, @@ -641,7 +653,7 @@ impl MorphPayloadBuilderCtx { /// Returns `Ok(Some(()))` if the job was cancelled or breaker triggered, `Ok(None)` otherwise. /// Executed transaction bytes are appended to the provided vector. #[expect(clippy::too_many_arguments)] - fn execute_pool_transactions( + fn execute_pool_transactions( &self, builder: &mut impl BlockBuilder, state_provider: &(impl StateProvider + ?Sized), @@ -649,19 +661,23 @@ impl MorphPayloadBuilderCtx { info: &mut ExecutionInfo, executed_txs: &mut Vec, best_txs: BestTxs, + client: &Client, pool: &Pool, breaker: &PayloadBuildingBreaker, ) -> Result, PayloadBuilderError> where BestTxs: PayloadTransactions>, + Client: StateProviderFactory, Pool: TransactionPool>, { + let parent_hash = self.parent().hash(); self.execute_pool_transactions_with_evictor( builder, info, executed_txs, best_txs, breaker, + || is_synchronized_canonical_parent(client, pool, parent_hash), |tx| { let Ok(evm_env) = self .evm_config @@ -694,6 +710,7 @@ impl MorphPayloadBuilderCtx { executed_txs: &mut Vec, mut best_txs: BestTxs, breaker: &PayloadBuildingBreaker, + mut is_still_canonical_parent: impl FnMut() -> bool, mut confirm_eviction_on_clean_parent: impl FnMut(&Recovered) -> bool, mut evict_from_pool: impl FnMut(B256), ) -> Result, PayloadBuilderError> @@ -811,11 +828,16 @@ impl MorphPayloadBuilderCtx { "skipping invalid transaction and its descendants" ); best_txs.mark_invalid(tx.signer(), tx.nonce()); + // Re-check canonical/pool head alignment right before evicting so a + // canonical head advance or reorg while this build job was running + // cannot delete a transaction valid on the new head. if self.can_evict_from_pool && is_evictable_token_fee_error(error.as_ref()) && !info.executed_senders.contains(&tx.signer()) + && is_still_canonical_parent() && (info.transaction_count == 0 - || confirm_eviction_on_clean_parent(&tx)) + || (confirm_eviction_on_clean_parent(&tx) + && is_still_canonical_parent())) { tracing::debug!( target: "payload_builder", @@ -943,9 +965,10 @@ impl ExecutionInfo { } /// Builds the payload on top of the state. -fn build_payload_inner<'a, DB, BestTxs, Pool>( +fn build_payload_inner<'a, DB, BestTxs, Client, Pool>( db: DB, state_provider: &(impl StateProvider + ?Sized), + client: &Client, pool: &Pool, ctx: MorphPayloadBuilderCtx, best: impl FnOnce(BestTransactionsAttributes) -> BestTxs + Send + Sync + 'a, @@ -954,6 +977,7 @@ fn build_payload_inner<'a, DB, BestTxs, Pool>( where DB: Database, BestTxs: PayloadTransactions> + 'a, + Client: StateProviderFactory, Pool: TransactionPool>, { let build_started = Instant::now(); @@ -1043,6 +1067,7 @@ where &mut info, &mut executed_txs, best_txs, + client, pool, &breaker, )? @@ -1928,6 +1953,7 @@ mod tests { &mut executed_txs, best_txs, &breaker, + || true, |_| true, |hash| evicted.push(hash), ) @@ -2147,6 +2173,7 @@ mod tests { &mut executed_txs, best_txs, &breaker, + || true, |_| true, |hash| evicted.push(hash), ) @@ -2239,6 +2266,7 @@ mod tests { marked_invalid: Vec::new(), }, &breaker, + || panic!("live canonical recheck should not run when can_evict_from_pool is false"), |_| panic!("clean-parent check should not run when can_evict_from_pool is false"), |hash| evicted.push(hash), ) @@ -2286,6 +2314,7 @@ mod tests { marked_invalid: Vec::new(), }, &breaker, + || true, |tx| *tx.tx_hash() == h_broken_on_parent, |hash| evicted.push(hash), ) @@ -2339,6 +2368,7 @@ mod tests { marked_invalid: Vec::new(), }, &breaker, + || true, |_| true, |hash| evicted.push(hash), ) @@ -2347,6 +2377,79 @@ mod tests { evicted.is_empty(), "sender with executed supplied L1 message in block must not be evicted" ); + + // 4. Mid-build canonical head advance / reorg (`can_evict_from_pool == true` at build + // start, but `is_still_canonical_parent` flips to `false` before or during the + // clean-parent check): must suppress global pool eviction in both cases. + let sender_race_zero = Address::repeat_byte(0x40); + let (h_race_zero, tx_race_zero) = make_morph_tx(sender_race_zero, 0, 0xd1); + let mut outcomes = HashMap::new(); + outcomes.insert( + h_race_zero, + Err(MorphInvalidTransaction::TokenNotRegistered(99)), + ); + let mut builder = ScriptedBlockBuilder::new(outcomes); + let mut info = ExecutionInfo::default(); + let mut executed_txs = Vec::new(); + let ctx = test_ctx_with_timestamp_and_txs(1_800_000_000, vec![]); + let breaker = ctx.builder_config.breaker(30_000_000); + let mut evicted = Vec::new(); + ctx.execute_pool_transactions_with_evictor( + &mut builder, + &mut info, + &mut executed_txs, + ScriptedPoolTxs { + txs: VecDeque::from([tx_race_zero]), + marked_invalid: Vec::new(), + }, + &breaker, + || false, + |_| panic!("clean-parent check should not run once canonical head moved"), + |hash| evicted.push(hash), + ) + .expect("pool execution should complete"); + assert!( + evicted.is_empty(), + "canonical head advance mid-build must suppress pool eviction at transaction_count == 0" + ); + + // Also test head advancing *during* `confirm_eviction_on_clean_parent` (`transaction_count > 0`): + let sender_prev = Address::repeat_byte(0x41); + let sender_race_mid = Address::repeat_byte(0x42); + let (h_prev, tx_prev) = make_eth_tx(sender_prev, 0, 0xd2); + let (h_race_mid, tx_race_mid) = make_morph_tx(sender_race_mid, 0, 0xd3); + let mut outcomes = HashMap::new(); + outcomes.insert(h_prev, Ok(21_000)); + outcomes.insert(h_race_mid, Err(MorphInvalidTransaction::TokenNotActive(99))); + let mut builder = ScriptedBlockBuilder::new(outcomes); + let mut info = ExecutionInfo::default(); + let mut executed_txs = Vec::new(); + let mut canonical_checks = 0usize; + let mut evicted = Vec::new(); + ctx.execute_pool_transactions_with_evictor( + &mut builder, + &mut info, + &mut executed_txs, + ScriptedPoolTxs { + txs: VecDeque::from([tx_prev, tx_race_mid]), + marked_invalid: Vec::new(), + }, + &breaker, + || { + canonical_checks += 1; + // First check (before clean-parent EVM) sees head unchanged; second check + // (after clean-parent EVM) sees head moved to a newer block. + canonical_checks == 1 + }, + |_| true, + |hash| evicted.push(hash), + ) + .expect("pool execution should complete"); + assert_eq!(canonical_checks, 2); + assert!( + evicted.is_empty(), + "canonical head advance during clean-parent recheck must suppress pool eviction" + ); } #[test] diff --git a/crates/payload/types/src/lib.rs b/crates/payload/types/src/lib.rs index df353f96..736026a3 100644 --- a/crates/payload/types/src/lib.rs +++ b/crates/payload/types/src/lib.rs @@ -56,7 +56,7 @@ pub use safe_l2_data::SafeL2Data; pub struct MorphPayloadTypes; /// Consensus validation mode applied when importing a [`MorphExecutionData`] payload. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)] pub enum MorphPayloadValidationMode { /// Standard untrusted payload validation (`VerifyHeader` + `ValidateBody` + execution). #[default] @@ -133,7 +133,10 @@ pub struct MorphExecutionData { #[serde(default, skip_serializing_if = "Option::is_none")] pub expected_withdraw_trie_root: Option, /// Validation mode governing consensus header/body exemptions. - #[serde(default)] + /// + /// Strictly internal in-process metadata (`#[serde(skip)]`) so external JSON/serde + /// payloads can never deserialize `LocallyBuilt` or `Safe`. + #[serde(skip)] pub validation_mode: MorphPayloadValidationMode, } @@ -354,6 +357,29 @@ mod tests { assert_eq!(safe.validation_mode, MorphPayloadValidationMode::Safe); } + #[test] + fn test_execution_data_serde_skips_and_ignores_validation_mode() { + let block = Arc::new(create_test_block()); + let safe = + MorphExecutionData::new(block).with_validation_mode(MorphPayloadValidationMode::Safe); + + let mut json_val = serde_json::to_value(&safe).expect("serialize MorphExecutionData"); + assert!( + json_val.get("validation_mode").is_none() && json_val.get("validationMode").is_none(), + "validation_mode must never be serialized" + ); + + json_val["validation_mode"] = serde_json::json!("Safe"); + json_val["validationMode"] = serde_json::json!("LocallyBuilt"); + let decoded: MorphExecutionData = + serde_json::from_value(json_val).expect("deserialize MorphExecutionData"); + assert_eq!( + decoded.validation_mode, + MorphPayloadValidationMode::Full, + "untrusted serde input must never set LocallyBuilt or Safe" + ); + } + #[test] fn test_tree_header_cache_insert_get_and_bounded_eviction() { let cache = TreeHeaderCache::new(); From aa371824a5663e5fb9201fa1c357a0320f6f697c Mon Sep 17 00:00:00 2001 From: panos-xyz Date: Mon, 30 Nov 2026 16:05:23 +0800 Subject: [PATCH 4/4] refactor(sequencer,engine,validator,builder): simplify PR #240 audit fixes Drops over-engineered caches, duplicate L1 validation loops, and hot-path EVM re-execution while preserving all 8 v1.5.0 audit fixes (M-C02, M-H07..H10, M-M10..M12): - M-M12 (evm, payload/builder): drop MorphEvm::validate_only and clean-parent EVM re-execution on pool eviction (avoids doubling gas/DB cost on malicious token-fee failures); keep is_synchronized_canonical_parent and supplied+pool executed_senders guards. - M-H07 WTR (node/validator, engine-api): drop KnownWithdrawTrieRootCache, VerifiedBlocksCache, tree-ancestor WTR walking, and historical MDBX state reads in convert_payload_to_block; keep single-Mutex WithdrawTrieRootCache (no dashmap) and stack-passed expectation on validate_payload. - L1 index dedup & tree headers (consensus, node/validator, engine-api, payload/types, add_ons): consolidate parent-aware and unhashed next_l1_msg_index checks into MorphConsensus (removing the duplicate engine-api copy), and keep tree_headers private to MorphTreeEngineValidator so morph-payload-types and add_ons stay clean. - Validation modes (payload/types, consensus, node/validator, engine-api): replace 3-state MorphPayloadValidationMode (Full/LocallyBuilt/Safe) with internal #[serde(skip)] is_safe: bool for L1-derived NewSafeL2Block exemptions only, sharing a single BoundedFifoMap helper inside validator.rs. --- crates/consensus/src/validation.rs | 131 +++- crates/engine-api/src/builder.rs | 238 +------ crates/evm/src/evm.rs | 15 - crates/node/src/add_ons.rs | 11 +- crates/node/src/validator.rs | 666 +++++------------- crates/node/tests/it/engine.rs | 40 +- .../node/tests/it/invalid_payload_recovery.rs | 470 +----------- crates/node/tests/it/morph_tx.rs | 114 +-- crates/payload/builder/src/builder.rs | 170 +---- crates/payload/types/src/lib.rs | 172 +---- 10 files changed, 441 insertions(+), 1586 deletions(-) diff --git a/crates/consensus/src/validation.rs b/crates/consensus/src/validation.rs index b9c5e52d..c5a57ef3 100644 --- a/crates/consensus/src/validation.rs +++ b/crates/consensus/src/validation.rs @@ -196,23 +196,119 @@ impl MorphConsensus { Ok(()) } - /// Validates parent-header continuity and timestamp progression for locally assembled blocks - /// (exempting the 1/1024 gas-limit bound). - pub fn validate_header_against_parent_locally_built( + /// Validates cross-block L1 message queue invariants against `parent`: + /// + /// 1. Across **all** hardforks (pre-Jade and post-Jade), if the block contains leading L1 + /// messages, the first message's `queue_index` must be `>= parent.next_l1_msg_index`. + /// Violations are cross-block replays and return cacheable + /// [`MorphConsensusError::L1MessagesNotInOrder`] (since transactions are committed by the + /// block hash). Forward skips (`first_queue_index > parent.next_l1_msg_index`) are allowed. + /// 2. From Jade onward, `header.next_l1_msg_index` must equal the exact derived index + /// (`parent.next_l1_msg_index` when no L1 messages are present, or `last_queue_index + 1` + /// otherwise). Mismatches return transient [`MorphConsensusError::InvalidNextL1MessageIndex`] + /// so an unhashed header field cannot poison `invalid_headers`. + pub fn validate_l1_msg_index_against_parent( &self, - header: &SealedHeader, - parent: &SealedHeader, + block: &SealedBlock, + parent: &MorphHeader, ) -> Result<(), ConsensusError> { - self.validate_header_against_parent_structural(header, parent)?; - let is_emerald = self + let mut expected = parent.next_l1_msg_index; + let mut first_l1_msg = true; + for tx in block.body().transactions() { + if !tx.is_l1_msg() { + break; + } + let queue_index = tx.queue_index().ok_or_else(|| { + ConsensusError::msg("L1 message transaction is missing queue index") + })?; + if first_l1_msg { + first_l1_msg = false; + if queue_index < parent.next_l1_msg_index { + return Err(ConsensusError::other( + MorphConsensusError::L1MessagesNotInOrder { + expected: parent.next_l1_msg_index, + actual: queue_index, + }, + )); + } + } + expected = queue_index.checked_add(1).ok_or_else(|| { + ConsensusError::other(MorphConsensusError::InvalidNextL1MessageIndex { + expected: u64::MAX, + actual: block.header().next_l1_msg_index, + }) + })?; + } + + if !self .chain_spec - .is_emerald_active_at_timestamp(header.timestamp()); - validate_against_parent_timestamp(header.header(), parent.header(), is_emerald) + .is_jade_active_at_timestamp(block.header().timestamp()) + { + return Ok(()); + } + + let actual = block.header().next_l1_msg_index; + if actual != expected { + return Err(ConsensusError::other( + MorphConsensusError::InvalidNextL1MessageIndex { expected, actual }, + )); + } + Ok(()) + } + + /// Validates only the unhashed `header.next_l1_msg_index` field against `parent`. + /// + /// Called during payload conversion so `AlreadySeen` hits cannot bypass an unhashed + /// `next_l1_msg_index` tamper without poisoning `invalid_headers`. Malformed or replayed L1 + /// messages are committed by the block hash and left to full validation. + pub fn validate_unhashed_next_l1_msg_index( + &self, + block: &SealedBlock, + parent: &MorphHeader, + ) -> Result<(), MorphConsensusError> { + let mut expected = parent.next_l1_msg_index; + let mut first_l1_msg = true; + for tx in block.body().transactions() { + if !tx.is_l1_msg() { + break; + } + let Some(queue_index) = tx.queue_index() else { + return Ok(()); + }; + if first_l1_msg { + first_l1_msg = false; + if queue_index < parent.next_l1_msg_index { + return Ok(()); + } + } + expected = queue_index.checked_add(1).ok_or( + MorphConsensusError::InvalidNextL1MessageIndex { + expected: u64::MAX, + actual: block.header().next_l1_msg_index, + }, + )?; + } + + let has_l1_msgs = !first_l1_msg; + let actual = block.header().next_l1_msg_index; + let is_jade = self + .chain_spec + .is_jade_active_at_timestamp(block.header().timestamp()); + let invalid = if is_jade { + actual != expected + } else { + has_l1_msgs && actual < expected + }; + if invalid { + return Err(MorphConsensusError::InvalidNextL1MessageIndex { expected, actual }); + } + + Ok(()) } /// Validates pre-execution body invariants except the local per-block DA byte limit - /// (`max_tx_payload_bytes_per_block`), matching morph-geth's `verified` and `NewSafeL2Block` - /// (`safe = true`) exemptions. + /// (`max_tx_payload_bytes_per_block`), matching morph-geth's `NewSafeL2Block` (`safe = true`) + /// exemption. pub fn validate_block_pre_execution_without_da_limit( &self, block: &SealedBlock, @@ -2539,13 +2635,13 @@ mod tests { } #[test] - fn test_structural_and_locally_built_exemptions_preserve_hard_invariants() { + fn test_structural_exemptions_preserve_hard_invariants() { let consensus = MorphConsensus::new(create_test_chainspec_with_payload_limit(64)); let parent = SealedHeader::seal_slow(create_valid_morph_header(1000, 30_000_000, 100)); // Future timestamp, doubled gas_limit (> 1/1024), and base_fee > MORPH_MAXIMUM_BASE_FEE: - // full validation rejects each, while structural / locally-built exempts the intended checks. + // full validation rejects each, while structural (Safe) validation exempts them. let future_ts = u64::MAX - 10; let mut child = create_valid_morph_header(future_ts, 60_000_000, 101); child.inner.parent_hash = parent.hash(); @@ -2562,23 +2658,18 @@ mod tests { consensus.validate_header_against_parent(&child_sealed, &parent), Err(ConsensusError::GasLimitInvalidIncrease { .. }) )); - assert!( - consensus - .validate_header_against_parent_locally_built(&child_sealed, &parent) - .is_ok() - ); assert!( consensus .validate_header_against_parent_structural(&child_sealed, &parent) .is_ok() ); - // Timestamp behind parent: rejected for LocallyBuilt, exempted for Safe (structural). + // Timestamp behind parent: rejected by full validation, exempted for Safe (structural). let mut past_child = child; past_child.inner.timestamp = 999; let past_sealed = SealedHeader::seal_slow(past_child); assert!(matches!( - consensus.validate_header_against_parent_locally_built(&past_sealed, &parent), + consensus.validate_header_against_parent(&past_sealed, &parent), Err(ConsensusError::TimestampIsInPast { .. }) )); assert!( diff --git a/crates/engine-api/src/builder.rs b/crates/engine-api/src/builder.rs index 8a13f073..0c93260c 100644 --- a/crates/engine-api/src/builder.rs +++ b/crates/engine-api/src/builder.rs @@ -14,26 +14,16 @@ use alloy_rpc_types_engine::{PayloadAttributes, PayloadStatus, PayloadStatusEnum use morph_chainspec::{MorphChainSpec, MorphHardforks}; use morph_payload_types::{ AssembleL2BlockParams, AssembleL2BlockV2Params, ExecutableL2Data, GenericResponse, - MorphBuiltPayload, MorphExecutionData, MorphPayloadTypes, MorphPayloadValidationMode, - SafeL2Data, TreeHeaderCache, + MorphBuiltPayload, MorphExecutionData, MorphPayloadTypes, SafeL2Data, }; use morph_primitives::{Block, BlockBody, MorphHeader, MorphTxEnvelope}; -use parking_lot::{Mutex, RwLock}; +use parking_lot::RwLock; use reth_payload_builder::{BuildNewPayload, PayloadBuilderHandle}; #[cfg(test)] use reth_primitives_traits::RecoveredBlock; use reth_primitives_traits::{FastInstant as Instant, SealedBlock, SealedHeader}; use reth_provider::{BlockNumReader, BlockReaderIdExt, CanonChainTracker, HeaderProvider}; -use std::{ - collections::{HashMap, VecDeque}, - sync::Arc, -}; - -#[derive(Debug, Default)] -struct VerifiedBlocksCache { - entries: HashMap, - order: VecDeque, -} +use std::sync::Arc; // ============================================================================= // Real Implementation @@ -60,15 +50,6 @@ pub struct RealMorphL2EngineApi { /// Tracks L1-derived finalized block tags for FCU updates. block_tag_tracker: Arc, - /// Shared cache of unpersisted in-memory `tree_state` headers populated by the - /// engine tree validator. - tree_headers: Arc, - - /// Locally assembled block hashes mapped to their computed `withdraw_trie_root`, - /// mirroring morph-geth's `api.verified` cache for `AssembleL2Block(V2)` -> - /// `ValidateL2Block` / `NewL2Block(V2)`. - verified_blocks: Mutex, - /// Serializes payload builds to prevent concurrent deterministic `PayloadId` /// collisions in reth's `PayloadBuilderService`. build_lock: tokio::sync::Mutex<()>, @@ -181,8 +162,6 @@ fn payload_timestamp( } impl RealMorphL2EngineApi { - const MAX_VERIFIED_BLOCKS: usize = 1024; - /// Creates a new [`RealMorphL2EngineApi`]. pub fn new( provider: Provider, @@ -197,46 +176,12 @@ impl RealMorphL2EngineApi { chain_spec, engine_handle, block_tag_tracker, - tree_headers: Arc::new(TreeHeaderCache::new()), - verified_blocks: Mutex::new(VerifiedBlocksCache::default()), build_lock: tokio::sync::Mutex::new(()), fcu_lock: tokio::sync::Mutex::new(()), metrics: MorphEngineApiMetrics::default(), } } - /// Attaches a shared [`TreeHeaderCache`] so unpersisted in-memory `tree_state` - /// headers are visible during parent lookups. - pub fn with_tree_headers(mut self, tree_headers: Arc) -> Self { - self.tree_headers = tree_headers; - self - } - - fn record_verified_block(&self, block_hash: B256, withdraw_trie_root: B256) { - let mut cache = self.verified_blocks.lock(); - let is_new = cache - .entries - .insert(block_hash, withdraw_trie_root) - .is_none(); - if is_new { - cache.order.push_back(block_hash); - while cache.entries.len() > Self::MAX_VERIFIED_BLOCKS { - let Some(evicted) = cache.order.pop_front() else { - break; - }; - cache.entries.remove(&evicted); - } - } - } - - fn verified_withdraw_trie_root(&self, block_hash: B256) -> Option { - self.verified_blocks - .lock() - .entries - .get(&block_hash) - .copied() - } - /// Updates `head_block_timegap_seconds` gauge after a successful block import. fn record_head_metrics(&self, block_timestamp: u64) { let now_secs = std::time::SystemTime::now() @@ -292,7 +237,6 @@ where self.metrics.assemble_l2_block_failures_total.increment(1); })?; let executable_data = built_payload.executable_data; - self.record_verified_block(executable_data.hash, executable_data.withdraw_trie_root); tracing::debug!( target: "morph::engine", @@ -316,7 +260,9 @@ where // looked up by hash and need not be the canonical head — that is the point of V2 // (the sequencer can build on a parent that diverges from its current head). let parent = self - .lookup_sealed_header_by_hash(parent_hash)? + .provider + .sealed_header_by_hash(parent_hash) + .map_err(|e| MorphEngineApiError::Database(e.to_string()))? .ok_or_else(|| { MorphEngineApiError::Internal(format!("parent block not found: {parent_hash}")) })?; @@ -344,7 +290,6 @@ where self.metrics.assemble_l2_block_failures_total.increment(1); })?; let executable_data = built_payload.executable_data; - self.record_verified_block(executable_data.hash, executable_data.withdraw_trie_root); tracing::debug!( target: "morph::engine", @@ -406,7 +351,7 @@ where } // 2. Convert and forward to reth engine tree (`newPayload` path). - let (mut payload, _) = match self.execution_payload_from_executable_data(&data) { + let (payload, _) = match self.execution_payload_from_executable_data(&data) { Ok(v) => v, Err(err) => { tracing::warn!( @@ -423,44 +368,6 @@ where } }; - // 2b. Validate `next_l1_message_index` before calling `new_payload`: the field is not - // covered by the block hash, so an `AlreadySeen` hit in the engine tree would - // otherwise return `Valid` without re-running `validate_payload`. - if let Err(err) = self.validate_next_l1_message_index(payload.block.as_ref()) { - tracing::warn!( - target: "morph::engine", - block_hash = %data.hash, - error = %err, - "invalid next_l1_message_index during validate_l2_block" - ); - self.metrics.validate_l2_block_failures_total.increment(1); - self.metrics - .validate_l2_block_duration_seconds - .record(validate_started.elapsed()); - return Ok(GenericResponse { success: false }); - } - - // 2c. Match morph-geth's `isVerified` branch: if this exact block hash was assembled - // locally, cross-check any non-zero `withdraw_trie_root` immediately and mark the - // payload `LocallyBuilt` so empty/reorg builds do not fail wall-clock checks. - if let Some(actual_wtr) = self.verified_withdraw_trie_root(payload.block.hash()) { - if !data.withdraw_trie_root.is_zero() && data.withdraw_trie_root != actual_wtr { - tracing::warn!( - target: "morph::engine", - block_hash = %data.hash, - expected = %actual_wtr, - actual = %data.withdraw_trie_root, - "validate_l2_block failed: wrong withdraw_trie_root on locally verified block" - ); - self.metrics.validate_l2_block_failures_total.increment(1); - self.metrics - .validate_l2_block_duration_seconds - .record(validate_started.elapsed()); - return Ok(GenericResponse { success: false }); - } - payload = payload.with_validation_mode(MorphPayloadValidationMode::LocallyBuilt); - } - let status = match self.engine_handle.new_payload(payload).await { Ok(status) => status, Err(err) => { @@ -564,7 +471,7 @@ where let block_hash = data.hash; let block_number = data.number; let block_timestamp = data.timestamp; - self.import_l2_block_via_engine(data, B256::ZERO, MorphPayloadValidationMode::Full) + self.import_l2_block_via_engine(data, B256::ZERO, false) .await .inspect_err(|_| { self.metrics.new_l2_block_failures_total.increment(1); @@ -604,7 +511,9 @@ where // chain onto this block. This is the centralized-sequencer import path, // where the sequencer may rebuild and replace recent blocks. let parent = self - .lookup_sealed_header_by_hash(data.parent_hash)? + .provider + .sealed_header_by_hash(data.parent_hash) + .map_err(|e| MorphEngineApiError::Database(e.to_string()))? .ok_or_else(|| { MorphEngineApiError::Internal(format!( "parent block not found: {}", @@ -630,7 +539,7 @@ where // FCU advances or reorgs the canonical head onto data.hash. let block_timestamp = data.timestamp; let header = self - .import_l2_block_via_engine(data, B256::ZERO, MorphPayloadValidationMode::Full) + .import_l2_block_via_engine(data, B256::ZERO, false) .await .inspect_err(|_| { self.metrics.new_l2_block_failures_total.increment(1); @@ -697,16 +606,11 @@ where let block_hash = executable_data.hash; // 3. Import the block through reth engine tree, marking the imported block safe - // in the same FCU. Pass `MorphPayloadValidationMode::Safe` to match morph-geth's - // `NewSafeL2Block` (`safe = true`), exempting `VerifyHeader` and `ValidateBody` - // DA byte-limit checks so follower clock skew or L1 batch parameter updates - // cannot stall L1 derivation. + // in the same FCU. Pass `is_safe = true` to match morph-geth's `NewSafeL2Block` + // (`safe = true`), exempting `VerifyHeader` and `ValidateBody` DA byte-limit checks + // so follower clock skew or L1 batch parameter updates cannot stall L1 derivation. let header = self - .import_l2_block_via_engine( - executable_data, - block_hash, - MorphPayloadValidationMode::Safe, - ) + .import_l2_block_via_engine(executable_data, block_hash, true) .await .inspect_err(|_| { self.metrics.new_safe_l2_block_failures_total.increment(1); @@ -845,23 +749,6 @@ where } impl RealMorphL2EngineApi { - /// Looks up a sealed header by hash, checking the shared in-memory `tree_state` - /// header cache first before falling back to `self.provider` (canonical memory + DB). - fn lookup_sealed_header_by_hash( - &self, - hash: B256, - ) -> EngineApiResult>> - where - Provider: HeaderProvider
, - { - if let Some(header) = self.tree_headers.get(&hash) { - return Ok(Some(header)); - } - self.provider - .sealed_header_by_hash(hash) - .map_err(|e| MorphEngineApiError::Database(e.to_string())) - } - /// Looks up a sealed header by hash and verifies that it belongs to the current /// canonical chain. /// @@ -929,7 +816,9 @@ impl RealMorphL2EngineApi { let (parent_number, parent_hash, parent_timestamp) = match parent_override { Some(parent_hash) => { let parent = self - .lookup_sealed_header_by_hash(parent_hash)? + .provider + .sealed_header_by_hash(parent_hash) + .map_err(|e| MorphEngineApiError::Database(e.to_string()))? .ok_or_else(|| { MorphEngineApiError::Internal(format!( "parent block not found: {parent_hash}" @@ -1036,103 +925,22 @@ impl RealMorphL2EngineApi { }) } - /// Validates the unhashed `next_l1_message_index` header field against the parent header - /// and the block's leading L1 messages before calling `engine_handle.new_payload`. - /// - /// Because `next_l1_msg_index` is not part of the block hash, reth's `AlreadySeen` - /// short-circuit would otherwise return `Valid` for a tampered `next_l1_message_index` - /// whenever the block hash is already in `tree_state` (e.g., pre-inserted by - /// `assembleL2Block`) or in the DB. Checking it here rejects the tampered request - /// without invoking `new_payload` (so `invalid_headers` is never poisoned). - fn validate_next_l1_message_index(&self, block: &SealedBlock) -> EngineApiResult<()> - where - Provider: HeaderProvider
, - { - let Some(parent) = self.lookup_sealed_header_by_hash(block.parent_hash())? else { - return Ok(()); - }; - - let mut expected = parent.next_l1_msg_index; - let mut first_l1_msg = true; - for tx in block.body().transactions() { - if !tx.is_l1_msg() { - break; - } - let Some(queue_index) = tx.queue_index() else { - // Malformed L1 message is committed by the block hash; let the engine - // validator reject and cache it. - return Ok(()); - }; - if first_l1_msg { - first_l1_msg = false; - if queue_index < parent.next_l1_msg_index { - // Cross-block L1 replay is committed by the block hash; let the engine - // validator reject and cache it with `L1MessagesNotInOrder`. - return Ok(()); - } - } - expected = match queue_index.checked_add(1) { - Some(next) => next, - None => { - return Err(MorphEngineApiError::ValidationFailed(format!( - "invalid block.NextL1MsgIndex: expected {}, got {}", - u64::MAX, - block.header().next_l1_msg_index - ))); - } - }; - } - - let has_l1_msgs = !first_l1_msg; - let actual = block.header().next_l1_msg_index; - let is_jade = self - .chain_spec - .is_jade_active_at_timestamp(block.header().timestamp()); - // Pre-Jade historical blocks without L1 messages are exempt from parent-index - // comparison, matching morph-geth `blockchain_l2.go` and - // `MorphTreeEngineValidator::validate_l1_msg_index_against_parent`. - let invalid = if is_jade { - actual != expected - } else { - has_l1_msgs && actual < expected - }; - if invalid { - return Err(MorphEngineApiError::ValidationFailed(format!( - "invalid block.NextL1MsgIndex: expected {expected}, got {actual}" - ))); - } - - Ok(()) - } - async fn import_l2_block_via_engine( &self, data: ExecutableL2Data, safe_block_hash: B256, - mut validation_mode: MorphPayloadValidationMode, + is_safe: bool, ) -> EngineApiResult where Provider: HeaderProvider
+ BlockNumReader + CanonChainTracker
, { - let (payload, header) = self.execution_payload_from_executable_data(&data)?; - self.validate_next_l1_message_index(payload.block.as_ref())?; - - if validation_mode == MorphPayloadValidationMode::Full - && let Some(actual_wtr) = self.verified_withdraw_trie_root(payload.block.hash()) - { - if !data.withdraw_trie_root.is_zero() && data.withdraw_trie_root != actual_wtr { - return Err(MorphEngineApiError::ValidationFailed(format!( - "withdraw trie root mismatch: expected {}, got {}", - data.withdraw_trie_root, actual_wtr - ))); - } - validation_mode = MorphPayloadValidationMode::LocallyBuilt; + let (mut payload, header) = self.execution_payload_from_executable_data(&data)?; + if is_safe { + payload = payload.with_safe_validation(); } - let payload = payload.with_validation_mode(validation_mode); - let payload_status = self .engine_handle .new_payload(payload) diff --git a/crates/evm/src/evm.rs b/crates/evm/src/evm.rs index 8c4ee123..32a67f87 100644 --- a/crates/evm/src/evm.rs +++ b/crates/evm/src/evm.rs @@ -113,21 +113,6 @@ impl MorphEvm { pub fn cached_l1_data_fee(&self) -> alloy_primitives::U256 { self.inner.cached_l1_data_fee() } - - /// Runs only the handler's pre-execution validation and fee-deduction phase - /// (including call-mode alt-token `balanceOf` and `transfer`), without executing - /// the main transaction body. - pub fn validate_only( - &mut self, - tx: MorphTxEnv, - ) -> Result<(), EVMError> { - use alloy_evm::revm::{context::ContextSetters, handler::Handler}; - - self.inner.inner.ctx.set_tx(tx); - morph_revm::handler::MorphEvmHandler::new() - .validate(&mut self.inner) - .map(|_| ()) - } } impl Deref for MorphEvm diff --git a/crates/node/src/add_ons.rs b/crates/node/src/add_ons.rs index ce99df16..b3446bfe 100644 --- a/crates/node/src/add_ons.rs +++ b/crates/node/src/add_ons.rs @@ -61,9 +61,6 @@ pub struct MorphAddOns< /// Held as one unit because the limit is only ever enforced by the RPC that this storage /// installs; there is no way to configure one without the other. proof_history: Option<(MorphProofsStorage>, usize)>, - /// Shared cache of validated in-memory `tree_state` headers populated by the engine tree - /// validator and read by `RealMorphL2EngineApi`. - tree_headers: Arc, } impl MorphAddOns, MorphEthApiBuilder> @@ -76,18 +73,16 @@ where /// Creates a new [`MorphAddOns`] with default configuration. pub fn new() -> Self { let pvb = MorphEngineValidatorBuilder::default(); - let tree_headers = Arc::new(morph_payload_types::TreeHeaderCache::new()); Self { inner: RpcAddOns::new( MorphEthApiBuilder::default(), pvb.clone(), NoopEngineApiBuilder::default(), - MorphTreeEngineValidatorBuilder::new(pvb).with_tree_headers(tree_headers.clone()), + MorphTreeEngineValidatorBuilder::new(pvb), Identity::default(), Identity::default(), ), proof_history: None, - tree_headers, } } @@ -206,7 +201,6 @@ where let morph_rpc_ctx = MorphRpc::new(reference_index_handle, provider.clone()); let reference_rpc_handler = MorphRpcHandler::new(morph_rpc_ctx); let proof_history = self.proof_history; - let tree_headers = self.tree_headers; // Use launch_add_ons_with to register custom Engine API and eth_config self.inner @@ -292,8 +286,7 @@ where chain_spec, beacon_engine_handle, block_tag_tracker, - ) - .with_tree_headers(tree_headers); + ); // Create the RPC handler let handler = morph_engine_api::MorphL2EngineRpcHandler::new(engine_api); diff --git a/crates/node/src/validator.rs b/crates/node/src/validator.rs index 4c963b0b..713f615c 100644 --- a/crates/node/src/validator.rs +++ b/crates/node/src/validator.rs @@ -2,17 +2,13 @@ use crate::MorphNode; use alloy_consensus::BlockHeader; -use alloy_primitives::B256; -#[cfg(test)] -use alloy_primitives::keccak256; +use alloy_primitives::{B256, keccak256}; use morph_chainspec::{ L2_MESSAGE_QUEUE_ADDRESS, L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT, MorphChainSpec, MorphHardforks, }; use morph_consensus::{MorphConsensus, MorphConsensusError}; -use morph_payload_types::{ - MorphExecutionData, MorphPayloadTypes, MorphPayloadValidationMode, TreeHeaderCache, -}; +use morph_payload_types::{MorphExecutionData, MorphPayloadTypes}; use morph_primitives::{ Block, BlockBody, MorphHeader, MorphPrimitives, MorphReceipt, MorphTxEnvelope, }; @@ -32,11 +28,7 @@ use reth_engine_tree::tree::{ }, }; use reth_errors::{ConsensusError, ProviderError, ProviderResult}; -use reth_evm::{ - ConfigureEvm, - block::BlockExecutionResult, - revm::{context::Block as _, database::BundleState}, -}; +use reth_evm::{ConfigureEvm, block::BlockExecutionResult, revm::context::Block as _}; use reth_node_api::{ AddOnsContext, FullNodeComponents, InvalidPayloadAttributesError, NewPayloadError, NodeTypes, PayloadAttributes, PayloadTypes, PayloadValidator, @@ -89,24 +81,15 @@ where #[derive(Debug, Clone)] pub struct MorphTreeEngineValidatorBuilder { payload_validator_builder: PVB, - tree_headers: Arc, } impl MorphTreeEngineValidatorBuilder { /// Creates a new instance with the given payload validator builder. - pub fn new(payload_validator_builder: PVB) -> Self { + pub const fn new(payload_validator_builder: PVB) -> Self { Self { payload_validator_builder, - tree_headers: Arc::new(TreeHeaderCache::new()), } } - - /// Attaches a shared [`TreeHeaderCache`] so the custom Morph L2 Engine API can - /// resolve unpersisted in-memory `tree_state` headers. - pub fn with_tree_headers(mut self, tree_headers: Arc) -> Self { - self.tree_headers = tree_headers; - self - } } impl Default for MorphTreeEngineValidatorBuilder @@ -126,7 +109,7 @@ where <::Payload as PayloadTypes>::ExecutionData, >, >, - Node::Provider: ChainSpecProvider + StateProviderFactory, + Node::Provider: ChainSpecProvider, PVB: PayloadValidatorBuilder, { type EngineValidator = MorphTreeEngineValidator; @@ -154,7 +137,7 @@ where let consensus: Arc> = engine_consensus.clone(); let state_root_strategy: Arc< dyn StateRootStrategy, - > = Arc::new(MorphStateRootStrategy::new(chain_spec.clone())); + > = Arc::new(MorphStateRootStrategy::new(chain_spec)); let tree_config = strict_morph_tree_config(tree_config); let txpool_prewarming = tree_config.txpool_prewarming(); let mut validator = BasicEngineValidator::new( @@ -177,10 +160,8 @@ where Ok(MorphTreeEngineValidator::new( validator, provider, - chain_spec, engine_consensus, post_execution_validator, - self.tree_headers, )) } } @@ -246,28 +227,72 @@ fn strict_morph_tree_config(tree_config: reth_node_api::TreeConfig) -> reth_node tree_config.with_skip_state_root(false) } -#[derive(Debug, Default)] -struct ValidationModeCache { - entries: HashMap, - order: VecDeque, +/// Bounded FIFO map used for validator-internal in-memory caches. +#[derive(Debug)] +struct BoundedFifoMap { + entries: HashMap, + order: VecDeque, + max_entries: usize, } -/// Engine-tree consensus adapter that applies [`MorphPayloadValidationMode`] exemptions -/// per block hash when `BasicEngineValidator` validates locally built or L1-derived safe -/// payloads, while defaulting to full [`MorphConsensus`] validation for all untrusted blocks. +impl BoundedFifoMap +where + K: Eq + std::hash::Hash + Copy, +{ + fn new(max_entries: usize) -> Self { + Self { + entries: HashMap::new(), + order: VecDeque::new(), + max_entries, + } + } + + fn insert(&mut self, key: K, value: V) { + let is_new = self.entries.insert(key, value).is_none(); + if is_new { + self.order.push_back(key); + while self.entries.len() > self.max_entries { + let Some(evicted) = self.order.pop_front() else { + break; + }; + self.entries.remove(&evicted); + } + } + } + + fn get(&self, key: &K) -> Option<&V> { + self.entries.get(key) + } + + fn contains_key(&self, key: &K) -> bool { + self.entries.contains_key(key) + } + + fn remove(&mut self, key: &K) -> Option { + let removed = self.entries.remove(key); + if removed.is_some() { + self.order.retain(|existing| existing != key); + } + removed + } +} + +/// Engine-tree consensus adapter that applies L1-derived safe-block (`engine_newSafeL2Block`) +/// exemptions per block hash when `BasicEngineValidator` validates safe payloads, while +/// enforcing full [`MorphConsensus`] validation for all untrusted blocks. #[derive(Debug)] struct MorphEngineConsensus { inner: MorphConsensus, - modes: Mutex, + safe_blocks: Mutex>, } impl MorphEngineConsensus { - const MAX_MODES: usize = 1024; + const MAX_SAFE_BLOCKS: usize = 1024; fn new(inner: MorphConsensus) -> Self { Self { inner, - modes: Mutex::new(ValidationModeCache::default()), + safe_blocks: Mutex::new(BoundedFifoMap::new(Self::MAX_SAFE_BLOCKS)), } } @@ -275,51 +300,23 @@ impl MorphEngineConsensus { &self.inner } - fn record_mode(&self, block_hash: B256, mode: MorphPayloadValidationMode) { - if mode == MorphPayloadValidationMode::Full { - // `Full` is the default when absent. Never delete or downgrade an existing - // `LocallyBuilt` or `Safe` entry: `BasicEngineValidator` runs - // `spawn_convert_and_validate` on a background thread, and buffered - // `Safe` / `LocallyBuilt` payloads later pass through `validate_block`. - return; - } - let mut cache = self.modes.lock(); - match cache.entries.get_mut(&block_hash) { - Some(existing) => { - if mode > *existing { - *existing = mode; - } - } - None => { - cache.entries.insert(block_hash, mode); - cache.order.push_back(block_hash); - while cache.entries.len() > Self::MAX_MODES { - let Some(evicted) = cache.order.pop_front() else { - break; - }; - cache.entries.remove(&evicted); - } - } - } + /// Records `block_hash` as an L1-derived safe block. Never downgrades an existing mark + /// because buffered safe payloads later pass through `validate_block` without `is_safe`. + fn mark_safe(&self, block_hash: B256) { + self.safe_blocks.lock().insert(block_hash, ()); } - fn mode_for(&self, block_hash: B256) -> MorphPayloadValidationMode { - self.modes - .lock() - .entries - .get(&block_hash) - .copied() - .unwrap_or(MorphPayloadValidationMode::Full) + fn is_safe(&self, block_hash: B256) -> bool { + self.safe_blocks.lock().contains_key(&block_hash) } } impl HeaderValidator for MorphEngineConsensus { fn validate_header(&self, header: &SealedHeader) -> Result<(), ConsensusError> { - match self.mode_for(header.hash()) { - MorphPayloadValidationMode::Full => self.inner.validate_header(header), - MorphPayloadValidationMode::LocallyBuilt | MorphPayloadValidationMode::Safe => { - self.inner.validate_header_structural(header) - } + if self.is_safe(header.hash()) { + self.inner.validate_header_structural(header) + } else { + self.inner.validate_header(header) } } @@ -328,16 +325,11 @@ impl HeaderValidator for MorphEngineConsensus { header: &SealedHeader, parent: &SealedHeader, ) -> Result<(), ConsensusError> { - match self.mode_for(header.hash()) { - MorphPayloadValidationMode::Full => { - self.inner.validate_header_against_parent(header, parent) - } - MorphPayloadValidationMode::LocallyBuilt => self - .inner - .validate_header_against_parent_locally_built(header, parent), - MorphPayloadValidationMode::Safe => self - .inner - .validate_header_against_parent_structural(header, parent), + if self.is_safe(header.hash()) { + self.inner + .validate_header_against_parent_structural(header, parent) + } else { + self.inner.validate_header_against_parent(header, parent) } } } @@ -355,11 +347,11 @@ impl Consensus for MorphEngineConsensus { &self, block: &SealedBlock, ) -> Result<(), ConsensusError> { - match self.mode_for(block.hash()) { - MorphPayloadValidationMode::Full => self.inner.validate_block_pre_execution(block), - MorphPayloadValidationMode::LocallyBuilt | MorphPayloadValidationMode::Safe => self - .inner - .validate_block_pre_execution_without_da_limit(block), + if self.is_safe(block.hash()) { + self.inner + .validate_block_pre_execution_without_da_limit(block) + } else { + self.inner.validate_block_pre_execution(block) } } @@ -385,12 +377,6 @@ impl FullConsensus for MorphEngineConsensus { } } -#[derive(Debug, Default)] -struct KnownWithdrawTrieRootCache { - entries: HashMap, - order: VecDeque, -} - /// Upstream engine validator plus Morph-specific validation hooks. /// /// State execution, caching and trie maintenance remain entirely upstream. This @@ -407,261 +393,54 @@ where { inner: BasicEngineValidator, provider: P, - chain_spec: Arc, engine_consensus: Arc, post_execution_validator: MorphEngineValidator, - tree_headers: Arc, - known_withdraw_trie_roots: Mutex, + /// Bounded cache of validated in-memory `tree_state` headers so `convert_payload_to_block` + /// and `on_inserted_executed_block` can resolve unpersisted side-branch parents. + tree_headers: Mutex>>, } impl MorphTreeEngineValidator where Evm: ConfigureEvm, { - const MAX_KNOWN_WITHDRAW_TRIE_ROOTS: usize = 8192; + const MAX_TREE_HEADERS: usize = 8192; fn new( inner: BasicEngineValidator, provider: P, - chain_spec: Arc, engine_consensus: Arc, post_execution_validator: MorphEngineValidator, - tree_headers: Arc, ) -> Self { Self { inner, provider, - chain_spec, engine_consensus, post_execution_validator, - tree_headers, - known_withdraw_trie_roots: Mutex::new(KnownWithdrawTrieRootCache::default()), + tree_headers: Mutex::new(BoundedFifoMap::new(Self::MAX_TREE_HEADERS)), } } - fn record_known_withdraw_trie_root(&self, block_hash: B256, root: B256) { - let mut cache = self.known_withdraw_trie_roots.lock(); - let is_new = cache.entries.insert(block_hash, root).is_none(); - if is_new { - cache.order.push_back(block_hash); - while cache.entries.len() > Self::MAX_KNOWN_WITHDRAW_TRIE_ROOTS { - let Some(evicted) = cache.order.pop_front() else { - break; - }; - cache.entries.remove(&evicted); - } - } - } - - fn get_known_withdraw_trie_root(&self, block_hash: B256) -> Option { - self.known_withdraw_trie_roots - .lock() - .entries - .get(&block_hash) - .copied() - } - - fn updated_withdraw_trie_root_from_bundle_state(bundle_state: &BundleState) -> Option { - bundle_state - .account(&L2_MESSAGE_QUEUE_ADDRESS) - .and_then(|account| { - account - .storage - .get(&L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT) - .map(|slot| B256::from(slot.present_value())) - }) + fn record_tree_header(&self, header: SealedHeader) { + self.tree_headers.lock().insert(header.hash(), header); } } impl MorphTreeEngineValidator where Evm: ConfigureEvm, - P: BlockReader
+ StateProviderFactory, + P: BlockReader
, { fn lookup_sealed_header( &self, hash: B256, ) -> ProviderResult>> { - if let Some(header) = self.tree_headers.get(&hash) { + if let Some(header) = self.tree_headers.lock().get(&hash).cloned() { return Ok(Some(header)); } self.provider.sealed_header_by_hash(hash) } - /// Walks in-memory `tree_state` ancestors from `parent_hash` without hitting MDBX so - /// unpersisted side-branch parents still resolve their `withdraw_trie_root` even if - /// evicted from `KnownWithdrawTrieRootCache`. - fn find_tree_ancestor_withdraw_trie_root( - &self, - parent_hash: B256, - ctx: &TreeCtx<'_, MorphPrimitives>, - ) -> (Option, B256) { - let mut cur = parent_hash; - loop { - if let Some(root) = self.get_known_withdraw_trie_root(cur) { - return (Some(root), cur); - } - let Some(executed) = ctx.state().tree_state().executed_block_by_hash(cur) else { - return (None, cur); - }; - if let Some(updated) = - Self::updated_withdraw_trie_root_from_bundle_state(&executed.execution_output.state) - { - return (Some(updated), cur); - } - cur = executed.recovered_block().parent_hash(); - } - } - - fn resolve_post_block_withdraw_trie_root( - &self, - parent_hash: B256, - bundle_state: &BundleState, - tree_hint: Option<(Option, B256)>, - ) -> ProviderResult { - if let Some(updated) = Self::updated_withdraw_trie_root_from_bundle_state(bundle_state) { - return Ok(updated); - } - if let Some(parent_root) = self.get_known_withdraw_trie_root(parent_hash) { - return Ok(parent_root); - } - if let Some((Some(ancestor_root), _)) = tree_hint { - self.record_known_withdraw_trie_root(parent_hash, ancestor_root); - return Ok(ancestor_root); - } - let fallback_hash = tree_hint.map_or(parent_hash, |(_, ancestor_hash)| ancestor_hash); - let state = self.provider.state_by_block_hash(fallback_hash)?; - let slot_val = state - .storage( - L2_MESSAGE_QUEUE_ADDRESS, - B256::from(L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT), - )? - .unwrap_or_default(); - let actual = B256::from(slot_val); - self.record_known_withdraw_trie_root(parent_hash, actual); - Ok(actual) - } - - /// Validates `header.next_l1_msg_index` during `convert_payload_to_block` (which runs on - /// `AlreadySeen` hits for both `tree_state` and DB blocks) using both in-memory - /// `tree_headers` and `provider` to resolve the parent header. - fn validate_l1_msg_index_on_conversion( - &self, - block: &SealedBlock, - ) -> Result<(), NewPayloadError> { - let Some(parent) = self - .lookup_sealed_header(block.parent_hash()) - .map_err(|e| NewPayloadError::Other(Box::new(e)))? - else { - return Ok(()); - }; - - let mut expected = parent.next_l1_msg_index; - let mut first_l1_msg = true; - for tx in block.body().transactions() { - if !tx.is_l1_msg() { - break; - } - let Some(queue_index) = tx.queue_index() else { - return Ok(()); - }; - if first_l1_msg { - first_l1_msg = false; - if queue_index < parent.next_l1_msg_index { - return Ok(()); - } - } - expected = queue_index.checked_add(1).ok_or_else(|| { - NewPayloadError::Other(Box::new(MorphConsensusError::InvalidNextL1MessageIndex { - expected: u64::MAX, - actual: block.header().next_l1_msg_index, - })) - })?; - } - - let has_l1_msgs = !first_l1_msg; - let actual = block.header().next_l1_msg_index; - let is_jade = self - .chain_spec - .is_jade_active_at_timestamp(block.header().timestamp()); - let invalid = if is_jade { - actual != expected - } else { - has_l1_msgs && actual < expected - }; - if invalid { - return Err(NewPayloadError::Other(Box::new( - MorphConsensusError::InvalidNextL1MessageIndex { expected, actual }, - ))); - } - - Ok(()) - } - - /// Enforces parent-aware L1 message queue invariants: - /// - /// 1. Across **all** hardforks (both pre-Jade and post-Jade), if the block contains - /// leading L1 messages, the first message's `queue_index` must be `>= parent.next_l1_msg_index`. - /// Violations are cross-block L1 message replays and return cacheable - /// [`MorphConsensusError::L1MessagesNotInOrder`] (since transactions are committed by the - /// block hash). Forward skips (`first_queue_index > parent.next_l1_msg_index`) remain - /// permitted. - /// 2. From Jade onward, `header.next_l1_msg_index` must match the exact derived index - /// (`parent.next_l1_msg_index` when no L1 messages are present, or `last_queue_index + 1` - /// otherwise). Mismatches return transient [`MorphConsensusError::InvalidNextL1MessageIndex`] - /// so an unhashed header field cannot poison `invalid_headers`. - fn validate_l1_msg_index_against_parent( - &self, - block: &SealedBlock, - parent: &MorphHeader, - ) -> Result<(), ConsensusError> { - let mut expected = parent.next_l1_msg_index; - let mut first_l1_msg = true; - for tx in block.body().transactions() { - if !tx.is_l1_msg() { - break; - } - let queue_index = tx.queue_index().ok_or_else(|| { - ConsensusError::msg("L1 message transaction is missing queue index") - })?; - if first_l1_msg { - first_l1_msg = false; - if queue_index < parent.next_l1_msg_index { - return Err(ConsensusError::other( - MorphConsensusError::L1MessagesNotInOrder { - expected: parent.next_l1_msg_index, - actual: queue_index, - }, - )); - } - } - expected = queue_index.checked_add(1).ok_or_else(|| { - ConsensusError::other(MorphConsensusError::InvalidNextL1MessageIndex { - expected: u64::MAX, - actual: block.header().next_l1_msg_index, - }) - })?; - } - - if !self - .chain_spec - .is_jade_active_at_timestamp(block.header().timestamp()) - { - return Ok(()); - } - - // Typed so that `MorphConsensus::is_transient_error` keeps this rejection out of - // reth's invalid-header cache: the field is not covered by the block hash, so - // the cache entry would also match the honest block. - let actual = block.header().next_l1_msg_index; - if actual != expected { - return Err(ConsensusError::other( - MorphConsensusError::InvalidNextL1MessageIndex { expected, actual }, - )); - } - Ok(()) - } - fn validate_next_l1_msg_index( &self, block: &SealedBlock, @@ -678,7 +457,9 @@ where return Ok(()); }; - self.validate_l1_msg_index_against_parent(block, parent.header()) + self.engine_consensus + .inner() + .validate_l1_msg_index_against_parent(block, parent.header()) .map_err(Into::into) } @@ -693,10 +474,8 @@ where } /// Runs structural consensus validation before admitting a locally built block via - /// `InsertExecutedBlock` (originating from either `assembleL2Block(V2)` or - /// `newSafeL2Block`), exempting wall-clock `TimestampIsInFuture`, `GasLimit` 1/1024 - /// bounds, `BaseFeeOverLimit`, and the local DA payload byte limit to match - /// morph-geth's `verified` and `NewSafeL2Block` (`safe = true`) paths. + /// `InsertExecutedBlock`, exempting wall-clock / gas-limit-step / base-fee-cap / local DA + /// bounds so `newSafeL2Block` and local payload pre-insertion keep working cleanly. fn validate_pre_inserted_block( &self, block: &RecoveredBlock, @@ -710,7 +489,8 @@ where consensus .validate_header_against_parent_structural(sealed_header, &parent) .map_err(ProviderError::other)?; - self.validate_l1_msg_index_against_parent(block.sealed_block(), parent.header()) + consensus + .validate_l1_msg_index_against_parent(block.sealed_block(), parent.header()) .map_err(ProviderError::other)?; } consensus @@ -719,38 +499,24 @@ where Ok(()) } - fn verify_and_record_withdraw_trie_root( + fn verify_withdraw_trie_root( &self, expectation: WithdrawTrieRootExpectation, - tree_hint: Option<(Option, B256)>, output: reth_engine_tree::tree::ValidationOutput, ) -> reth_engine_tree::tree::ValidationOutcome { - let sealed_block = output.executed_block.sealed_block(); - let block_hash = sealed_block.hash(); - let parent_hash = sealed_block.parent_hash(); - let actual = self - .resolve_post_block_withdraw_trie_root( - parent_hash, - &output.executed_block.execution_output.state, - tree_hint, - ) - .map_err(|err| InsertBlockError::new(sealed_block.clone(), err.into()))?; - - if let WithdrawTrieRootExpectation::Verify(expected) = expectation - && actual != expected + if let Err(err) = + MorphEngineValidator::validate_withdraw_trie_root_expectation(expectation, || { + output.executed_block.hashed_state() + }) { return Err(InsertBlockError::consensus_error( - ConsensusError::other(MorphConsensusError::WithdrawTrieRootMismatch { - expected, - actual, - }), - sealed_block.clone(), + err, + output.executed_block.sealed_block().clone(), ) .into()); } - self.record_known_withdraw_trie_root(block_hash, actual); - self.tree_headers.insert( + self.record_tree_header( output .executed_block .recovered_block() @@ -764,7 +530,7 @@ where impl EngineValidator for MorphTreeEngineValidator where - P: BlockReader
+ StateProviderFactory + Send + Sync + 'static, + P: BlockReader
+ Send + Sync + 'static, Evm: ConfigureEvm + 'static, BasicEngineValidator: EngineValidator, @@ -783,75 +549,27 @@ where mut payload: MorphExecutionData, ) -> Result, NewPayloadError> { let block_hash = payload.block.hash(); - self.validate_l1_msg_index_on_conversion(payload.block.as_ref())?; - self.engine_consensus - .record_mode(block_hash, payload.validation_mode); - - match payload.expected_withdraw_trie_root { - None => {} - Some(root) if root.is_zero() => { - self.post_execution_validator - .take_withdraw_trie_root_expectation(block_hash); - payload.expected_withdraw_trie_root = None; - } - Some(expected) => { - if let Some(actual) = self.get_known_withdraw_trie_root(block_hash) { - self.post_execution_validator - .take_withdraw_trie_root_expectation(block_hash); - payload.expected_withdraw_trie_root = None; - if actual != expected { - return Err(NewPayloadError::Other(Box::new( - MorphConsensusError::WithdrawTrieRootMismatch { expected, actual }, - ))); - } - } else if self - .provider - .sealed_header_by_hash(block_hash) - .map_err(|e| NewPayloadError::Other(Box::new(e)))? - .is_some() - { - match self.provider.state_by_block_hash(block_hash) { - Ok(state) => { - let slot_val = state - .storage( - L2_MESSAGE_QUEUE_ADDRESS, - B256::from(L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT), - ) - .map_err(|e| NewPayloadError::Other(Box::new(e)))? - .unwrap_or_default(); - let actual = B256::from(slot_val); - self.record_known_withdraw_trie_root(block_hash, actual); - self.post_execution_validator - .take_withdraw_trie_root_expectation(block_hash); - payload.expected_withdraw_trie_root = None; - if actual != expected { - return Err(NewPayloadError::Other(Box::new( - MorphConsensusError::WithdrawTrieRootMismatch { - expected, - actual, - }, - ))); - } - } - Err( - ProviderError::StateAtBlockPruned(_) - | ProviderError::StateForHashNotFound(_), - ) => { - tracing::warn!( - target: "morph::engine_validator", - %block_hash, - "skipping withdraw_trie_root check on persisted block with pruned historical state" - ); - self.post_execution_validator - .take_withdraw_trie_root_expectation(block_hash); - payload.expected_withdraw_trie_root = None; - } - Err(err) => { - return Err(NewPayloadError::Other(Box::new(err))); - } - } - } - } + // Validate the unhashed `next_l1_msg_index` here so `AlreadySeen` hits (both + // `tree_state` and DB) cannot bypass it, without poisoning `invalid_headers`. + if let Some(parent) = self + .lookup_sealed_header(payload.block.parent_hash()) + .map_err(|e| NewPayloadError::Other(Box::new(e)))? + { + self.engine_consensus + .inner() + .validate_unhashed_next_l1_msg_index(payload.block.as_ref(), parent.header()) + .map_err(|e| NewPayloadError::Other(Box::new(e)))?; + } + if payload.is_safe { + self.engine_consensus.mark_safe(block_hash); + } + if payload + .expected_withdraw_trie_root + .is_some_and(|root| root.is_zero()) + { + self.post_execution_validator + .take_withdraw_trie_root_expectation(block_hash); + payload.expected_withdraw_trie_root = None; } self.inner.convert_payload_to_block(payload) } @@ -862,7 +580,6 @@ where ctx: TreeCtx<'_, MorphPrimitives>, ) -> reth_engine_tree::tree::ValidationOutcome { let block_hash = payload.block.hash(); - let parent_hash = payload.block.parent_hash(); // Extract the expectation directly onto the stack so the live `validate_payload` // path never inserts into (or can leak from) `expected_withdraw_trie_roots`. // Also clear any residual entry left by an earlier buffered conversion. @@ -871,13 +588,13 @@ where .take_withdraw_trie_root_expectation(block_hash); self.validate_next_l1_msg_index_for_block(payload.block.as_ref(), &ctx)?; - let tree_hint = Some(self.find_tree_ancestor_withdraw_trie_root(parent_hash, &ctx)); - self.engine_consensus - .record_mode(block_hash, payload.validation_mode); + if payload.is_safe { + self.engine_consensus.mark_safe(block_hash); + } let output = self.inner.validate_payload(payload, ctx)?; let expectation = MorphEngineValidator::expectation_from_root(expected_withdraw_trie_root); - self.verify_and_record_withdraw_trie_root(expectation, tree_hint, output) + self.verify_withdraw_trie_root(expectation, output) } fn validate_block( @@ -886,11 +603,9 @@ where ctx: TreeCtx<'_, MorphPrimitives>, ) -> reth_engine_tree::tree::ValidationOutcome { let block_hash = block.hash(); - let parent_hash = block.parent_hash(); let l1_validation = self.validate_next_l1_msg_index_for_block(&block, &ctx); self.post_execution_validator .clear_withdraw_trie_root_expectation_on_error(block_hash, l1_validation)?; - let tree_hint = Some(self.find_tree_ancestor_withdraw_trie_root(parent_hash, &ctx)); let validation = self.inner.validate_block(block, ctx); let output = self @@ -900,7 +615,7 @@ where .post_execution_validator .take_withdraw_trie_root_expectation(block_hash) .unwrap_or(WithdrawTrieRootExpectation::SkipValidation); - self.verify_and_record_withdraw_trie_root(expectation, tree_hint, output) + self.verify_withdraw_trie_root(expectation, output) } fn on_inserted_executed_block( @@ -908,21 +623,14 @@ where block: BuiltPayloadExecutedBlock, ) -> ProviderResult> { self.validate_pre_inserted_block(block.recovered_block.as_ref())?; - let actual = self.resolve_post_block_withdraw_trie_root( - block.recovered_block.parent_hash(), - &block.execution_output.state, - None, - )?; - self.record_known_withdraw_trie_root(block.recovered_block.hash(), actual); let executed = self.inner.on_inserted_executed_block(block)?; - self.tree_headers - .insert(executed.recovered_block().sealed_header().clone()); + self.record_tree_header(executed.recovered_block().sealed_header().clone()); Ok(executed) } fn on_canonical_head_changed(&self, hash: B256, state: &EngineApiTreeState) { if let Some(header) = state.tree_state().sealed_header_by_hash(&hash) { - self.tree_headers.insert(header); + self.record_tree_header(header); } self.inner.on_canonical_head_changed(hash, state); } @@ -1055,20 +763,20 @@ where } } -#[derive(Debug, Default)] -struct WithdrawTrieRootCache { - entries: HashMap, - order: VecDeque, -} - /// Morph engine validator for payload validation. /// /// This validator is used by the engine API to validate incoming payloads. /// For Morph, most validation is deferred to the consensus layer. -#[derive(Debug, Default, Clone)] +#[derive(Debug, Clone)] #[non_exhaustive] pub struct MorphEngineValidator { - expected_withdraw_trie_roots: Arc>, + expected_withdraw_trie_roots: Arc>>, +} + +impl Default for MorphEngineValidator { + fn default() -> Self { + Self::new() + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -1082,7 +790,11 @@ impl MorphEngineValidator { /// Creates a new [`MorphEngineValidator`]. pub fn new() -> Self { - Self::default() + Self { + expected_withdraw_trie_roots: Arc::new(Mutex::new(BoundedFifoMap::new( + Self::MAX_EXPECTED_WITHDRAW_TRIE_ROOTS, + ))), + } } fn expectation_from_root(root: Option) -> WithdrawTrieRootExpectation { @@ -1099,33 +811,16 @@ impl MorphEngineValidator { block_hash: B256, expectation: WithdrawTrieRootExpectation, ) { - let mut cache = self.expected_withdraw_trie_roots.lock(); - let is_new_entry = cache.entries.insert(block_hash, expectation).is_none(); - - if is_new_entry { - cache.order.push_back(block_hash); - - while cache.entries.len() > Self::MAX_EXPECTED_WITHDRAW_TRIE_ROOTS { - let Some(evicted_hash) = cache.order.pop_front() else { - break; - }; - cache.entries.remove(&evicted_hash); - } - } + self.expected_withdraw_trie_roots + .lock() + .insert(block_hash, expectation); } fn take_withdraw_trie_root_expectation( &self, block_hash: B256, ) -> Option { - let mut cache = self.expected_withdraw_trie_roots.lock(); - let removed = cache.entries.remove(&block_hash); - - if removed.is_some() { - cache.order.retain(|hash| *hash != block_hash); - } - - removed + self.expected_withdraw_trie_roots.lock().remove(&block_hash) } fn clear_withdraw_trie_root_expectation_on_error( @@ -1139,7 +834,6 @@ impl MorphEngineValidator { result } - #[cfg(test)] fn updated_withdraw_trie_root_from_sorted_hashed_state( state_updates: &reth_trie::HashedPostStateSorted, ) -> Option { @@ -1158,7 +852,6 @@ impl MorphEngineValidator { }) } - #[cfg(test)] fn validate_withdraw_trie_root_expectation( expectation: WithdrawTrieRootExpectation, state_updates: impl FnOnce() -> Arc, @@ -1211,9 +904,15 @@ impl PayloadValidator for MorphEngineValidator { let expected_withdraw_trie_root = payload.expected_withdraw_trie_root; let sealed_block = Arc::unwrap_or_clone(payload.block); - if expected_withdraw_trie_root.is_some() { - let expectation = Self::expectation_from_root(expected_withdraw_trie_root); - self.record_withdraw_trie_root_expectation(sealed_block.hash(), expectation); + if let Some(root) = expected_withdraw_trie_root { + if !root.is_zero() { + self.record_withdraw_trie_root_expectation( + sealed_block.hash(), + WithdrawTrieRootExpectation::Verify(root), + ); + } else { + self.take_withdraw_trie_root_expectation(sealed_block.hash()); + } } Ok(sealed_block) @@ -1711,53 +1410,30 @@ mod tests { } #[test] - fn morph_engine_consensus_mode_records_monotonically_without_downgrade_or_full_deletion() { + fn morph_engine_consensus_safe_blocks_bounded_fifo() { let consensus = MorphEngineConsensus::new(MorphConsensus::new(Arc::new( morph_chainspec::MORPH_MAINNET.as_ref().clone(), ))); let hash = B256::from([0x91; 32]); - assert_eq!(consensus.mode_for(hash), MorphPayloadValidationMode::Full); + assert!(!consensus.is_safe(hash)); - // `Full` never inserts into the bounded cache. - consensus.record_mode(hash, MorphPayloadValidationMode::Full); - assert!(consensus.modes.lock().entries.is_empty()); + consensus.mark_safe(hash); + assert!(consensus.is_safe(hash)); - // `LocallyBuilt` is retained and not deleted by a concurrent/subsequent `Full` call. - consensus.record_mode(hash, MorphPayloadValidationMode::LocallyBuilt); - assert_eq!( - consensus.mode_for(hash), - MorphPayloadValidationMode::LocallyBuilt - ); - consensus.record_mode(hash, MorphPayloadValidationMode::Full); - assert_eq!( - consensus.mode_for(hash), - MorphPayloadValidationMode::LocallyBuilt, - "untrusted Full validation must never clobber LocallyBuilt mode" - ); - - // `Safe` upgrades `LocallyBuilt` and is never downgraded back to `LocallyBuilt` or `Full`. - consensus.record_mode(hash, MorphPayloadValidationMode::Safe); - assert_eq!(consensus.mode_for(hash), MorphPayloadValidationMode::Safe); - consensus.record_mode(hash, MorphPayloadValidationMode::LocallyBuilt); - assert_eq!(consensus.mode_for(hash), MorphPayloadValidationMode::Safe); - consensus.record_mode(hash, MorphPayloadValidationMode::Full); - assert_eq!(consensus.mode_for(hash), MorphPayloadValidationMode::Safe); - - // Bounded FIFO eviction at MAX_MODES (1024). - for idx in 0..=MorphEngineConsensus::MAX_MODES { + // Bounded FIFO eviction at MAX_SAFE_BLOCKS (1024). + for idx in 0..=MorphEngineConsensus::MAX_SAFE_BLOCKS { let mut raw = [0u8; 32]; raw[..8].copy_from_slice(&(idx as u64).to_be_bytes()); - consensus.record_mode(B256::from(raw), MorphPayloadValidationMode::LocallyBuilt); + consensus.mark_safe(B256::from(raw)); } assert_eq!( - consensus.modes.lock().entries.len(), - MorphEngineConsensus::MAX_MODES + consensus.safe_blocks.lock().entries.len(), + MorphEngineConsensus::MAX_SAFE_BLOCKS ); - assert_eq!( - consensus.mode_for(hash), - MorphPayloadValidationMode::Full, - "oldest mode entry must be evicted once MAX_MODES is exceeded" + assert!( + !consensus.is_safe(hash), + "oldest safe entry must be evicted once MAX_SAFE_BLOCKS is exceeded" ); } } diff --git a/crates/node/tests/it/engine.rs b/crates/node/tests/it/engine.rs index a19887f8..cf2b6f22 100644 --- a/crates/node/tests/it/engine.rs +++ b/crates/node/tests/it/engine.rs @@ -1804,22 +1804,36 @@ async fn validate_next_l1_msg_index_pre_jade_empty_l1_and_unpersisted_tree_paren assert!(c_status.is_valid()); // `child_c` is now `AlreadySeen` in `follower`'s `tree_state`, and its parent `parent_p` - // is only in `tree_state` (`TreeHeaderCache`): tampering `next_l1_message_index` on - // `engine_newL2BlockV2` MUST fail! + // is only in `tree_state`: tampering `next_l1_message_index` on `new_payload` MUST fail + // via `convert_payload_to_block` without poisoning `invalid_headers`! let mut child_c_tampered = child_c.clone(); child_c_tampered.next_l1_message_index = 99; - let err = import_l2_block(&follower, child_c_tampered) - .await - .expect_err( - "newL2BlockV2 must reject tampered next_l1_message_index with tree_state parent", - ) - .to_string(); - assert!(err.contains("invalid block.NextL1MsgIndex"), "got: {err}"); + let tampered_status = follower + .inner + .add_ons_handle + .beacon_engine_handle + .new_payload(decode_sealed(&child_c_tampered)?) + .await?; + assert!( + tampered_status.is_invalid(), + "new_payload must reject tampered next_l1_message_index with tree_state parent: {tampered_status:?}" + ); + assert!( + format!("{tampered_status:?}").contains("invalid block.NextL1MsgIndex"), + "unexpected validation error: {tampered_status:?}" + ); - // Honest `child_c` reorgs `follower` onto `Genesis -> parent_p -> child_c` cleanly. - let imported_c = import_l2_block(&follower, child_c.clone()).await?; - assert_eq!(imported_c.hash_slow(), child_c.hash); - assert_eq!(canonical_snapshot(&follower)?.hash, child_c.hash); + // Honest `child_c` must still be valid (`invalid_headers` not poisoned). + let honest_status = follower + .inner + .add_ons_handle + .beacon_engine_handle + .new_payload(decode_sealed(&child_c)?) + .await?; + assert!( + honest_status.is_valid(), + "honest AlreadySeen child_c must remain valid: {honest_status:?}" + ); Ok(()) } diff --git a/crates/node/tests/it/invalid_payload_recovery.rs b/crates/node/tests/it/invalid_payload_recovery.rs index acf5efc8..b74c0628 100644 --- a/crates/node/tests/it/invalid_payload_recovery.rs +++ b/crates/node/tests/it/invalid_payload_recovery.rs @@ -277,460 +277,60 @@ async fn tampered_next_l1_msg_index_rejected_when_block_already_seen() -> eyre:: Ok(()) } -/// Locally assembled blocks bypass the 0-second wall-clock `TimestampIsInFuture` check on the -/// assembling sequencer (matching morph-geth's `AssembleL2Block -> NewL2Block` `verified` path, -/// including HA switchover where `parent.timestamp > now` causes `payload_timestamp` to raise -/// the child timestamp past local wall-clock), while external followers that did not assemble -/// the block still enforce `TimestampIsInFuture`. -#[tokio::test(flavor = "multi_thread")] -async fn locally_assembled_future_timestamp_accepted_on_assembler_and_rejected_on_follower() --> eyre::Result<()> { - reth_tracing::init_test_tracing(); - - let (mut nodes, wallet) = TestNodeBuilder::new().with_num_nodes(2).build().await?; - let follower = nodes.pop().expect("two nodes requested"); - let sequencer = nodes.pop().expect("two nodes requested"); - - let raw_tx0 = make_transfer_tx(wallet.chain_id, wallet.inner.clone(), 0).await; - let tx0_hash = sequencer.rpc.inject_tx(raw_tx0).await?; - wait_until_pooled(&sequencer, tx0_hash).await?; - - let genesis = canonical_snapshot(&sequencer)?; - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default() - .as_secs(); - let future_timestamp = now + 3600; - - // 1. Sequencer locally assembles a non-empty block ahead of local wall clock. - let future_block = assemble_l2_block_v2( - &sequencer, - AssembleL2BlockV2Params { - parent_hash: genesis.hash, - transactions: vec![], - timestamp: Some(future_timestamp), - }, - ) - .await?; - assert_eq!( - future_block.transactions.len(), - 1, - "precondition: block must be non-empty so InsertExecutedBlock is emitted" - ); - - // Wait for `on_inserted_executed_block` to pre-insert the locally assembled block. - let deadline = tokio::time::Instant::now() + LOCAL_POLL_BUDGET; - loop { - if sequencer - .inner - .provider - .pending_block_num_hash()? - .map(|p| p.hash) - == Some(future_block.hash) - { - break; - } - assert!( - tokio::time::Instant::now() < deadline, - "locally assembled non-empty block must be pre-inserted into tree_state" - ); - tokio::time::sleep(POLL_INTERVAL).await; - } - - // Follower did NOT assemble `future_block`: both validate and import must reject it as future. - let follower_client = follower.auth_server_handle().http_client(); - let follower_validation: GenericResponse = follower_client - .request("engine_validateL2Block", (future_block.clone(),)) - .await?; - assert!( - !follower_validation.success, - "follower must reject untrusted future-timestamp block in engine_validateL2Block" - ); - let follower_err = import_l2_block(&follower, future_block.clone()) - .await - .expect_err("follower must reject untrusted future-timestamp block on import") - .to_string(); - assert!( - follower_err.to_lowercase().contains("future"), - "expected future-timestamp consensus rejection on follower, got: {follower_err}" - ); - assert_eq!( - canonical_snapshot(&follower)?, - genesis, - "follower canonical state must remain unchanged" - ); - - // Sequencer locally assembled `future_block`: validate and import must succeed. - let seq_client = sequencer.auth_server_handle().http_client(); - let seq_validation: GenericResponse = seq_client - .request("engine_validateL2Block", (future_block.clone(),)) - .await?; - assert!(seq_validation.success); - let imported1 = import_l2_block(&sequencer, future_block.clone()).await?; - assert_eq!(imported1.hash_slow(), future_block.hash); - - // 2. HA clock-behind-parent path: `parent.timestamp == now + 3600 > now`. - // `assemble_l2_block_v2` with `timestamp: Some(now)` raises timestamp to `now + 3600`. - // Build an EMPTY block so `InsertExecutedBlock` is skipped and `import_l2_block` - // exercises `new_payload -> validate_payload` under `LocallyBuilt`. - let empty_ha_block = assemble_l2_block_v2( - &sequencer, - AssembleL2BlockV2Params { - parent_hash: future_block.hash, - transactions: vec![], - timestamp: Some(now), - }, - ) - .await?; - assert!(empty_ha_block.transactions.is_empty()); - assert_eq!(empty_ha_block.timestamp, future_timestamp); - let imported2 = import_l2_block(&sequencer, empty_ha_block.clone()).await?; - assert_eq!(imported2.hash_slow(), empty_ha_block.hash); - - // 3. Reorg locally-built path (`number <= canonical_head`, where reth also skips - // `InsertExecutedBlock` even for non-empty blocks): rebuild height 2 on `future_block`. - let raw_tx1 = make_transfer_tx(wallet.chain_id, wallet.inner.clone(), 1).await; - let tx1_hash = sequencer.rpc.inject_tx(raw_tx1).await?; - wait_until_pooled(&sequencer, tx1_hash).await?; - - let reorg_ha_block = assemble_l2_block_v2( - &sequencer, - AssembleL2BlockV2Params { - parent_hash: future_block.hash, - transactions: vec![], - timestamp: Some(now), - }, - ) - .await?; - assert_eq!(reorg_ha_block.transactions.len(), 1); - assert_eq!(reorg_ha_block.timestamp, future_timestamp); - let imported2_reorg = import_l2_block(&sequencer, reorg_ha_block.clone()).await?; - assert_eq!(imported2_reorg.hash_slow(), reorg_ha_block.hash); - assert_eq!(canonical_snapshot(&sequencer)?.hash, reorg_ha_block.hash); - - Ok(()) -} - -/// Forged non-zero `withdraw_trie_root` must be rejected across ALL known-block paths: -/// 1. `AlreadySeen` in `tree_state` via `assembleL2BlockV2` pre-insertion (untouched zero slot), -/// 2. Live execution AND `AlreadySeen` in `tree_state` on a follower when an earlier block set a -/// non-zero `withdraw_trie_root` and the target block did NOT touch the slot in its own diff, -/// 3. DB-persisted `AlreadySeen` after advancing past the persistence threshold, -/// while `B256::ZERO` (skip optional check) and the true root continue to succeed without -/// poisoning `invalid_headers`. +/// Structural consensus violations (such as non-empty `extra_data` or `gas_used > gas_limit`) +/// must still be rejected even when `is_safe` (`engine_newSafeL2Block`) is set. #[tokio::test(flavor = "multi_thread")] -async fn forged_withdraw_trie_root_rejected_across_all_known_block_paths() -> eyre::Result<()> { +async fn safe_mode_still_rejects_structural_consensus_violations() -> eyre::Result<()> { reth_tracing::init_test_tracing(); - use morph_node::test_utils::MorphTxBuilder; - - // 7-byte runtime on L2MessageQueue (`0x5300...0001`): `SSTORE(CALLDATALOAD(0), CALLDATALOAD(32))`. - let (mut nodes, wallet) = TestNodeBuilder::new() - .with_account_code( - morph_chainspec::L2_MESSAGE_QUEUE_ADDRESS, - "0x6020355f355500", - ) - .with_num_nodes(2) - .build() - .await?; - let follower = nodes.pop().expect("two nodes requested"); - let sequencer = nodes.pop().expect("two nodes requested"); - - let seq_client = sequencer.auth_server_handle().http_client(); - let fol_client = follower.auth_server_handle().http_client(); - - // --- Path 1: Pre-inserted `tree_state` block with untouched zero withdraw slot --- - let raw_tx0 = make_transfer_tx(wallet.chain_id, wallet.inner.clone(), 0).await; - let tx0_hash = sequencer.rpc.inject_tx(raw_tx0).await?; - wait_until_pooled(&sequencer, tx0_hash).await?; - - let genesis = canonical_snapshot(&sequencer)?; - let block1 = assemble_l2_block_v2( - &sequencer, - AssembleL2BlockV2Params { - parent_hash: genesis.hash, - transactions: vec![], - timestamp: Some(head_timestamp(&sequencer)? + 1), - }, - ) - .await?; - assert_eq!(block1.withdraw_trie_root, B256::ZERO); - - let deadline = tokio::time::Instant::now() + LOCAL_POLL_BUDGET; - loop { - if sequencer - .inner - .provider - .pending_block_num_hash()? - .map(|p| p.hash) - == Some(block1.hash) - { - break; - } - assert!(tokio::time::Instant::now() < deadline); - tokio::time::sleep(POLL_INTERVAL).await; - } - - let forged_root = B256::repeat_byte(0xde); - let mut block1_forged = block1.clone(); - block1_forged.withdraw_trie_root = forged_root; - - let res: GenericResponse = seq_client - .request("engine_validateL2Block", (block1_forged.clone(),)) - .await?; - assert!( - !res.success, - "pre-inserted block with forged non-zero withdraw_trie_root must fail validateL2Block" - ); - assert!( - seq_client - .request::<(), _>("engine_newL2Block", (block1_forged.clone(),)) - .await - .is_err(), - "pre-inserted block with forged non-zero withdraw_trie_root must fail newL2Block" - ); - assert!( - import_l2_block(&sequencer, block1_forged).await.is_err(), - "pre-inserted block with forged non-zero withdraw_trie_root must fail newL2BlockV2" - ); - - // Honest block1 (withdraw_trie_root == ZERO) must still validate and import on both nodes. - let ok_res: GenericResponse = seq_client - .request("engine_validateL2Block", (block1.clone(),)) - .await?; - assert!(ok_res.success); - import_l2_block(&sequencer, block1.clone()).await?; - import_l2_block(&follower, block1.clone()).await?; - - // --- Path 2: Block 2 updates withdraw slot to R1; Block 3 leaves slot untouched --- - let real_root = B256::repeat_byte(0xab); - let mut wtr_calldata = Vec::with_capacity(64); - wtr_calldata.extend_from_slice( - B256::from(morph_chainspec::L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT).as_slice(), - ); - wtr_calldata.extend_from_slice(real_root.as_slice()); - let set_wtr_tx = MorphTxBuilder::new(wallet.chain_id, wallet.inner.clone(), 1) - .with_v1_eth_fee() - .with_to(morph_chainspec::L2_MESSAGE_QUEUE_ADDRESS) - .with_data(wtr_calldata) - .with_gas_limit(100_000) - .build_signed()?; - let set_wtr_hash = sequencer.rpc.inject_tx(set_wtr_tx).await?; - wait_until_pooled(&sequencer, set_wtr_hash).await?; - - let block2 = assemble_l2_block_v2( - &sequencer, - AssembleL2BlockV2Params { - parent_hash: block1.hash, - transactions: vec![], - timestamp: Some(block1.timestamp + 1), - }, - ) - .await?; - assert_eq!( - block2.withdraw_trie_root, real_root, - "assembled block2 must reflect updated withdraw_trie_root slot" - ); - import_l2_block(&sequencer, block2.clone()).await?; - import_l2_block(&follower, block2.clone()).await?; - - // Block 3 is empty (does NOT write slot 0 in its BundleState), so post-Block-3 root is still `real_root`. - let block3 = assemble_l2_block_v2( - &sequencer, - AssembleL2BlockV2Params { - parent_hash: block2.hash, - transactions: vec![], - timestamp: Some(block2.timestamp + 1), - }, - ) - .await?; - assert!(block3.transactions.is_empty()); - assert_eq!(block3.withdraw_trie_root, real_root); - import_l2_block(&sequencer, block3.clone()).await?; - - // On `follower` (which did NOT assemble `block3`): - // 2a. Live execution with forged non-zero root when slot 0 was untouched in Block 3 must fail! - let mut block3_forged = block3.clone(); - block3_forged.withdraw_trie_root = B256::repeat_byte(0xee); - let live_bad: GenericResponse = fol_client - .request("engine_validateL2Block", (block3_forged.clone(),)) - .await?; - assert!( - !live_bad.success, - "live validateL2Block must reject forged withdraw_trie_root even when slot was untouched in block" - ); - - // 2b. Validate `block3` with ZERO root on `follower` so `block3` enters `follower`'s `tree_state`. - let mut block3_zero = block3.clone(); - block3_zero.withdraw_trie_root = B256::ZERO; - let live_zero: GenericResponse = fol_client - .request("engine_validateL2Block", (block3_zero,)) - .await?; - assert!(live_zero.success); + use morph_payload_types::MorphPayloadTypes; + use reth_node_api::PayloadTypes; + use reth_primitives_traits::SealedBlock; - // 2c. Now `block3` hits `AlreadySeen` in `follower`'s `tree_state`: forged root must STILL fail! - let seen_bad: GenericResponse = fol_client - .request("engine_validateL2Block", (block3_forged.clone(),)) - .await?; - assert!( - !seen_bad.success, - "AlreadySeen in tree_state must reject forged non-zero withdraw_trie_root" - ); - assert!( - import_l2_block(&follower, block3_forged).await.is_err(), - "AlreadySeen import must reject forged non-zero withdraw_trie_root" - ); + let (mut nodes, _wallet) = TestNodeBuilder::new().build().await?; + let mut node = nodes.pop().expect("one node requested"); - // Honest `real_root` must still validate and import cleanly on `follower`. - let seen_good: GenericResponse = fol_client - .request("engine_validateL2Block", (block3.clone(),)) - .await?; - assert!(seen_good.success); - import_l2_block(&follower, block3.clone()).await?; - - // --- Path 3: Advance blocks so `block2` is persisted to MDBX and verify DB AlreadySeen --- - let mut parent_hash = block3.hash; - let mut ts = block3.timestamp; - for _ in 0..6 { - ts += 1; - let next_blk = assemble_l2_block_v2( - &sequencer, - AssembleL2BlockV2Params { - parent_hash, - transactions: vec![], - timestamp: Some(ts), - }, - ) - .await?; - import_l2_block(&sequencer, next_blk.clone()).await?; - import_l2_block(&follower, next_blk.clone()).await?; - parent_hash = next_blk.hash; - } + let base_payload = build_block_no_submit(&mut node, vec![]).await?; - let mut block2_forged = block2.clone(); - block2_forged.withdraw_trie_root = B256::repeat_byte(0x99); - let db_err = import_l2_block(&follower, block2_forged) - .await - .expect_err("persisted block must reject forged non-zero withdraw_trie_root") - .to_string(); - assert!( - db_err.contains("withdraw trie root mismatch"), - "expected withdraw trie root mismatch on persisted block, got: {db_err}" + let mut bad_extra = morph_primitives::Block::new( + base_payload.block().header().clone(), + base_payload.block().body().clone(), ); - let db_good = import_l2_block(&follower, block2.clone()).await?; - assert_eq!(db_good.hash_slow(), block2.hash); - - // --- Path 4: Cold-MDBX lookup (`known_withdraw_trie_roots` cache empty!) --- - // On a freshly booted node, genesis is persisted in MDBX (`provider.sealed_header_by_hash` - // returns `Some`) while `known_withdraw_trie_roots` is completely empty, exercising the - // cold-DB `state_by_block_hash` fallback in `MorphTreeEngineValidator::convert_payload_to_block`. - let genesis_wtr = B256::repeat_byte(0x77); - let (mut cold_nodes, _) = TestNodeBuilder::new() - .with_account_storage( - morph_chainspec::L2_MESSAGE_QUEUE_ADDRESS, - B256::from(morph_chainspec::L2_MESSAGE_QUEUE_WITHDRAW_TRIE_ROOT_SLOT), - genesis_wtr, - ) - .build() - .await?; - let cold_node = cold_nodes.pop().unwrap(); - let cold_genesis = std::sync::Arc::new(reth_primitives_traits::SealedBlock::seal_slow( - reth_provider::BlockReader::block_by_number(&cold_node.inner.provider, 0)? - .expect("genesis block in MDBX"), - )); - let forged_genesis_payload = - morph_payload_types::MorphExecutionData::with_expected_withdraw_trie_root( - cold_genesis.clone(), - B256::repeat_byte(0x88), - ); - let cold_bad_status = cold_node + bad_extra.header.inner.extra_data = alloy_primitives::Bytes::from_static(b"invalid"); + let payload_extra = + MorphPayloadTypes::block_to_payload(SealedBlock::seal_slow(bad_extra), None) + .with_safe_validation(); + let status = node .inner .add_ons_handle .beacon_engine_handle - .new_payload(forged_genesis_payload) + .new_payload(payload_extra) .await?; assert!( - cold_bad_status.is_invalid(), - "cold-MDBX block with forged withdraw_trie_root must be rejected: {cold_bad_status:?}" + status.is_invalid(), + "non-empty extra_data must be rejected in safe mode: {status:?}" ); - let honest_genesis_payload = - morph_payload_types::MorphExecutionData::with_expected_withdraw_trie_root( - cold_genesis, - genesis_wtr, - ); - let cold_ok_status = cold_node + + let mut bad_gas = morph_primitives::Block::new( + base_payload.block().header().clone(), + base_payload.block().body().clone(), + ); + bad_gas.header.inner.gas_used = bad_gas.header.inner.gas_limit + 1; + let payload_gas = MorphPayloadTypes::block_to_payload(SealedBlock::seal_slow(bad_gas), None) + .with_safe_validation(); + let status = node .inner .add_ons_handle .beacon_engine_handle - .new_payload(honest_genesis_payload) + .new_payload(payload_gas) .await?; assert!( - cold_ok_status.is_valid(), - "cold-MDBX block with matching withdraw_trie_root must succeed: {cold_ok_status:?}" + status.is_invalid(), + "gas_used > gas_limit must be rejected in safe mode: {status:?}" ); Ok(()) } -/// Structural consensus violations (such as non-empty `extra_data` or `gas_used > gas_limit`) -/// must still be rejected even when `MorphPayloadValidationMode::LocallyBuilt` or `Safe` is set. -#[tokio::test(flavor = "multi_thread")] -async fn locally_built_and_safe_modes_still_reject_structural_consensus_violations() --> eyre::Result<()> { - reth_tracing::init_test_tracing(); - use morph_payload_types::{MorphPayloadTypes, MorphPayloadValidationMode}; - use reth_node_api::PayloadTypes; - use reth_primitives_traits::SealedBlock; - - let (mut nodes, _wallet) = TestNodeBuilder::new().build().await?; - let mut node = nodes.pop().expect("one node requested"); - - let base_payload = build_block_no_submit(&mut node, vec![]).await?; - for mode in [ - MorphPayloadValidationMode::LocallyBuilt, - MorphPayloadValidationMode::Safe, - ] { - let mut bad_extra = morph_primitives::Block::new( - base_payload.block().header().clone(), - base_payload.block().body().clone(), - ); - bad_extra.header.inner.extra_data = alloy_primitives::Bytes::from_static(b"invalid"); - let payload_extra = - MorphPayloadTypes::block_to_payload(SealedBlock::seal_slow(bad_extra), None) - .with_validation_mode(mode); - let status = node - .inner - .add_ons_handle - .beacon_engine_handle - .new_payload(payload_extra) - .await?; - assert!( - status.is_invalid(), - "non-empty extra_data must be rejected in {mode:?} mode: {status:?}" - ); - - let mut bad_gas = morph_primitives::Block::new( - base_payload.block().header().clone(), - base_payload.block().body().clone(), - ); - bad_gas.header.inner.gas_used = bad_gas.header.inner.gas_limit + 1; - let payload_gas = - MorphPayloadTypes::block_to_payload(SealedBlock::seal_slow(bad_gas), None) - .with_validation_mode(mode); - let status = node - .inner - .add_ons_handle - .beacon_engine_handle - .new_payload(payload_gas) - .await?; - assert!( - status.is_invalid(), - "gas_used > gas_limit must be rejected in {mode:?} mode: {status:?}" - ); - } - - Ok(()) -} - /// When a `Safe` payload arrives while its parent is not yet in the engine tree, /// `EngineApiTreeHandler` converts it via `convert_payload_to_block`, buffers the /// `SealedBlock`, and later validates it via `MorphTreeEngineValidator::validate_block` @@ -746,7 +346,7 @@ async fn buffered_safe_payload_preserves_validation_mode_when_parent_connects() use alloy_rpc_types_engine::ForkchoiceState; use jsonrpsee::core::client::ClientT; use morph_node::test_utils::MorphTxBuilder; - use morph_payload_types::{MorphPayloadTypes, MorphPayloadValidationMode, SafeL2Data}; + use morph_payload_types::{MorphPayloadTypes, SafeL2Data}; use morph_primitives::MorphHeader; use reth_node_api::PayloadTypes; use reth_primitives_traits::SealedBlock; @@ -829,8 +429,8 @@ async fn buffered_safe_payload_preserves_validation_mode_when_parent_connects() // 1. Submit Block 2 (`Safe`) to `follower` BEFORE Block 1 so `follower` buffers it via // `convert_payload_to_block` -> `self.state.buffer` (`Syncing`). let follower_engine = &follower.inner.add_ons_handle.beacon_engine_handle; - let b2_safe_payload = MorphPayloadTypes::block_to_payload(sealed_b2, None) - .with_validation_mode(MorphPayloadValidationMode::Safe); + let b2_safe_payload = + MorphPayloadTypes::block_to_payload(sealed_b2, None).with_safe_validation(); let b2_buffered_status = follower_engine.new_payload(b2_safe_payload).await?; assert!( b2_buffered_status.is_syncing(), diff --git a/crates/node/tests/it/morph_tx.rs b/crates/node/tests/it/morph_tx.rs index 6be1e665..a508430c 100644 --- a/crates/node/tests/it/morph_tx.rs +++ b/crates/node/tests/it/morph_tx.rs @@ -1736,17 +1736,18 @@ async fn assemble_on_non_canonical_parent_does_not_evict_canonical_valid_morph_t Ok(()) } -/// An earlier transaction in the same block (either a supplied L1 message or a higher-priority -/// pool transaction from another sender) mutating Call-mode token state so `transfer` reverts -/// (`MorphInvalidTransaction::TokenTransferFailed`) must NOT evict a `MorphTx` that is valid on -/// the clean canonical parent; once that mutation IS committed to the canonical parent, the now -/// genuinely-broken `MorphTx` IS evicted on subsequent canonical builds. +/// M-M12: A Call-mode `MorphTx` whose token contract reverts on `transfer` +/// (`MorphInvalidTransaction::TokenTransferFailed`) is evicted from the global pool when +/// building on the synchronized canonical head, while eviction is suppressed during the +/// async txpool maintenance lag window (`pool.last_seen_block_hash != parent_hash`). #[tokio::test(flavor = "multi_thread")] -async fn in_block_token_mutation_does_not_evict_morph_tx_valid_on_clean_parent() -> eyre::Result<()> +async fn broken_token_morph_tx_evicted_only_when_pool_synced_to_canonical_head() -> eyre::Result<()> { reth_tracing::init_test_tracing(); - use morph_node::test_utils::L1MessageBuilder; - use morph_payload_types::AssembleL2BlockV2Params; + use alloy_consensus::Sealable; + use jsonrpsee::core::client::ClientT; + use morph_payload_types::{AssembleL2BlockV2Params, SafeL2Data}; + use morph_primitives::MorphHeader; use reth_transaction_pool::{TransactionPool, TransactionPoolExt}; let registry = alloy_primitives::address!("5300000000000000000000000000000000000021"); @@ -1768,7 +1769,7 @@ async fn in_block_token_mutation_does_not_evict_morph_tx_valid_on_clean_parent() let node = nodes.pop().unwrap(); let genesis = super::helpers::canonical_snapshot(&node)?; - // Inject a valid Call-mode MorphTx (`fee_token_id = 1`) from account 1 (moderate priority fee). + // Inject a valid Call-mode MorphTx (`fee_token_id = 1`) from account 1 while the token works. let signer1 = wallet_at_index(1, wallet.chain_id); let morph_tx = MorphTxBuilder::new(wallet.chain_id, signer1, 0) .with_v0_token_fee(TEST_TOKEN_ID) @@ -1778,82 +1779,41 @@ async fn in_block_token_mutation_does_not_evict_morph_tx_valid_on_clean_parent() let morph_tx_hash = node.rpc.inject_tx(morph_tx).await?; super::helpers::wait_until_pooled(&node, morph_tx_hash).await?; + // Commit Block 1 switching `TEST_TOKEN_ID` to `broken_token` using a deterministic supplied tx. let mut point_to_broken_calldata = Vec::with_capacity(64); point_to_broken_calldata.extend_from_slice(token_addr_slot.as_slice()); point_to_broken_calldata.extend_from_slice(&broken_token_word); - - // 1. Supplied L1 message mutates `L2TokenRegistry` mid-block so `MorphTx` hits - // `TokenTransferFailed` in-block, while still valid on clean Genesis parent. - let l1_mutator = L1MessageBuilder::new(0) - .with_sender(Address::with_last_byte(0xaa)) - .with_target(registry) - .with_data(point_to_broken_calldata.clone()) - .with_gas_limit(100_000) - .build_encoded(); - let l1_candidate = super::helpers::assemble_l2_block_v2( - &node, - AssembleL2BlockV2Params { - parent_hash: genesis.hash, - transactions: vec![l1_mutator], - timestamp: Some(1), - }, - ) - .await?; - assert_eq!( - l1_candidate.transactions.len(), - 1, - "only the supplied L1 message should execute; MorphTx fails in-block" - ); - assert!( - node.inner.pool.contains(&morph_tx_hash), - "supplied L1 message state mutation must NOT evict MorphTx valid on clean parent" - ); - - // 2. Higher-priority pool tx from `wallet` (account 0) mutates `L2TokenRegistry` mid-block. - let high_prio_mutator = MorphTxBuilder::new(wallet.chain_id, wallet.inner.clone(), 0) + let mutator_tx = MorphTxBuilder::new(wallet.chain_id, wallet.inner.clone(), 0) .with_v1_eth_fee() .with_to(registry) .with_data(point_to_broken_calldata) .with_fees(50_000_000_000, 50_000_000_000) .with_gas_limit(100_000) .build_signed()?; - let mutator_hash = node.rpc.inject_tx(high_prio_mutator).await?; - super::helpers::wait_until_pooled(&node, mutator_hash).await?; - - let pool_candidate = super::helpers::assemble_l2_block_v2( - &node, - AssembleL2BlockV2Params { - parent_hash: genesis.hash, - transactions: vec![], - timestamp: Some(2), - }, - ) - .await?; - assert_eq!( - pool_candidate.transactions.len(), - 1, - "only the high-priority mutator tx should execute" - ); - assert!( - node.inner.pool.contains(&morph_tx_hash), - "in-block state mutation by another sender's pool tx must NOT evict MorphTx valid on clean parent" - ); - - // 3. Once `pool_candidate` IS imported as canonical Block 1, `TEST_TOKEN_ID` now fails - // `TokenTransferFailed` on the clean canonical parent itself, so assembling Block 2 - // on Block 1 MUST evict `morph_tx_hash` from the global pool. - super::helpers::import_l2_block(&node, pool_candidate.clone()).await?; - super::helpers::wait_until_evicted(&node, mutator_hash).await?; + let client = node.auth_server_handle().http_client(); + let block1: MorphHeader = client + .request( + "engine_newSafeL2Block", + (SafeL2Data { + number: 1, + gas_limit: 30_000_000, + base_fee_per_gas: Some(1_000_000), + timestamp: 1, + transactions: vec![mutator_tx], + parent_hash: Some(genesis.hash), + },), + ) + .await?; + let block1_hash = block1.hash_slow(); let deadline = tokio::time::Instant::now() + super::helpers::LOCAL_POLL_BUDGET; - while node.inner.pool.block_info().last_seen_block_hash != pool_candidate.hash { + while node.inner.pool.block_info().last_seen_block_hash != block1_hash { assert!(tokio::time::Instant::now() < deadline); tokio::time::sleep(super::helpers::POLL_INTERVAL).await; } - // 3a. Simulate the async txpool maintenance lag window right after FCU advanced the - // canonical head to `pool_candidate.hash` while `pool.block_info().last_seen_block_hash` - // still points at `genesis.hash`: eviction is suppressed for that lagged tick. + // 1. Simulate async txpool maintenance lag (`last_seen_block_hash != parent_hash`): + // eviction is suppressed for that lagged tick. let mut lagged_info = node.inner.pool.block_info(); lagged_info.last_seen_block_hash = genesis.hash; node.inner.pool.set_block_info(lagged_info); @@ -1861,9 +1821,9 @@ async fn in_block_token_mutation_does_not_evict_morph_tx_valid_on_clean_parent() let lagged_block2 = super::helpers::assemble_l2_block_v2( &node, AssembleL2BlockV2Params { - parent_hash: pool_candidate.hash, + parent_hash: block1_hash, transactions: vec![], - timestamp: Some(3), + timestamp: Some(2), }, ) .await?; @@ -1873,18 +1833,18 @@ async fn in_block_token_mutation_does_not_evict_morph_tx_valid_on_clean_parent() "pool maintenance lag window (pool last_seen_block_hash != parent_hash) must suppress eviction" ); - // 3b. Once `pool.block_info().last_seen_block_hash` catches up to `pool_candidate.hash`, - // the next canonical build evicts the genuinely broken MorphTx cleanly. + // 2. Once `pool.block_info().last_seen_block_hash` catches up to `block1_hash`, + // the next canonical build evicts the genuinely broken MorphTx cleanly. let mut synced_info = node.inner.pool.block_info(); - synced_info.last_seen_block_hash = pool_candidate.hash; + synced_info.last_seen_block_hash = block1_hash; node.inner.pool.set_block_info(synced_info); let block2 = super::helpers::assemble_l2_block_v2( &node, AssembleL2BlockV2Params { - parent_hash: pool_candidate.hash, + parent_hash: block1_hash, transactions: vec![], - timestamp: Some(4), + timestamp: Some(3), }, ) .await?; diff --git a/crates/payload/builder/src/builder.rs b/crates/payload/builder/src/builder.rs index b54e1e62..229fe6f8 100644 --- a/crates/payload/builder/src/builder.rs +++ b/crates/payload/builder/src/builder.rs @@ -32,7 +32,7 @@ use reth_execution_types::BlockExecutionOutput; use reth_payload_builder::PayloadId; use reth_payload_primitives::{BuiltPayloadExecutedBlock, PayloadBuilderError}; use reth_payload_util::{BestPayloadTransactions, NoopPayloadTransactions, PayloadTransactions}; -use reth_primitives_traits::{FastInstant as Instant, Recovered, RecoveredBlock, SealedHeader}; +use reth_primitives_traits::{FastInstant as Instant, RecoveredBlock, SealedHeader}; use reth_revm::{database::StateProviderDatabase, db::State}; use reth_storage_api::{StateProvider, StateProviderFactory}; use reth_transaction_pool::{BestTransactionsAttributes, PoolTransaction, TransactionPool}; @@ -656,8 +656,6 @@ impl MorphPayloadBuilderCtx { fn execute_pool_transactions( &self, builder: &mut impl BlockBuilder, - state_provider: &(impl StateProvider + ?Sized), - next_block_attrs: &MorphNextBlockEnvAttributes, info: &mut ExecutionInfo, executed_txs: &mut Vec, best_txs: BestTxs, @@ -678,24 +676,6 @@ impl MorphPayloadBuilderCtx { best_txs, breaker, || is_synchronized_canonical_parent(client, pool, parent_hash), - |tx| { - let Ok(evm_env) = self - .evm_config - .next_evm_env(self.parent(), next_block_attrs) - else { - return false; - }; - let tx_env = self.evm_config.tx_env(tx); - let mut clean_evm = self - .evm_config - .evm_with_env(StateProviderDatabase::new(state_provider), evm_env); - match clean_evm.validate_only(tx_env) { - Err(revm::context::result::EVMError::Transaction(morph_err)) => { - is_evictable_token_fee_error(&morph_err) - } - _ => false, - } - }, |tx_hash| { pool.remove_transactions(vec![tx_hash]); }, @@ -711,7 +691,6 @@ impl MorphPayloadBuilderCtx { mut best_txs: BestTxs, breaker: &PayloadBuildingBreaker, mut is_still_canonical_parent: impl FnMut() -> bool, - mut confirm_eviction_on_clean_parent: impl FnMut(&Recovered) -> bool, mut evict_from_pool: impl FnMut(B256), ) -> Result, PayloadBuilderError> where @@ -835,9 +814,6 @@ impl MorphPayloadBuilderCtx { && is_evictable_token_fee_error(error.as_ref()) && !info.executed_senders.contains(&tx.signer()) && is_still_canonical_parent() - && (info.transaction_count == 0 - || (confirm_eviction_on_clean_parent(&tx) - && is_still_canonical_parent())) { tracing::debug!( target: "payload_builder", @@ -1017,7 +993,7 @@ where // Create block builder let mut builder = ctx .evm_config - .builder_for_next_block(&mut db, ctx.parent(), next_block_attrs.clone()) + .builder_for_next_block(&mut db, ctx.parent(), next_block_attrs) .map_err(PayloadBuilderError::other)?; // If the engine tree provided a sparse-trie state root handle, wire the @@ -1062,8 +1038,6 @@ where if ctx .execute_pool_transactions( &mut builder, - state_provider, - &next_block_attrs, &mut info, &mut executed_txs, best_txs, @@ -1954,7 +1928,6 @@ mod tests { best_txs, &breaker, || true, - |_| true, |hash| evicted.push(hash), ) .expect("pool execution should complete"); @@ -2174,7 +2147,6 @@ mod tests { best_txs, &breaker, || true, - |_| true, |hash| evicted.push(hash), ) .expect("pool execution should complete"); @@ -2188,9 +2160,8 @@ mod tests { } #[test] - fn test_execute_pool_transactions_does_not_evict_when_non_canonical_or_caused_by_in_block_state() - { - use alloy_consensus::{Sealable, Signed, TxEip1559}; + fn test_execute_pool_transactions_does_not_evict_when_non_canonical_or_supplied_sender() { + use alloy_consensus::{Sealable, Signed}; use alloy_primitives::{Signature, TxKind}; use morph_primitives::{TxL1Msg, TxMorph}; use morph_txpool::MorphPooledTransaction; @@ -2219,29 +2190,7 @@ mod tests { (hash, MorphPooledTransaction::new(recovered, len)) }; - let make_eth_tx = |signer: Address, nonce: u64, tag: u8| { - let tx = TxEip1559 { - chain_id: 2818, - nonce, - gas_limit: 21_000, - max_fee_per_gas: 100, - max_priority_fee_per_gas: 10, - to: TxKind::Call(Address::repeat_byte(0xee)), - ..Default::default() - }; - let hash = B256::repeat_byte(tag); - let env = MorphTxEnvelope::Eip1559(Signed::new_unchecked( - tx, - Signature::test_signature(), - hash, - )); - let recovered = Recovered::new_unchecked(env, signer); - let len = recovered.encode_2718_len(); - (hash, MorphPooledTransaction::new(recovered, len)) - }; - - // 1. Non-canonical parent build (`can_evict_from_pool == false`): never evicts even - // at `transaction_count == 0`. + // 1. Non-canonical parent build (`can_evict_from_pool == false`): never evicts. let sender_a = Address::repeat_byte(0x10); let (h_stale_inactive, tx_stale_inactive) = make_morph_tx(sender_a, 0, 0xa1); let mut outcomes = HashMap::new(); @@ -2267,7 +2216,6 @@ mod tests { }, &breaker, || panic!("live canonical recheck should not run when can_evict_from_pool is false"), - |_| panic!("clean-parent check should not run when can_evict_from_pool is false"), |hash| evicted.push(hash), ) .expect("pool execution should complete"); @@ -2276,56 +2224,7 @@ mod tests { "non-canonical parent build must never evict from global pool" ); - // 2. In-block state mutation by an earlier transaction from another sender: - // `h_mutated_in_block` is valid on clean parent (`confirm == false` -> NOT evicted), - // whereas `h_broken_on_parent` also fails on clean parent (`confirm == true` -> evicted). - let sender_mutator = Address::repeat_byte(0x20); - let sender_victim = Address::repeat_byte(0x21); - let sender_broken = Address::repeat_byte(0x22); - let (h_mutator, tx_mutator) = make_eth_tx(sender_mutator, 0, 0xb1); - let (h_mutated_in_block, tx_mutated_in_block) = make_morph_tx(sender_victim, 0, 0xb2); - let (h_broken_on_parent, tx_broken_on_parent) = make_morph_tx(sender_broken, 0, 0xb3); - - let mut outcomes = HashMap::new(); - outcomes.insert(h_mutator, Ok(21_000)); - outcomes.insert( - h_mutated_in_block, - Err(MorphInvalidTransaction::TokenTransferFailed { - reason: "paused mid-block".into(), - }), - ); - outcomes.insert( - h_broken_on_parent, - Err(MorphInvalidTransaction::TokenBalanceQueryFailed), - ); - let mut builder = ScriptedBlockBuilder::new(outcomes); - let mut info = ExecutionInfo::default(); - let mut executed_txs = Vec::new(); - let ctx = test_ctx_with_timestamp_and_txs(1_800_000_000, vec![]); - let breaker = ctx.builder_config.breaker(30_000_000); - let mut evicted = Vec::new(); - - ctx.execute_pool_transactions_with_evictor( - &mut builder, - &mut info, - &mut executed_txs, - ScriptedPoolTxs { - txs: VecDeque::from([tx_mutator, tx_mutated_in_block, tx_broken_on_parent]), - marked_invalid: Vec::new(), - }, - &breaker, - || true, - |tx| *tx.tx_hash() == h_broken_on_parent, - |hash| evicted.push(hash), - ) - .expect("pool execution should complete"); - assert_eq!( - evicted, - vec![h_broken_on_parent], - "only tx confirmed invalid on clean parent may be evicted after earlier txs ran" - ); - - // 3. Supplied L1 message from `sender_l1` seeds `info.executed_senders`, preventing + // 2. Supplied L1 message from `sender_l1` seeds `info.executed_senders`, preventing // eviction of a subsequent failing pool tx from `sender_l1`. let sender_l1 = Address::repeat_byte(0x30); let l1_msg = TxL1Msg { @@ -2369,7 +2268,6 @@ mod tests { }, &breaker, || true, - |_| true, |hash| evicted.push(hash), ) .expect("pool execution should complete"); @@ -2378,16 +2276,11 @@ mod tests { "sender with executed supplied L1 message in block must not be evicted" ); - // 4. Mid-build canonical head advance / reorg (`can_evict_from_pool == true` at build - // start, but `is_still_canonical_parent` flips to `false` before or during the - // clean-parent check): must suppress global pool eviction in both cases. - let sender_race_zero = Address::repeat_byte(0x40); - let (h_race_zero, tx_race_zero) = make_morph_tx(sender_race_zero, 0, 0xd1); + // 3. Mid-build canonical head advance / reorg suppresses global pool eviction. + let sender_race = Address::repeat_byte(0x40); + let (h_race, tx_race) = make_morph_tx(sender_race, 0, 0xd1); let mut outcomes = HashMap::new(); - outcomes.insert( - h_race_zero, - Err(MorphInvalidTransaction::TokenNotRegistered(99)), - ); + outcomes.insert(h_race, Err(MorphInvalidTransaction::TokenNotRegistered(99))); let mut builder = ScriptedBlockBuilder::new(outcomes); let mut info = ExecutionInfo::default(); let mut executed_txs = Vec::new(); @@ -2399,56 +2292,17 @@ mod tests { &mut info, &mut executed_txs, ScriptedPoolTxs { - txs: VecDeque::from([tx_race_zero]), + txs: VecDeque::from([tx_race]), marked_invalid: Vec::new(), }, &breaker, || false, - |_| panic!("clean-parent check should not run once canonical head moved"), - |hash| evicted.push(hash), - ) - .expect("pool execution should complete"); - assert!( - evicted.is_empty(), - "canonical head advance mid-build must suppress pool eviction at transaction_count == 0" - ); - - // Also test head advancing *during* `confirm_eviction_on_clean_parent` (`transaction_count > 0`): - let sender_prev = Address::repeat_byte(0x41); - let sender_race_mid = Address::repeat_byte(0x42); - let (h_prev, tx_prev) = make_eth_tx(sender_prev, 0, 0xd2); - let (h_race_mid, tx_race_mid) = make_morph_tx(sender_race_mid, 0, 0xd3); - let mut outcomes = HashMap::new(); - outcomes.insert(h_prev, Ok(21_000)); - outcomes.insert(h_race_mid, Err(MorphInvalidTransaction::TokenNotActive(99))); - let mut builder = ScriptedBlockBuilder::new(outcomes); - let mut info = ExecutionInfo::default(); - let mut executed_txs = Vec::new(); - let mut canonical_checks = 0usize; - let mut evicted = Vec::new(); - ctx.execute_pool_transactions_with_evictor( - &mut builder, - &mut info, - &mut executed_txs, - ScriptedPoolTxs { - txs: VecDeque::from([tx_prev, tx_race_mid]), - marked_invalid: Vec::new(), - }, - &breaker, - || { - canonical_checks += 1; - // First check (before clean-parent EVM) sees head unchanged; second check - // (after clean-parent EVM) sees head moved to a newer block. - canonical_checks == 1 - }, - |_| true, |hash| evicted.push(hash), ) .expect("pool execution should complete"); - assert_eq!(canonical_checks, 2); assert!( evicted.is_empty(), - "canonical head advance during clean-parent recheck must suppress pool eviction" + "canonical head advance mid-build must suppress pool eviction" ); } diff --git a/crates/payload/types/src/lib.rs b/crates/payload/types/src/lib.rs index 736026a3..15ebc71c 100644 --- a/crates/payload/types/src/lib.rs +++ b/crates/payload/types/src/lib.rs @@ -21,13 +21,10 @@ mod safe_l2_data; use alloy_consensus::BlockHeader as _; use alloy_eips::eip4895::Withdrawal; use alloy_primitives::{B256, Bytes}; -use morph_primitives::{Block, MorphHeader}; +use morph_primitives::Block; use reth_payload_primitives::{BuiltPayload, ExecutionPayload, PayloadTypes}; -use reth_primitives_traits::{NodePrimitives, SealedBlock, SealedHeader}; -use std::{ - collections::{HashMap, VecDeque}, - sync::{Arc, Mutex}, -}; +use reth_primitives_traits::{NodePrimitives, SealedBlock}; +use std::sync::Arc; // Feature unification: Ensure reth-ethereum-primitives' serde features are enabled // for transitive dependencies (via reth-payload-primitives → reth-chain-state). @@ -55,75 +52,6 @@ pub use safe_l2_data::SafeL2Data; #[non_exhaustive] pub struct MorphPayloadTypes; -/// Consensus validation mode applied when importing a [`MorphExecutionData`] payload. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)] -pub enum MorphPayloadValidationMode { - /// Standard untrusted payload validation (`VerifyHeader` + `ValidateBody` + execution). - #[default] - Full, - /// Locally assembled block (`AssembleL2Block` / `AssembleL2BlockV2` `verified` path in - /// morph-geth). Skips wall-clock `TimestampIsInFuture`, `GasLimit` 1/1024 bound, and local - /// DA payload byte limit. - LocallyBuilt, - /// L1-derived safe block (`NewSafeL2Block` with `safe = true` in morph-geth). Skips - /// `VerifyHeader` (`TimestampIsInFuture`, `TimestampIsInPast`, `GasLimit` bounds, - /// `BaseFeeOverLimit`) and `ValidateBody`'s local DA payload byte limit. - Safe, -} - -/// Bounded in-memory cache of validated [`SealedHeader`] entries currently held in -/// the engine tree, shared between the tree validator and the custom Morph L2 Engine API so -/// unpersisted in-memory parent headers are visible before MDBX persistence. -#[derive(Debug, Default)] -pub struct TreeHeaderCache { - inner: Mutex, -} - -#[derive(Debug, Default)] -struct TreeHeaderCacheInner { - entries: HashMap>, - order: VecDeque, -} - -impl TreeHeaderCache { - /// Maximum number of sealed headers retained in memory. - pub const MAX_ENTRIES: usize = 8192; - - /// Creates an empty [`TreeHeaderCache`]. - pub fn new() -> Self { - Self::default() - } - - /// Records a validated sealed header in the cache. - pub fn insert(&self, header: SealedHeader) { - let hash = header.hash(); - let mut inner = self - .inner - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - let is_new = inner.entries.insert(hash, header).is_none(); - if is_new { - inner.order.push_back(hash); - while inner.entries.len() > Self::MAX_ENTRIES { - let Some(evicted) = inner.order.pop_front() else { - break; - }; - inner.entries.remove(&evicted); - } - } - } - - /// Looks up a sealed header by block hash. - pub fn get(&self, hash: &B256) -> Option> { - self.inner - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - .entries - .get(hash) - .cloned() - } -} - /// Execution data for Morph node: a sealed block plus optional cross-check metadata. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct MorphExecutionData { @@ -132,12 +60,13 @@ pub struct MorphExecutionData { /// Optional expected withdraw trie root supplied by custom engine APIs. #[serde(default, skip_serializing_if = "Option::is_none")] pub expected_withdraw_trie_root: Option, - /// Validation mode governing consensus header/body exemptions. + /// Marks L1-derived safe blocks (`engine_newSafeL2Block`) that exempt header wall-clock / + /// gas-limit / base-fee bounds and local DA byte caps while preserving structural invariants. /// - /// Strictly internal in-process metadata (`#[serde(skip)]`) so external JSON/serde - /// payloads can never deserialize `LocallyBuilt` or `Safe`. + /// Strictly internal in-process metadata (`#[serde(skip)]`) so external JSON/serde payloads + /// can never set `is_safe = true`. #[serde(skip)] - pub validation_mode: MorphPayloadValidationMode, + pub is_safe: bool, } impl MorphExecutionData { @@ -146,7 +75,7 @@ impl MorphExecutionData { Self { block, expected_withdraw_trie_root: None, - validation_mode: MorphPayloadValidationMode::Full, + is_safe: false, } } @@ -158,16 +87,13 @@ impl MorphExecutionData { Self { block, expected_withdraw_trie_root: Some(expected_withdraw_trie_root), - validation_mode: MorphPayloadValidationMode::Full, + is_safe: false, } } - /// Sets the consensus validation mode for this payload. - pub const fn with_validation_mode( - mut self, - validation_mode: MorphPayloadValidationMode, - ) -> Self { - self.validation_mode = validation_mode; + /// Marks this payload as an L1-derived safe block (`NewSafeL2Block`). + pub const fn with_safe_validation(mut self) -> Self { + self.is_safe = true; self } } @@ -336,80 +262,28 @@ mod tests { let data = MorphPayloadTypes::block_to_payload(block, None); assert_eq!(data.block_hash(), hash); assert!(data.expected_withdraw_trie_root.is_none()); - assert_eq!(data.validation_mode, MorphPayloadValidationMode::Full); - } - - #[test] - fn test_execution_data_validation_mode_builder() { - let block = Arc::new(create_test_block()); - let data = MorphExecutionData::new(block); - assert_eq!(data.validation_mode, MorphPayloadValidationMode::Full); - - let local = data - .clone() - .with_validation_mode(MorphPayloadValidationMode::LocallyBuilt); - assert_eq!( - local.validation_mode, - MorphPayloadValidationMode::LocallyBuilt - ); - - let safe = data.with_validation_mode(MorphPayloadValidationMode::Safe); - assert_eq!(safe.validation_mode, MorphPayloadValidationMode::Safe); + assert!(!data.is_safe); } #[test] - fn test_execution_data_serde_skips_and_ignores_validation_mode() { + fn test_execution_data_serde_skips_and_ignores_is_safe() { let block = Arc::new(create_test_block()); - let safe = - MorphExecutionData::new(block).with_validation_mode(MorphPayloadValidationMode::Safe); + let safe = MorphExecutionData::new(block).with_safe_validation(); + assert!(safe.is_safe); let mut json_val = serde_json::to_value(&safe).expect("serialize MorphExecutionData"); assert!( - json_val.get("validation_mode").is_none() && json_val.get("validationMode").is_none(), - "validation_mode must never be serialized" + json_val.get("is_safe").is_none() && json_val.get("isSafe").is_none(), + "is_safe must never be serialized" ); - json_val["validation_mode"] = serde_json::json!("Safe"); - json_val["validationMode"] = serde_json::json!("LocallyBuilt"); + json_val["is_safe"] = serde_json::json!(true); + json_val["isSafe"] = serde_json::json!(true); let decoded: MorphExecutionData = serde_json::from_value(json_val).expect("deserialize MorphExecutionData"); - assert_eq!( - decoded.validation_mode, - MorphPayloadValidationMode::Full, - "untrusted serde input must never set LocallyBuilt or Safe" - ); - } - - #[test] - fn test_tree_header_cache_insert_get_and_bounded_eviction() { - let cache = TreeHeaderCache::new(); - let mut first_hash = B256::ZERO; - let mut last_hash = B256::ZERO; - - for number in 0..=(TreeHeaderCache::MAX_ENTRIES as u64) { - let header = SealedHeader::seal_slow(MorphHeader { - inner: Header { - number, - ..Default::default() - }, - next_l1_msg_index: number + 1, - }); - if number == 0 { - first_hash = header.hash(); - } - if number == TreeHeaderCache::MAX_ENTRIES as u64 { - last_hash = header.hash(); - } - cache.insert(header); - } - assert!( - cache.get(&first_hash).is_none(), - "oldest entry must be evicted once MAX_ENTRIES is exceeded" - ); - assert_eq!( - cache.get(&last_hash).unwrap().next_l1_msg_index, - TreeHeaderCache::MAX_ENTRIES as u64 + 1 + !decoded.is_safe, + "untrusted serde input must never set is_safe" ); } }