Skip to main content

ethrex_common/
validation.rs

1//! Stateless block validation utilities.
2//!
3//! This module provides pure validation functions that can be used without
4//! storage dependencies, making them suitable for use in zkVM guest programs.
5
6use crate::constants::{GAS_PER_BLOB, MAX_RLP_BLOCK_SIZE, POST_OSAKA_GAS_LIMIT_CAP};
7use crate::errors::InvalidBlockError;
8use crate::types::block_access_list::BlockAccessList;
9use crate::types::requests::{EncodedRequests, Requests, compute_requests_hash};
10use crate::types::{
11    Block, BlockHeader, ChainConfig, EIP4844Transaction, Receipt, Transaction,
12    compute_receipts_root_and_logs_bloom, validate_block_header, validate_cancun_header_fields,
13    validate_prague_header_fields, validate_pre_cancun_header_fields,
14};
15use ethrex_crypto::{Crypto, NativeCrypto};
16use ethrex_rlp::encode::RLPEncode;
17
18/// Performs pre-execution validation of the block's header values in reference to the parent_header.
19/// Verifies that blob gas fields in the header are correct in reference to the block's body.
20/// If a block passes this check, execution will still fail with execute_block when a transaction runs out of gas.
21///
22/// # WARNING
23///
24/// This doesn't validate that the transactions or withdrawals root of the header matches the body
25/// contents, since we assume the caller already did it. And, in any case, that wouldn't invalidate the block header.
26///
27/// To validate it, use [`ethrex_common::types::validate_block_body`]
28pub fn validate_block_pre_execution(
29    block: &Block,
30    parent_header: &BlockHeader,
31    chain_config: &ChainConfig,
32    elasticity_multiplier: u64,
33) -> Result<(), InvalidBlockError> {
34    // Verify initial header validity against parent
35    validate_block_header(&block.header, parent_header, elasticity_multiplier)?;
36
37    if chain_config.is_osaka_activated(block.header.timestamp) {
38        let block_rlp_size = block.length();
39        if block_rlp_size > MAX_RLP_BLOCK_SIZE as usize {
40            return Err(InvalidBlockError::MaximumRlpSizeExceeded(
41                MAX_RLP_BLOCK_SIZE,
42                block_rlp_size as u64,
43            ));
44        }
45    }
46    if chain_config.is_prague_activated(block.header.timestamp) {
47        validate_prague_header_fields(&block.header, parent_header, chain_config)?;
48        verify_blob_gas_usage(block, chain_config)?;
49        if chain_config.is_osaka_activated(block.header.timestamp)
50            && !chain_config.is_amsterdam_activated(block.header.timestamp)
51        {
52            verify_transaction_max_gas_limit(block)?;
53        }
54    } else if chain_config.is_cancun_activated(block.header.timestamp) {
55        validate_cancun_header_fields(&block.header, parent_header, chain_config)?;
56        verify_blob_gas_usage(block, chain_config)?;
57    } else {
58        validate_pre_cancun_header_fields(&block.header)?;
59    }
60
61    // A transaction's chain id is bound into its signature (EIP-155 / the typed-tx
62    // `chain_id` field), so the recovered sender is only valid for that chain. Reject any
63    // transaction whose chain id does not match this chain: other clients (geth's signer)
64    // reject it at block validation, so accepting one would split consensus. Legacy
65    // pre-EIP-155 transactions carry no chain id (`None`) and are left untouched.
66    //
67    // Privileged (L2) transactions are exempt: their sender comes from an unsigned `from`
68    // field, so chain id is not a signature-binding scalar for them, and on L2 it may name
69    // a different source chain (cross-chain deposits). On L1 they are rejected outright as
70    // an unsupported transaction type, so this exemption opens no L1 gap. The other L2-only
71    // type, `FeeTokenTransaction` (0x7d), is signature-recovered and therefore stays
72    // checked — on L2 it carries the L2 chain id; on L1 it is rejected as unsupported.
73    for tx in &block.body.transactions {
74        if matches!(tx, Transaction::PrivilegedL2Transaction(_)) {
75            continue;
76        }
77        if let Some(tx_chain_id) = tx.chain_id()
78            && tx_chain_id != chain_config.chain_id
79        {
80            return Err(InvalidBlockError::InvalidTransactionChainId {
81                have: tx_chain_id,
82                want: chain_config.chain_id,
83            });
84        }
85    }
86
87    Ok(())
88}
89
90/// Validates that the block gas used matches the block header.
91/// For Amsterdam+ (EIP-7778), block_gas_used is PRE-REFUND and differs from
92/// receipt cumulative_gas_used which is POST-REFUND.
93pub fn validate_gas_used(
94    block_gas_used: u64,
95    block_header: &BlockHeader,
96) -> Result<(), InvalidBlockError> {
97    if block_gas_used != block_header.gas_used {
98        return Err(InvalidBlockError::GasUsedMismatch(
99            block_gas_used,
100            block_header.gas_used,
101        ));
102    }
103    Ok(())
104}
105
106/// Validates both the receipts root and the header `logs_bloom` against the executed
107/// receipts in a single pass.
108///
109/// The receipts root commits to each receipt's per-receipt bloom, but *not* to the
110/// header's aggregate `logs_bloom` field — so the aggregate must be checked separately
111/// or a block with a correct receipts root but an arbitrary bloom would be accepted,
112/// diverging from geth/reth. Both checks need each receipt's bloom, so computing them
113/// together hashes it only once (it is cycle-counted in the zkVM guest).
114pub fn validate_receipts_root_and_logs_bloom(
115    block_header: &BlockHeader,
116    receipts: &[Receipt],
117    crypto: &dyn Crypto,
118) -> Result<(), InvalidBlockError> {
119    let (receipts_root, logs_bloom) = compute_receipts_root_and_logs_bloom(receipts, crypto);
120
121    if receipts_root != block_header.receipts_root {
122        return Err(InvalidBlockError::ReceiptsRootMismatch);
123    }
124    if logs_bloom != block_header.logs_bloom {
125        return Err(InvalidBlockError::LogsBloomMismatch);
126    }
127    Ok(())
128}
129
130/// Validates that the requests hash matches the block header (Prague+).
131pub fn validate_requests_hash(
132    header: &BlockHeader,
133    chain_config: &ChainConfig,
134    requests: &[Requests],
135) -> Result<(), InvalidBlockError> {
136    if !chain_config.is_prague_activated(header.timestamp) {
137        return Ok(());
138    }
139
140    let encoded_requests: Vec<EncodedRequests> = requests.iter().map(|r| r.encode()).collect();
141    let computed_requests_hash = compute_requests_hash(&encoded_requests);
142    let valid = header
143        .requests_hash
144        .map(|requests_hash| requests_hash == computed_requests_hash)
145        .unwrap_or(false);
146
147    if !valid {
148        return Err(InvalidBlockError::RequestsHashMismatch);
149    }
150
151    Ok(())
152}
153
154/// Validates a block access list a peer supplied for a block, before anything uses it: it
155/// must be canonically ordered, carry no oversized code, and match the header's commitment.
156///
157/// The commitment alone is not enough: it is computed over a re-sorted encoding, so it
158/// accepts any permutation of the canonical list, and the parallel executor seeds each
159/// transaction's starting state by binary search over the list's entries, which assumes
160/// the canonical order. The engine API runs the same checks on the lists it is handed.
161pub fn validate_supplied_block_access_list(
162    bal: &crate::types::block_access_list::BlockAccessList,
163    commitment: Option<crate::H256>,
164    crypto: &dyn Crypto,
165) -> Result<(), String> {
166    bal.validate_ordering()?;
167    validate_bal_code_sizes(bal, crate::constants::AMSTERDAM_MAX_CODE_SIZE)
168        .map_err(|err| err.to_string())?;
169    if !bal.matches_commitment(commitment, crypto) {
170        return Err("block access list does not match the header's commitment".to_string());
171    }
172    Ok(())
173}
174
175/// Validates that the burned fees match the block header (LStar+, EIP-8079).
176///
177/// Whether the field may be present at all for the block's fork is checked before
178/// execution by the header validators; here the value the block commits to is compared
179/// with the one execution computed, as the receipts root and requests hash are.
180pub fn validate_burned_fees(
181    header: &BlockHeader,
182    chain_config: &ChainConfig,
183    computed_burned_fees: Option<u64>,
184) -> Result<(), InvalidBlockError> {
185    if !chain_config.is_lstar_activated(header.timestamp) {
186        return Ok(());
187    }
188    if header.burned_fees != computed_burned_fees {
189        return Err(InvalidBlockError::BurnedFeesMismatch);
190    }
191    Ok(())
192}
193
194/// Helper to validate that all indices in an iterator are within bounds.
195fn validate_bal_indices(
196    indices: impl Iterator<Item = u32>,
197    max_valid_index: u32,
198) -> Result<(), InvalidBlockError> {
199    for index in indices {
200        if index > max_valid_index {
201            return Err(InvalidBlockError::BlockAccessListIndexOutOfBounds {
202                index,
203                max: max_valid_index,
204            });
205        }
206    }
207    Ok(())
208}
209
210/// Validates that all indices in the header BAL are within valid bounds (Amsterdam+).
211/// This is a subset of the full hash check — used in the parallel execution path
212/// where we have the header BAL but do not build a new BAL during execution.
213/// Per EIP-7928: valid indices are 0 (pre-exec) through len(transactions)+1 (post-exec).
214pub fn validate_header_bal_indices(
215    bal: &crate::types::block_access_list::BlockAccessList,
216    transaction_count: usize,
217) -> Result<(), InvalidBlockError> {
218    let max_valid_index = u32::try_from(transaction_count + 1).unwrap_or(u32::MAX);
219
220    for account in bal.accounts() {
221        validate_bal_indices(
222            account
223                .storage_changes
224                .iter()
225                .flat_map(|slot| slot.slot_changes.iter().map(|c| c.block_access_index)),
226            max_valid_index,
227        )?;
228        validate_bal_indices(
229            account.balance_changes.iter().map(|c| c.block_access_index),
230            max_valid_index,
231        )?;
232        validate_bal_indices(
233            account.nonce_changes.iter().map(|c| c.block_access_index),
234            max_valid_index,
235        )?;
236        validate_bal_indices(
237            account.code_changes.iter().map(|c| c.block_access_index),
238            max_valid_index,
239        )?;
240    }
241    Ok(())
242}
243
244/// Validates that no code change in the BAL is larger than `max_code_size`, the fork's
245/// maximum deployed bytecode size.
246///
247/// Code can only be deployed within that limit, so a larger code change cannot appear in
248/// the BAL of a valid block. This is structural, like [`validate_header_bal_indices`], so
249/// it runs before the BAL is used to seed execution rather than after.
250pub fn validate_bal_code_sizes(
251    bal: &BlockAccessList,
252    max_code_size: u64,
253) -> Result<(), InvalidBlockError> {
254    for account in bal.accounts() {
255        for change in &account.code_changes {
256            let size = change.new_code.len();
257            if u64::try_from(size).map_or(true, |size| size > max_code_size) {
258                return Err(InvalidBlockError::BlockAccessListCodeTooLarge {
259                    address: account.address,
260                    size,
261                    max: max_code_size,
262                });
263            }
264        }
265    }
266    Ok(())
267}
268
269/// Validates that the block access list hash matches the block header (Amsterdam+).
270/// Also validates that all BlockAccessIndex values are within valid bounds per EIP-7928,
271/// and that the BAL size does not exceed the gas-derived limit.
272pub fn validate_block_access_list_hash(
273    header: &BlockHeader,
274    chain_config: &ChainConfig,
275    computed_bal: &crate::types::block_access_list::BlockAccessList,
276    transaction_count: usize,
277    crypto: &dyn Crypto,
278) -> Result<(), InvalidBlockError> {
279    use crate::constants::BAL_ITEM_COST;
280
281    // BAL validation only applies to Amsterdam+ forks
282    if !chain_config.is_amsterdam_activated(header.timestamp) {
283        return Ok(());
284    }
285
286    // Per EIP-7928: "Invalidate block if access list...contains indices exceeding len(transactions) + 1"
287    // Index semantics: 0=pre-exec, 1..n=tx indices, n+1=post-exec (withdrawals)
288    let max_valid_index = u32::try_from(transaction_count + 1).unwrap_or(u32::MAX);
289
290    // Validate all indices and compute item count in a single pass over the BAL.
291    let mut bal_items: u64 = 0;
292    for account in computed_bal.accounts() {
293        bal_items += 1; // address
294        bal_items += account.storage_reads.len() as u64;
295        bal_items += account.storage_changes.len() as u64;
296
297        // Check storage_changes indices
298        validate_bal_indices(
299            account
300                .storage_changes
301                .iter()
302                .flat_map(|slot| slot.slot_changes.iter().map(|c| c.block_access_index)),
303            max_valid_index,
304        )?;
305
306        // Check balance_changes indices
307        validate_bal_indices(
308            account.balance_changes.iter().map(|c| c.block_access_index),
309            max_valid_index,
310        )?;
311
312        // Check nonce_changes indices
313        validate_bal_indices(
314            account.nonce_changes.iter().map(|c| c.block_access_index),
315            max_valid_index,
316        )?;
317
318        // Check code_changes indices
319        validate_bal_indices(
320            account.code_changes.iter().map(|c| c.block_access_index),
321            max_valid_index,
322        )?;
323    }
324
325    // EIP-7928 size cap: bal_items <= gas_limit / GAS_BLOCK_ACCESS_LIST_ITEM
326    let max_items = header.gas_limit / BAL_ITEM_COST;
327    if bal_items > max_items {
328        return Err(InvalidBlockError::BlockAccessListSizeExceeded {
329            items: bal_items,
330            max_items,
331        });
332    }
333
334    let computed_hash = computed_bal.compute_hash(crypto);
335    let valid = header
336        .block_access_list_hash
337        .map(|expected_hash| expected_hash == computed_hash)
338        .unwrap_or(false);
339
340    if !valid {
341        return Err(InvalidBlockError::BlockAccessListHashMismatch);
342    }
343
344    Ok(())
345}
346
347/// Validates that the block access list does not exceed the maximum allowed size (Amsterdam+).
348/// Per EIP-7928: bal_items <= block_gas_limit // GAS_BLOCK_ACCESS_LIST_ITEM
349///
350/// Prefer using [`validate_block_access_list_hash`] when both hash and size validation are needed,
351/// as it performs both checks in a single pass over the BAL.
352pub fn validate_block_access_list_size(
353    header: &BlockHeader,
354    chain_config: &ChainConfig,
355    computed_bal: &crate::types::block_access_list::BlockAccessList,
356) -> Result<(), InvalidBlockError> {
357    use crate::constants::BAL_ITEM_COST;
358
359    if !chain_config.is_amsterdam_activated(header.timestamp) {
360        return Ok(());
361    }
362
363    let bal_items = computed_bal.item_count();
364    let max_items = header.gas_limit / BAL_ITEM_COST;
365
366    if bal_items > max_items {
367        return Err(InvalidBlockError::BlockAccessListSizeExceeded {
368            items: bal_items,
369            max_items,
370        });
371    }
372
373    Ok(())
374}
375
376/// Perform validations over the block's blob gas usage.
377/// Must be called only if the block has cancun activated.
378pub fn verify_blob_gas_usage(block: &Block, config: &ChainConfig) -> Result<(), InvalidBlockError> {
379    let mut blob_gas_used = 0_u32;
380    let mut blobs_in_block = 0_u32;
381    let max_blob_number_per_block = config
382        .get_fork_blob_schedule(block.header.timestamp)
383        .map(|schedule| schedule.max)
384        .ok_or(InvalidBlockError::InvalidBlockFork)?;
385    let max_blob_gas_per_block = max_blob_number_per_block * GAS_PER_BLOB;
386
387    for transaction in block.body.transactions.iter() {
388        match transaction {
389            crate::types::Transaction::EIP4844Transaction(tx) => {
390                blob_gas_used += get_total_blob_gas(tx);
391                blobs_in_block += tx.blob_versioned_hashes.len() as u32;
392            }
393            crate::types::Transaction::FrameTransaction(tx) => {
394                blob_gas_used += GAS_PER_BLOB * tx.blob_versioned_hashes.len() as u32;
395                blobs_in_block += tx.blob_versioned_hashes.len() as u32;
396            }
397            _ => {}
398        }
399    }
400    if blob_gas_used > max_blob_gas_per_block {
401        return Err(InvalidBlockError::ExceededMaxBlobGasPerBlock);
402    }
403    if blobs_in_block > max_blob_number_per_block {
404        return Err(InvalidBlockError::ExceededMaxBlobNumberPerBlock);
405    }
406    if block
407        .header
408        .blob_gas_used
409        .is_some_and(|header_blob_gas_used| header_blob_gas_used != blob_gas_used as u64)
410    {
411        return Err(InvalidBlockError::BlobGasUsedMismatch);
412    }
413    Ok(())
414}
415
416/// Perform validations over the block's gas usage.
417/// Must be called only if the block has osaka activated
418/// as specified in https://eips.ethereum.org/EIPS/eip-7825
419fn verify_transaction_max_gas_limit(block: &Block) -> Result<(), InvalidBlockError> {
420    for transaction in block.body.transactions.iter() {
421        if transaction.gas_limit() > POST_OSAKA_GAS_LIMIT_CAP {
422            return Err(InvalidBlockError::InvalidTransaction(format!(
423                "Transaction gas limit exceeds maximum. Transaction hash: {}, transaction gas limit: {}",
424                transaction.hash(&NativeCrypto),
425                transaction.gas_limit()
426            )));
427        }
428    }
429    Ok(())
430}
431
432/// Calculates the blob gas required by a transaction.
433pub fn get_total_blob_gas(tx: &EIP4844Transaction) -> u32 {
434    GAS_PER_BLOB * tx.blob_versioned_hashes.len() as u32
435}
436
437#[cfg(test)]
438mod tests {
439    use super::*;
440    use crate::H256;
441    use crate::types::{Block, BlockBody, BlockHeader, ChainConfig, Transaction};
442
443    /// Minimal cancun-active ChainConfig: only cancun_time set (= 0), default
444    /// blob schedule (max = 6 blobs per block).
445    fn cancun_config() -> ChainConfig {
446        ChainConfig {
447            cancun_time: Some(0),
448            ..Default::default()
449        }
450    }
451
452    /// Build a minimal Block with the given transactions and blob_gas_used header
453    /// value. timestamp = 1 so cancun_time = 0 is active.
454    fn make_block(transactions: Vec<Transaction>, blob_gas_used: u64) -> Block {
455        Block {
456            header: BlockHeader {
457                timestamp: 1,
458                gas_limit: 30_000_000,
459                blob_gas_used: Some(blob_gas_used),
460                excess_blob_gas: Some(0),
461                ..Default::default()
462            },
463            body: BlockBody {
464                transactions,
465                ommers: vec![],
466                withdrawals: Some(vec![]),
467            },
468        }
469    }
470
471    // --- EIP-4844 blob gas accounting (regression guard) ---
472
473    #[test]
474    fn eip4844_blob_gas_counts_correctly() {
475        let config = cancun_config();
476        let tx = Transaction::EIP4844Transaction(EIP4844Transaction {
477            blob_versioned_hashes: vec![H256::zero(), H256::zero()],
478            ..Default::default()
479        });
480        let block = make_block(vec![tx], 2 * GAS_PER_BLOB as u64);
481        assert!(verify_blob_gas_usage(&block, &config).is_ok());
482    }
483
484    #[test]
485    fn eip4844_blob_gas_mismatch_fails() {
486        let config = cancun_config();
487        let tx = Transaction::EIP4844Transaction(EIP4844Transaction {
488            blob_versioned_hashes: vec![H256::zero(), H256::zero()],
489            ..Default::default()
490        });
491        // Header claims 0 but actual is 2 * GAS_PER_BLOB
492        let block = make_block(vec![tx], 0);
493        assert!(matches!(
494            verify_blob_gas_usage(&block, &config),
495            Err(InvalidBlockError::BlobGasUsedMismatch)
496        ));
497    }
498}