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/consensus/src/validation.rs b/crates/consensus/src/validation.rs index 3f101eea..c5a57ef3 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,236 @@ 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 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, + 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(()); + } + + 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 `NewSafeL2Block` (`safe = true`) + /// exemption. + 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 +400,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 +426,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 +438,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 +474,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 +483,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 +2633,127 @@ mod tests { Err(ConsensusError::BlockGasUsed { .. }) )); } + + #[test] + 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 (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(); + 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_structural(&child_sealed, &parent) + .is_ok() + ); + + // 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(&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/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..0c93260c 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(), } } @@ -456,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) + self.import_l2_block_via_engine(data, B256::ZERO, false) .await .inspect_err(|_| { self.metrics.new_l2_block_failures_total.increment(1); @@ -524,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) + .import_l2_block_via_engine(data, B256::ZERO, false) .await .inspect_err(|_| { self.metrics.new_l2_block_failures_total.increment(1); @@ -591,12 +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. 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 `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) + .import_l2_block_via_engine(executable_data, block_hash, true) .await .inspect_err(|_| { self.metrics.new_safe_l2_block_failures_total.increment(1); @@ -624,42 +638,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 +732,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 +744,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 +798,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, @@ -854,13 +929,17 @@ impl RealMorphL2EngineApi { &self, data: ExecutableL2Data, safe_block_hash: B256, + is_safe: bool, ) -> EngineApiResult where Provider: HeaderProvider
+ BlockNumReader + CanonChainTracker
, { - let (payload, header) = self.execution_payload_from_executable_data(&data)?; + let (mut payload, header) = self.execution_payload_from_executable_data(&data)?; + if is_safe { + payload = payload.with_safe_validation(); + } let payload_status = self .engine_handle @@ -869,6 +948,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 +1119,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 +1139,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 +1444,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 +1455,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 +1464,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 +1600,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/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 6e9b37e8..713f615c 100644 --- a/crates/node/src/validator.rs +++ b/crates/node/src/validator.rs @@ -3,17 +3,19 @@ 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, }; -use morph_consensus::MorphConsensusError; +use morph_consensus::{MorphConsensus, MorphConsensusError}; use morph_payload_types::{MorphExecutionData, MorphPayloadTypes}; -use morph_primitives::{MorphHeader, MorphPrimitives, MorphTxEnvelope}; +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, ReceiptRootBloom}; use reth_engine_tree::tree::payload_validator::TreeCtx; use reth_engine_tree::tree::{ BasicEngineValidator, CacheWaitDurations, EngineApiTreeState, EngineValidator, @@ -25,8 +27,8 @@ use reth_engine_tree::tree::{ StateRootJobOutcome, StateRootStrategy, }, }; -use reth_errors::{ConsensusError, ProviderResult}; -use reth_evm::{ConfigureEvm, revm::context::Block as _}; +use reth_errors::{ConsensusError, ProviderError, ProviderResult}; +use reth_evm::{ConfigureEvm, block::BlockExecutionResult, revm::context::Block as _}; use reth_node_api::{ AddOnsContext, FullNodeComponents, InvalidPayloadAttributesError, NewPayloadError, NodeTypes, PayloadAttributes, PayloadTypes, PayloadValidator, @@ -36,7 +38,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, @@ -47,7 +49,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,14 +131,18 @@ where let post_execution_validator = validator.clone(); let provider = ctx.node.provider().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())); + > = 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( provider.clone(), - Arc::new(ctx.node.consensus().clone()), + consensus, ctx.node.evm_config().clone(), validator, tree_config, @@ -151,7 +160,7 @@ where Ok(MorphTreeEngineValidator::new( validator, provider, - chain_spec, + engine_consensus, post_execution_validator, )) } @@ -218,6 +227,156 @@ fn strict_morph_tree_config(tree_config: reth_node_api::TreeConfig) -> reth_node tree_config.with_skip_state_root(false) } +/// Bounded FIFO map used for validator-internal in-memory caches. +#[derive(Debug)] +struct BoundedFifoMap { + entries: HashMap, + order: VecDeque, + max_entries: usize, +} + +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, + safe_blocks: Mutex>, +} + +impl MorphEngineConsensus { + const MAX_SAFE_BLOCKS: usize = 1024; + + fn new(inner: MorphConsensus) -> Self { + Self { + inner, + safe_blocks: Mutex::new(BoundedFifoMap::new(Self::MAX_SAFE_BLOCKS)), + } + } + + const fn inner(&self) -> &MorphConsensus { + &self.inner + } + + /// 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 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> { + if self.is_safe(header.hash()) { + self.inner.validate_header_structural(header) + } else { + self.inner.validate_header(header) + } + } + + fn validate_header_against_parent( + &self, + header: &SealedHeader, + parent: &SealedHeader, + ) -> Result<(), ConsensusError> { + if self.is_safe(header.hash()) { + self.inner + .validate_header_against_parent_structural(header, parent) + } else { + self.inner.validate_header_against_parent(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> { + if self.is_safe(block.hash()) { + self.inner + .validate_block_pre_execution_without_da_limit(block) + } else { + self.inner.validate_block_pre_execution(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, + ) + } +} + /// Upstream engine validator plus Morph-specific validation hooks. /// /// State execution, caching and trie maintenance remain entirely upstream. This @@ -234,27 +393,37 @@ where { inner: BasicEngineValidator, provider: P, - chain_spec: Arc, + engine_consensus: Arc, post_execution_validator: MorphEngineValidator, + /// 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 fn new( + const MAX_TREE_HEADERS: usize = 8192; + + fn new( inner: BasicEngineValidator, provider: P, - chain_spec: Arc, + engine_consensus: Arc, post_execution_validator: MorphEngineValidator, ) -> Self { Self { inner, provider, - chain_spec, + engine_consensus, post_execution_validator, + tree_headers: Mutex::new(BoundedFifoMap::new(Self::MAX_TREE_HEADERS)), } } + + fn record_tree_header(&self, header: SealedHeader) { + self.tree_headers.lock().insert(header.hash(), header); + } } impl MorphTreeEngineValidator @@ -262,22 +431,25 @@ where Evm: ConfigureEvm, P: BlockReader
, { + fn lookup_sealed_header( + &self, + hash: B256, + ) -> ProviderResult>> { + if let Some(header) = self.tree_headers.lock().get(&hash).cloned() { + return Ok(Some(header)); + } + self.provider.sealed_header_by_hash(hash) + } + fn validate_next_l1_msg_index( &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)?, + None => self.lookup_sealed_header(parent_hash)?, }; let Some(parent) = parent else { // The upstream validator reports the missing parent with the @@ -285,36 +457,10 @@ where return Ok(()); }; - let mut expected = parent.next_l1_msg_index; - 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") - })?; - expected = queue_index.checked_add(1).ok_or_else(|| { - ConsensusError::other(MorphConsensusError::InvalidNextL1MessageIndex { - expected: u64::MAX, - actual: block.header().next_l1_msg_index, - }) - })?; - } - - // 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(), - ); - } - Ok(()) + self.engine_consensus + .inner() + .validate_l1_msg_index_against_parent(block, parent.header()) + .map_err(Into::into) } fn validate_next_l1_msg_index_for_block( @@ -327,14 +473,39 @@ where .map_err(|kind| InsertBlockError::new(block.clone(), kind).into()) } - fn validate_withdraw_trie_root( + /// Runs structural consensus validation before admitting a locally built block via + /// `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, + ) -> ProviderResult<()> { + let consensus = self.engine_consensus.inner(); + let sealed_header = block.sealed_header(); + consensus + .validate_header_structural(sealed_header) + .map_err(ProviderError::other)?; + if let Some(parent) = self.lookup_sealed_header(block.parent_hash())? { + consensus + .validate_header_against_parent_structural(sealed_header, &parent) + .map_err(ProviderError::other)?; + consensus + .validate_l1_msg_index_against_parent(block.sealed_block(), parent.header()) + .map_err(ProviderError::other)?; + } + consensus + .validate_block_pre_execution_without_da_limit(block.sealed_block()) + .map_err(ProviderError::other)?; + Ok(()) + } + + fn verify_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(), || { + if let Err(err) = + MorphEngineValidator::validate_withdraw_trie_root_expectation(expectation, || { output.executed_block.hashed_state() }) { @@ -345,6 +516,13 @@ where .into()); } + self.record_tree_header( + output + .executed_block + .recovered_block() + .sealed_header() + .clone(), + ); Ok(output) } } @@ -368,29 +546,55 @@ where fn convert_payload_to_block( &self, - payload: MorphExecutionData, + mut payload: MorphExecutionData, ) -> Result, NewPayloadError> { + let block_hash = payload.block.hash(); + // 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) } 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)?; + 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_withdraw_trie_root(expectation, output) } fn validate_block( @@ -407,17 +611,27 @@ 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_withdraw_trie_root(expectation, output) } fn on_inserted_executed_block( &self, block: BuiltPayloadExecutedBlock, ) -> ProviderResult> { - self.inner.on_inserted_executed_block(block) + self.validate_pre_inserted_block(block.recovered_block.as_ref())?; + let executed = self.inner.on_inserted_executed_block(block)?; + 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.record_tree_header(header); + } self.inner.on_canonical_head_changed(hash, state); } @@ -553,11 +767,16 @@ where /// /// 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_root_order: Arc>>, + expected_withdraw_trie_roots: Arc>>, +} + +impl Default for MorphEngineValidator { + fn default() -> Self { + Self::new() + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -571,7 +790,20 @@ 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 { + 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( @@ -579,40 +811,16 @@ impl MorphEngineValidator { block_hash: B256, expectation: WithdrawTrieRootExpectation, ) { - let is_new_entry = self - .expected_withdraw_trie_roots - .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); - - while self.expected_withdraw_trie_roots.len() > Self::MAX_EXPECTED_WITHDRAW_TRIE_ROOTS { - let Some(evicted_hash) = order.pop_front() else { - break; - }; - self.expected_withdraw_trie_roots.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 removed = self - .expected_withdraw_trie_roots - .remove(&block_hash) - .map(|(_, expected)| expected); - - if removed.is_some() { - self.expected_withdraw_trie_root_order - .lock() - .retain(|hash| *hash != block_hash); - } - - removed + self.expected_withdraw_trie_roots.lock().remove(&block_hash) } fn clear_withdraw_trie_root_expectation_on_error( @@ -644,19 +852,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 +875,23 @@ impl MorphEngineValidator { } Ok(()) } + + #[cfg(test)] + 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 +904,16 @@ 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 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) } @@ -770,10 +989,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 +1005,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 +1273,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() { @@ -1173,4 +1408,32 @@ mod tests { .is_ok() ); } + + #[test] + 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!(!consensus.is_safe(hash)); + + consensus.mark_safe(hash); + assert!(consensus.is_safe(hash)); + + // 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.mark_safe(B256::from(raw)); + } + assert_eq!( + consensus.safe_blocks.lock().entries.len(), + MorphEngineConsensus::MAX_SAFE_BLOCKS + ); + assert!( + !consensus.is_safe(hash), + "oldest safe entry must be evicted once MAX_SAFE_BLOCKS is exceeded" + ); + } } 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..cf2b6f22 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,585 @@ 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(()) +} + +/// `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`: 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 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` 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 d67d5590..b74c0628 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,287 @@ 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(()) +} + +/// 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 safe_mode_still_rejects_structural_consensus_violations() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + use morph_payload_types::MorphPayloadTypes; + 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?; + + 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_safe_validation(); + 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 safe 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_safe_validation(); + 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 safe 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` +/// 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, 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_safe_validation(); + 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 d5456a1e..a508430c 100644 --- a/crates/node/tests/it/morph_tx.rs +++ b/crates/node/tests/it/morph_tx.rs @@ -1626,3 +1626,233 @@ 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(()) +} + +/// 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 broken_token_morph_tx_evicted_only_when_pool_synced_to_canonical_head() -> eyre::Result<()> +{ + reth_tracing::init_test_tracing(); + 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"); + 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 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) + .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?; + + // 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); + 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 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 != block1_hash { + assert!(tokio::time::Instant::now() < deadline); + tokio::time::sleep(super::helpers::POLL_INTERVAL).await; + } + + // 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); + + let lagged_block2 = super::helpers::assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: block1_hash, + transactions: vec![], + timestamp: Some(2), + }, + ) + .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" + ); + + // 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 = block1_hash; + node.inner.pool.set_block_info(synced_info); + + let block2 = super::helpers::assemble_l2_block_v2( + &node, + AssembleL2BlockV2Params { + parent_hash: block1_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/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..229fe6f8 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_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_consensus::{BlockHeader, Transaction, Typed2718, transaction::TxHashRef}; +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, + 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,76 @@ 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(_) + ) +} + +/// 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( + 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( @@ -194,12 +267,20 @@ 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 can_evict_from_pool = + is_synchronized_canonical_parent(&self.client, &self.pool, 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(), }; @@ -229,6 +310,8 @@ where build_payload_inner( cached_reads.as_db_mut(state), state_provider.as_ref(), + &self.client, + &self.pool, ctx, best, state_root_handle, @@ -298,6 +381,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, } @@ -354,6 +440,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()`. @@ -369,21 +456,68 @@ 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(), + }, + ) + })?; + // 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!( + "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 +617,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 @@ -514,6 +634,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; @@ -528,13 +652,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( + #[expect(clippy::too_many_arguments)] + fn execute_pool_transactions( + &self, + builder: &mut impl BlockBuilder, + 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_hash| { + pool.remove_transactions(vec![tx_hash]); + }, + ) + } + + #[expect(clippy::too_many_arguments)] + 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 is_still_canonical_parent: impl FnMut() -> bool, + mut evict_from_pool: impl FnMut(B256), ) -> Result, PayloadBuilderError> where BestTxs: PayloadTransactions>, @@ -582,6 +739,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 +807,24 @@ 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() + { + 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 +854,7 @@ impl MorphPayloadBuilderCtx { self.metrics .commit_tx_apply_duration_seconds .record(apply_started.elapsed()); + info.executed_senders.insert(tx.signer()); // Update execution info info.cumulative_gas_used += gas_used; @@ -699,13 +895,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, @@ -713,6 +911,7 @@ impl ExecutionInfo { total_fees: U256::ZERO, next_l1_message_index, transaction_count: 0, + executed_senders: HashSet::new(), max_da_block_size, } } @@ -742,9 +941,11 @@ impl ExecutionInfo { } /// Builds the payload on top of the state. -fn build_payload_inner<'a, DB, BestTxs>( +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, mut state_root_handle: Option, @@ -752,6 +953,8 @@ fn build_payload_inner<'a, DB, BestTxs>( where DB: Database, BestTxs: PayloadTransactions> + 'a, + Client: StateProviderFactory, + Pool: TransactionPool>, { let build_started = Instant::now(); let attributes = ctx.attributes(); @@ -838,6 +1041,8 @@ where &mut info, &mut executed_txs, best_txs, + client, + pool, &breaker, )? .is_some() @@ -1201,6 +1406,7 @@ mod tests { cancel: Default::default(), best_payload, builder_config: MorphBuilderConfig::default(), + can_evict_from_pool: true, metrics: MorphPayloadBuilderMetrics::default(), } } @@ -1299,4 +1505,890 @@ 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(), + can_evict_from_pool: true, + 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, + || true, + |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, + || true, + |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); + } + + #[test] + 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; + 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)) + }; + + // 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(); + 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!("live canonical recheck 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. 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" + ); + + // 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, 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]), + marked_invalid: Vec::new(), + }, + &breaker, + || false, + |hash| evicted.push(hash), + ) + .expect("pool execution should complete"); + assert!( + evicted.is_empty(), + "canonical head advance mid-build must suppress pool eviction" + ); + } + + #[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..15ebc71c 100644 --- a/crates/payload/types/src/lib.rs +++ b/crates/payload/types/src/lib.rs @@ -52,7 +52,7 @@ 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. +/// 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 +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, + /// 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 set `is_safe = true`. + #[serde(skip)] + pub is_safe: bool, } impl MorphExecutionData { @@ -68,6 +75,7 @@ impl MorphExecutionData { Self { block, expected_withdraw_trie_root: None, + is_safe: false, } } @@ -79,8 +87,15 @@ impl MorphExecutionData { Self { block, expected_withdraw_trie_root: Some(expected_withdraw_trie_root), + is_safe: false, } } + + /// Marks this payload as an L1-derived safe block (`NewSafeL2Block`). + pub const fn with_safe_validation(mut self) -> Self { + self.is_safe = true; + self + } } impl From for MorphExecutionData { @@ -247,5 +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!(!data.is_safe); + } + + #[test] + fn test_execution_data_serde_skips_and_ignores_is_safe() { + let block = Arc::new(create_test_block()); + 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("is_safe").is_none() && json_val.get("isSafe").is_none(), + "is_safe must never be serialized" + ); + + 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!( + !decoded.is_safe, + "untrusted serde input must never set is_safe" + ); } } 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()); + } }