Skip to main content

reth_ethereum_consensus/
validation.rs

1use alloc::vec::Vec;
2use alloy_consensus::{proofs::calculate_receipt_root, BlockHeader, TxReceipt};
3use alloy_eips::Encodable2718;
4use alloy_primitives::{Bloom, Bytes, B256};
5use reth_chainspec::EthereumHardforks;
6use reth_consensus::ConsensusError;
7use reth_execution_types::BlockExecutionResult;
8use reth_primitives_traits::{
9    receipt::gas_spent_by_transactions, Block, GotExpected, Receipt, RecoveredBlock,
10};
11
12/// Validate a block with regard to execution results:
13///
14/// - Compares the receipts root in the block header to the block body
15/// - Compares the gas used in the block header to the actual gas usage after execution
16/// - Compares the blob gas used in the block header to the blob gas consumed by the executed
17///   transactions if Cancun is active
18/// - Compares the computed Block Access List Hash to the value in the header if Amsterdam is active
19///
20/// If `receipt_root_bloom` is provided, the pre-computed receipt root and logs bloom are used
21/// instead of computing them from the receipts.
22pub fn validate_block_post_execution<B, R, ChainSpec>(
23    block: &RecoveredBlock<B>,
24    chain_spec: &ChainSpec,
25    result: &BlockExecutionResult<R>,
26    receipt_root_bloom: Option<(B256, Bloom)>,
27    block_access_list_hash: Option<B256>,
28) -> Result<(), ConsensusError>
29where
30    B: Block,
31    R: Receipt,
32    ChainSpec: EthereumHardforks,
33{
34    validate_block_post_execution_with_bal_hashes(
35        block,
36        chain_spec,
37        result,
38        receipt_root_bloom,
39        block_access_list_hash,
40        false,
41        false,
42        false,
43    )
44}
45
46/// Validate a block with regard to execution results, optionally allowing pre-Amsterdam BAL hashes
47/// and skipping the blob gas used and requests hash comparisons.
48///
49/// `skip_blob_gas_used_check` only skips the comparison of the header blob gas used against the
50/// executed blob gas, and `skip_requests_hash_check` only skips the comparison of the header
51/// requests hash against the executed requests; all other checks, including the block access list
52/// hash, still run.
53#[expect(clippy::too_many_arguments, reason = "each argument is an independent check input")]
54pub(crate) fn validate_block_post_execution_with_bal_hashes<B, R, ChainSpec>(
55    block: &RecoveredBlock<B>,
56    chain_spec: &ChainSpec,
57    result: &BlockExecutionResult<R>,
58    receipt_root_bloom: Option<(B256, Bloom)>,
59    block_access_list_hash: Option<B256>,
60    allow_bal_hashes: bool,
61    skip_blob_gas_used_check: bool,
62    skip_requests_hash_check: bool,
63) -> Result<(), ConsensusError>
64where
65    B: Block,
66    R: Receipt,
67    ChainSpec: EthereumHardforks,
68{
69    // Check if gas used matches the value set in header.
70    if block.header().gas_used() != result.gas_used {
71        return Err(ConsensusError::BlockGasUsed {
72            gas: GotExpected { got: result.gas_used, expected: block.header().gas_used() },
73            gas_spent_by_tx: gas_spent_by_transactions(&result.receipts),
74        })
75    }
76
77    // Pipeline bodies classified as empty skip pre-execution validation, so this is the only blob
78    // gas used check for them.
79    if !skip_blob_gas_used_check &&
80        chain_spec.is_cancun_active_at_timestamp(block.header().timestamp())
81    {
82        let Some(header_blob_gas_used) = block.header().blob_gas_used() else {
83            return Err(ConsensusError::BlobGasUsedMissing)
84        };
85        if header_blob_gas_used != result.blob_gas_used {
86            return Err(ConsensusError::BlobGasUsedDiff(GotExpected {
87                got: result.blob_gas_used,
88                expected: header_blob_gas_used,
89            }))
90        }
91    }
92
93    // Before Byzantium, receipts contained state root that would mean that expensive
94    // operation as hashing that is required for state root got calculated in every
95    // transaction This was replaced with is_success flag.
96    // See more about EIP here: https://eips.ethereum.org/EIPS/eip-658
97    if chain_spec.is_byzantium_active_at_block(block.header().number()) {
98        let res = if let Some((receipts_root, logs_bloom)) = receipt_root_bloom {
99            compare_receipts_root_and_logs_bloom(
100                receipts_root,
101                logs_bloom,
102                block.header().receipts_root(),
103                block.header().logs_bloom(),
104            )
105        } else {
106            verify_receipts(
107                block.header().receipts_root(),
108                block.header().logs_bloom(),
109                &result.receipts,
110            )
111        };
112
113        if let Err(error) = res {
114            let receipts = result
115                .receipts
116                .iter()
117                .map(|r| Bytes::from(r.with_bloom_ref().encoded_2718()))
118                .collect::<Vec<_>>();
119            tracing::debug!(%error, ?receipts, "receipts verification failed");
120            return Err(error)
121        }
122    }
123
124    // Validate that the header requests hash matches the calculated requests hash
125    if chain_spec.is_prague_active_at_timestamp(block.header().timestamp()) {
126        let Some(header_requests_hash) = block.header().requests_hash() else {
127            return Err(ConsensusError::RequestsHashMissing)
128        };
129        let requests_hash = result.requests.requests_hash();
130        if !skip_requests_hash_check && requests_hash != header_requests_hash {
131            return Err(ConsensusError::BodyRequestsHashDiff(
132                GotExpected::new(requests_hash, header_requests_hash).into(),
133            ))
134        }
135    }
136
137    // Validate that the header block access list hash matches the calculated block access list hash
138    let is_allowed_pre_amsterdam_bal_hash = allow_bal_hashes &&
139        !chain_spec.is_amsterdam_active_at_timestamp(block.header().timestamp()) &&
140        block.header().block_access_list_hash().is_some();
141
142    let is_amsterdam = chain_spec.is_amsterdam_active_at_timestamp(block.header().timestamp());
143    if is_amsterdam && block_access_list_hash.is_none() {
144        return Err(ConsensusError::BlockAccessListHashMissing)
145    }
146
147    if (is_amsterdam || is_allowed_pre_amsterdam_bal_hash) &&
148        let Some(block_access_list_hash) = block_access_list_hash
149    {
150        let block_bal_hash = block.header().block_access_list_hash().unwrap_or_default();
151        if block_access_list_hash != block_bal_hash {
152            return Err(ConsensusError::BlockAccessListHashMismatch(
153                GotExpected::new(block_access_list_hash, block_bal_hash).into(),
154            ))
155        }
156    }
157
158    Ok(())
159}
160
161/// Calculate the receipts root, and compare it against the expected receipts root and logs
162/// bloom.
163pub fn verify_receipts<R: Receipt>(
164    expected_receipts_root: B256,
165    expected_logs_bloom: Bloom,
166    receipts: &[R],
167) -> Result<(), ConsensusError> {
168    // Calculate receipts root.
169    let receipts_with_bloom = receipts.iter().map(TxReceipt::with_bloom_ref).collect::<Vec<_>>();
170    let receipts_root = calculate_receipt_root(&receipts_with_bloom);
171
172    // Calculate header logs bloom.
173    let logs_bloom = receipts_with_bloom.iter().fold(Bloom::ZERO, |bloom, r| bloom | r.bloom_ref());
174
175    compare_receipts_root_and_logs_bloom(
176        receipts_root,
177        logs_bloom,
178        expected_receipts_root,
179        expected_logs_bloom,
180    )
181}
182
183/// Compare the calculated receipts root with the expected receipts root, also compare
184/// the calculated logs bloom with the expected logs bloom.
185pub fn compare_receipts_root_and_logs_bloom(
186    calculated_receipts_root: B256,
187    calculated_logs_bloom: Bloom,
188    expected_receipts_root: B256,
189    expected_logs_bloom: Bloom,
190) -> Result<(), ConsensusError> {
191    if calculated_receipts_root != expected_receipts_root {
192        return Err(ConsensusError::BodyReceiptRootDiff(
193            GotExpected { got: calculated_receipts_root, expected: expected_receipts_root }.into(),
194        ))
195    }
196
197    if calculated_logs_bloom != expected_logs_bloom {
198        return Err(ConsensusError::BodyBloomLogDiff(
199            GotExpected { got: calculated_logs_bloom, expected: expected_logs_bloom }.into(),
200        ))
201    }
202
203    Ok(())
204}
205
206#[cfg(test)]
207mod tests {
208
209    use super::*;
210    use alloy_primitives::b256;
211    use reth_ethereum_primitives::Receipt;
212
213    #[test]
214    fn test_verify_receipts_success() {
215        // Create a vector of 5 default Receipt instances
216        let receipts: Vec<Receipt> = vec![Receipt::default(); 5];
217
218        // Compare against expected values
219        assert!(verify_receipts(
220            b256!("0x61353b4fb714dc1fccacbf7eafc4273e62f3d1eed716fe41b2a0cd2e12c63ebc"),
221            Bloom::ZERO,
222            &receipts
223        )
224        .is_ok());
225    }
226
227    #[test]
228    fn test_verify_receipts_incorrect_root() {
229        // Generate random expected values to produce a failure
230        let expected_receipts_root = B256::random();
231        let expected_logs_bloom = Bloom::random();
232
233        // Create a vector of 5 random Receipt instances
234        let receipts: Vec<Receipt> = vec![Receipt::default(); 5];
235
236        assert!(verify_receipts(expected_receipts_root, expected_logs_bloom, &receipts).is_err());
237    }
238
239    #[test]
240    fn test_compare_receipts_root_and_logs_bloom_success() {
241        let calculated_receipts_root = B256::random();
242        let calculated_logs_bloom = Bloom::random();
243
244        let expected_receipts_root = calculated_receipts_root;
245        let expected_logs_bloom = calculated_logs_bloom;
246
247        assert!(compare_receipts_root_and_logs_bloom(
248            calculated_receipts_root,
249            calculated_logs_bloom,
250            expected_receipts_root,
251            expected_logs_bloom
252        )
253        .is_ok());
254    }
255
256    #[test]
257    fn test_compare_receipts_root_failure() {
258        let calculated_receipts_root = B256::random();
259        let calculated_logs_bloom = Bloom::random();
260
261        let expected_receipts_root = B256::random();
262        let expected_logs_bloom = calculated_logs_bloom;
263
264        assert!(matches!(
265            compare_receipts_root_and_logs_bloom(
266                calculated_receipts_root,
267                calculated_logs_bloom,
268                expected_receipts_root,
269                expected_logs_bloom
270            ).unwrap_err(),
271            ConsensusError::BodyReceiptRootDiff(diff)
272                if diff.got == calculated_receipts_root && diff.expected == expected_receipts_root
273        ));
274    }
275
276    #[test]
277    fn test_compare_log_bloom_failure() {
278        let calculated_receipts_root = B256::random();
279        let calculated_logs_bloom = Bloom::random();
280
281        let expected_receipts_root = calculated_receipts_root;
282        let expected_logs_bloom = Bloom::random();
283
284        assert!(matches!(
285            compare_receipts_root_and_logs_bloom(
286                calculated_receipts_root,
287                calculated_logs_bloom,
288                expected_receipts_root,
289                expected_logs_bloom
290            ).unwrap_err(),
291            ConsensusError::BodyBloomLogDiff(diff)
292                if diff.got == calculated_logs_bloom && diff.expected == expected_logs_bloom
293        ));
294    }
295}