Skip to main content

reth_cli_commands/
re_execute.rs

1//! Re-execute blocks from database in parallel.
2
3use crate::common::{
4    AccessRights, CliComponentsBuilder, CliNodeComponents, CliNodeTypes, Environment,
5    EnvironmentArgs,
6};
7use alloy_consensus::{transaction::TxHashRef, BlockHeader, TxReceipt};
8use alloy_eip7928::bal::Bal;
9use alloy_primitives::{Address, B256, U256};
10use clap::Parser;
11use eyre::WrapErr;
12use reth_chainspec::{EthChainSpec, EthereumHardforks, Hardforks};
13use reth_cli::chainspec::ChainSpecParser;
14use reth_cli_util::cancellation::CancellationToken;
15use reth_concurrency::sync::thread;
16use reth_consensus::FullConsensus;
17use reth_evm::{database::StateProviderDatabase, execute::Executor, ConfigureEvm};
18use reth_node_core::args::JitArgs;
19use reth_primitives_traits::{format_gas_throughput, Account, BlockBody, GotExpected};
20use reth_provider::{
21    providers::BlockchainProvider, BlockHashReader, BlockNumReader, BlockReader, ChainSpecProvider,
22    DatabaseProviderFactory, ReceiptProvider, StaticFileProviderFactory, TransactionVariant,
23};
24use reth_stages::stages::calculate_gas_used_from_headers;
25use reth_storage_api::{ChangeSetReader, DBProvider, StateProvider, StorageChangeSetReader};
26use reth_trie::bundle_state::{AccountInfoRevert, BundleState, RevertToSlot};
27use std::{
28    collections::HashMap,
29    sync::{
30        atomic::{AtomicU64, Ordering},
31        Arc,
32    },
33    time::{Duration, Instant},
34};
35use tokio::{sync::mpsc, task::JoinSet};
36use tracing::*;
37
38/// `reth re-execute` command
39///
40/// Re-execute blocks in parallel to verify historical sync correctness.
41#[derive(Debug, Parser)]
42pub struct Command<C: ChainSpecParser> {
43    #[command(flatten)]
44    env: EnvironmentArgs<C>,
45
46    /// The height to start at.
47    #[arg(long, default_value = "1", value_parser = clap::value_parser!(u64).range(1..))]
48    from: u64,
49
50    /// The height to end at. Defaults to the latest block.
51    #[arg(long)]
52    to: Option<u64>,
53
54    /// Number of tasks to run in parallel. Defaults to the number of available CPUs.
55    #[arg(long, value_parser = clap::value_parser!(u64).range(1..))]
56    num_tasks: Option<u64>,
57
58    /// Number of blocks each worker processes before grabbing the next chunk.
59    #[arg(long, default_value = "5000", value_parser = clap::value_parser!(u64).range(1..))]
60    blocks_per_chunk: u64,
61
62    /// Continues with execution when an invalid block is encountered and collects these blocks.
63    #[arg(long)]
64    skip_invalid_blocks: bool,
65
66    #[command(flatten)]
67    pub jit: JitArgs,
68}
69
70impl<C: ChainSpecParser> Command<C> {
71    /// Returns the underlying chain being used to run this command
72    pub fn chain_spec(&self) -> Option<&Arc<C::ChainSpec>> {
73        Some(&self.env.chain)
74    }
75}
76
77impl<C: ChainSpecParser<ChainSpec: EthChainSpec + Hardforks + EthereumHardforks>> Command<C> {
78    /// Execute `re-execute` command
79    pub async fn execute<N>(
80        mut self,
81        components: impl CliComponentsBuilder<N>,
82        runtime: reth_tasks::Runtime,
83    ) -> eyre::Result<()>
84    where
85        N: CliNodeTypes<ChainSpec = C::ChainSpec>,
86    {
87        // Default to 4GB RocksDB block cache for re-execute unless explicitly set.
88        if self.env.db.rocksdb_block_cache_size.is_none() {
89            self.env.db.rocksdb_block_cache_size = Some(4 << 30);
90        }
91
92        let Environment { provider_factory, .. } = self.env.init::<N>(AccessRights::RO, runtime)?;
93
94        let components = components(provider_factory.chain_spec());
95
96        let min_block = self.from;
97        let best_block = DatabaseProviderFactory::database_provider_ro(&provider_factory)?
98            .best_block_number()?;
99        let mut max_block = best_block;
100        if let Some(to) = self.to {
101            if to > best_block {
102                warn!(
103                    requested = to,
104                    best_block,
105                    "Requested --to is beyond available chain head; clamping to best block"
106                );
107            } else {
108                max_block = to;
109            }
110        };
111
112        if min_block > max_block {
113            eyre::bail!("--from ({min_block}) is beyond --to ({max_block}), nothing to re-execute");
114        }
115
116        let num_tasks = self.num_tasks.unwrap_or_else(|| {
117            thread::available_parallelism().map(|n| n.get() as u64).unwrap_or(10)
118        });
119
120        let total_gas = calculate_gas_used_from_headers(
121            &provider_factory.static_file_provider(),
122            min_block..=max_block,
123        )?;
124
125        let skip_invalid_blocks = self.skip_invalid_blocks;
126        let blocks_per_chunk = self.blocks_per_chunk;
127        let (stats_tx, mut stats_rx) = mpsc::unbounded_channel();
128        let (info_tx, mut info_rx) = mpsc::unbounded_channel();
129        let cancellation = CancellationToken::new();
130        let _guard = cancellation.drop_guard();
131
132        // Shared counter for work stealing: workers atomically grab the next chunk of blocks.
133        let next_block = Arc::new(AtomicU64::new(min_block));
134
135        let mut tasks = JoinSet::new();
136        for _ in 0..num_tasks {
137            let provider_factory = provider_factory.clone();
138            let evm_config = components.evm_config().clone();
139            let consensus = components.consensus().clone();
140            let stats_tx = stats_tx.clone();
141            let info_tx = info_tx.clone();
142            let cancellation = cancellation.clone();
143            let next_block = Arc::clone(&next_block);
144            tasks.spawn_blocking(move || {
145                let evm_config = evm_config.with_jit_support();
146                let executor_lifetime = Duration::from_secs(600);
147                let provider = provider_factory.database_provider_ro()?.disable_long_read_transaction_safety();
148                let state_provider_factory = BlockchainProvider::new(provider_factory.clone())?;
149                // Reused across blocks for BAL hash encoding.
150                let mut bal_buf = Vec::new();
151
152                let db_at = {
153                    |block_number: u64| {
154                        let provider = state_provider_factory.long_read_consistent_provider()?;
155                        let hash = provider.block_hash(block_number)?.ok_or_else(|| {
156                            eyre::eyre!("hash for block {block_number} not found in the database")
157                        })?;
158                        eyre::Ok(StateProviderDatabase(
159                            provider.state_by_hash(hash, false)?.into_evm_state_provider(),
160                        ))
161                    }
162                };
163
164                loop {
165                    if cancellation.is_cancelled() {
166                        break;
167                    }
168
169                    // Atomically grab the next chunk of blocks.
170                    let chunk_start =
171                        next_block.fetch_add(blocks_per_chunk, Ordering::Relaxed);
172                    if chunk_start > max_block {
173                        break;
174                    }
175                    let chunk_end = (chunk_start + blocks_per_chunk).min(max_block + 1);
176
177                    let mut executor = evm_config.batch_executor(db_at(chunk_start - 1)?);
178                    let mut executor_created = Instant::now();
179
180                    'blocks: for block in chunk_start..chunk_end {
181                        if cancellation.is_cancelled() {
182                            break;
183                        }
184
185                        let block = provider_factory
186                            .recovered_block(block.into(), TransactionVariant::NoHash)?
187                            .ok_or_else(|| eyre::eyre!("block {block} not found in the database"))?;
188
189                        let result = match executor.execute_one(&block) {
190                            Ok(result) => result,
191                            Err(err) => {
192                                if skip_invalid_blocks {
193                                    executor =
194                                        evm_config.batch_executor(db_at(block.number())?);
195                                    let _ =
196                                        info_tx.send((block, eyre::Report::new(err)));
197                                    continue
198                                }
199                                return Err(err.into())
200                            }
201                        };
202
203                        let bal_hash = executor
204                            .take_bal()
205                            .map(|bal| Bal::from(bal).compute_hash_with_buf(&mut bal_buf));
206
207                        if let Err(err) = consensus
208                            .validate_block_post_execution(&block, &result, None, bal_hash)
209                            .wrap_err_with(|| {
210                                format!(
211                                    "Failed to validate block {} {}",
212                                    block.number(),
213                                    block.hash()
214                                )
215                            })
216                        {
217                            let correct_receipts = provider_factory
218                                .receipts_by_block(block.number().into())?
219                                .ok_or_else(|| {
220                                    eyre::eyre!(
221                                        "receipts for block {} not found in the database",
222                                        block.number()
223                                    )
224                                })?;
225
226                            for (i, (receipt, correct_receipt)) in
227                                result.receipts.iter().zip(correct_receipts.iter()).enumerate()
228                            {
229                                if receipt != correct_receipt {
230                                    let tx_hash =
231                                        block.body().transactions()[i].tx_hash();
232                                    error!(
233                                        ?receipt,
234                                        ?correct_receipt,
235                                        index = i,
236                                        ?tx_hash,
237                                        "Invalid receipt"
238                                    );
239                                    let expected_gas_used =
240                                        correct_receipt.cumulative_gas_used() -
241                                            if i == 0 {
242                                                0
243                                            } else {
244                                                correct_receipts[i - 1]
245                                                    .cumulative_gas_used()
246                                            };
247                                    let got_gas_used = receipt.cumulative_gas_used() -
248                                        if i == 0 {
249                                            0
250                                        } else {
251                                            result.receipts[i - 1].cumulative_gas_used()
252                                        };
253                                    if got_gas_used != expected_gas_used {
254                                        let mismatch = GotExpected {
255                                            expected: expected_gas_used,
256                                            got: got_gas_used,
257                                        };
258
259                                        error!(number=?block.number(), ?mismatch, "Gas usage mismatch");
260                                        if skip_invalid_blocks {
261                                            executor = evm_config
262                                                .batch_executor(db_at(block.number())?);
263                                            let _ = info_tx.send((block, err));
264                                            continue 'blocks;
265                                        }
266                                        return Err(err);
267                                    }
268                                } else {
269                                    continue;
270                                }
271                            }
272
273                            if skip_invalid_blocks {
274                                executor =
275                                    evm_config.batch_executor(db_at(block.number())?);
276                                let _ = info_tx.send((block, err));
277                                continue 'blocks;
278                            }
279                            return Err(err);
280                        }
281                        let _ = stats_tx.send((block.number(), block.gas_used()));
282
283                        // Reset DB once in a while to avoid OOM or read tx timeouts
284                        if executor.size_hint() > 5_000_000 ||
285                            executor_created.elapsed() > executor_lifetime
286                        {
287                            let last_block = block.number();
288                            let old_executor = std::mem::replace(
289                                &mut executor,
290                                evm_config.batch_executor(db_at(last_block)?),
291                            );
292                            let bundle = old_executor.into_state();
293                            verify_bundle_against_changesets(
294                                &provider,
295                                &bundle,
296                                last_block,
297                            )?;
298                            executor_created = Instant::now();
299                        }
300                    }
301
302                    // Full verification at chunk end for remaining unverified blocks
303                    let bundle = executor.into_state();
304                    verify_bundle_against_changesets(
305                        &provider,
306                        &bundle,
307                        chunk_end - 1,
308                    )?;
309                }
310
311                eyre::Ok(())
312            });
313        }
314
315        let instant = Instant::now();
316        let mut total_executed_blocks = 0;
317        let mut total_executed_gas = 0;
318        let mut latest_executed_block = None;
319
320        let mut last_logged_gas = 0;
321        let mut last_logged_blocks = 0;
322        let mut last_logged_time = Instant::now();
323        let mut invalid_blocks = Vec::new();
324
325        let mut interval = tokio::time::interval(Duration::from_secs(10));
326
327        loop {
328            tokio::select! {
329                Some((block_number, gas_used)) = stats_rx.recv() => {
330                    total_executed_blocks += 1;
331                    total_executed_gas += gas_used;
332                    latest_executed_block =
333                        Some(latest_executed_block.unwrap_or(block_number).max(block_number));
334                }
335                Some((block, err)) = info_rx.recv() => {
336                    error!(?err, block=?block.num_hash(), "Invalid block");
337                    invalid_blocks.push(block.num_hash());
338                }
339                result = tasks.join_next() => {
340                    let Some(result) = result else { break };
341                    match result {
342                        Ok(Ok(())) => {}
343                        Ok(Err(err)) => return Err(err.wrap_err("Re-execution failed")),
344                        Err(err) => {
345                            return Err(eyre::Report::new(err).wrap_err("Re-execution failed"))
346                        }
347                    }
348                }
349                _ = interval.tick() => {
350                    let blocks_executed = total_executed_blocks - last_logged_blocks;
351                    let gas_executed = total_executed_gas - last_logged_gas;
352
353                    if blocks_executed > 0 {
354                        let progress = 100.0 * total_executed_gas as f64 / total_gas as f64;
355                        info!(
356                            throughput=?format_gas_throughput(gas_executed, last_logged_time.elapsed()),
357                            progress=format!("{progress:.2}%"),
358                            ?latest_executed_block,
359                            "Executed {blocks_executed} blocks"
360                        );
361                    }
362
363                    last_logged_blocks = total_executed_blocks;
364                    last_logged_gas = total_executed_gas;
365                    last_logged_time = Instant::now();
366                }
367            }
368        }
369
370        if invalid_blocks.is_empty() {
371            info!(
372                start_block = min_block,
373                end_block = max_block,
374                %total_executed_blocks,
375                ?latest_executed_block,
376                throughput=?format_gas_throughput(total_executed_gas, instant.elapsed()),
377                "Re-executed successfully"
378            );
379        } else {
380            info!(
381                start_block = min_block,
382                end_block = max_block,
383                %total_executed_blocks,
384                ?latest_executed_block,
385                invalid_block_count = invalid_blocks.len(),
386                ?invalid_blocks,
387                throughput=?format_gas_throughput(total_executed_gas, instant.elapsed()),
388                "Re-executed with invalid blocks"
389            );
390        }
391
392        Ok(())
393    }
394}
395
396/// Verifies reverts against database changesets.
397///
398/// For each block, reverts must match changeset entries exactly. No extra slots/accounts
399/// in reverts for non-destroyed accounts. Destroyed accounts may have extra changeset slots
400/// (from DB storage wipe) absent from reverts.
401fn verify_bundle_against_changesets<P>(
402    provider: &P,
403    bundle: &BundleState,
404    last_block: u64,
405) -> eyre::Result<()>
406where
407    P: ChangeSetReader + StorageChangeSetReader,
408{
409    // Verify reverts against changesets per block
410    for (i, block_reverts) in bundle.reverts.iter().rev().enumerate() {
411        let block_number = last_block - i as u64;
412
413        let mut cs_accounts: HashMap<Address, Option<Account>> = provider
414            .account_block_changeset(block_number)?
415            .into_iter()
416            .map(|cs| (cs.address, cs.info))
417            .collect();
418
419        let mut cs_storage: HashMap<Address, HashMap<B256, U256>> = HashMap::new();
420        for (bna, entry) in provider.storage_changeset(block_number)? {
421            cs_storage.entry(bna.address()).or_default().insert(entry.key, entry.value);
422        }
423
424        for (addr, revert) in block_reverts {
425            // Verify account info
426            match &revert.account {
427                AccountInfoRevert::DoNothing => {
428                    eyre::ensure!(
429                        !cs_accounts.contains_key(addr),
430                        "Block {block_number}: account {addr} in changeset but revert is DoNothing",
431                    );
432                }
433                AccountInfoRevert::DeleteIt => {
434                    let cs_info = cs_accounts.remove(addr).ok_or_else(|| {
435                        eyre::eyre!("Block {block_number}: account {addr} revert is DeleteIt but not in changeset")
436                    })?;
437                    eyre::ensure!(
438                        cs_info.is_none(),
439                        "Block {block_number}: account {addr} revert is DeleteIt but changeset has {cs_info:?}",
440                    );
441                }
442                AccountInfoRevert::RevertTo(info) => {
443                    let cs_info = cs_accounts.remove(addr).ok_or_else(|| {
444                        eyre::eyre!("Block {block_number}: account {addr} revert is RevertTo but not in changeset")
445                    })?;
446                    let revert_acct = Some(Account::from(info));
447                    eyre::ensure!(
448                        revert_acct == cs_info,
449                        "Block {block_number}: account {addr} info mismatch: revert={revert_acct:?} cs={cs_info:?}",
450                    );
451                }
452            }
453
454            // Verify storage slots — remove matched changeset entries as we go
455            let mut cs_slots = cs_storage.get_mut(addr);
456            for (slot_key, revert_slot) in &revert.storage {
457                let b256_key = B256::from(*slot_key);
458                let cs_value = cs_slots.as_mut().and_then(|s| s.remove(&b256_key));
459                match (revert_slot, cs_value) {
460                    // When a contract is selfdestructed and re-created at the same address
461                    // within the same block, revm marks slots touched by the new contract
462                    // as `Destroyed` and never reads the original DB value, so
463                    // `to_previous_value()` would resolve to zero, which might be wrong.
464                    (RevertToSlot::Destroyed, _) => {}
465                    (RevertToSlot::Some(prev), Some(cs_value)) => eyre::ensure!(
466                        *prev == cs_value,
467                        "Block {block_number}: {addr} slot {b256_key} mismatch: \
468                         revert={prev} cs={cs_value}",
469                    ),
470                    (RevertToSlot::Some(_), None) => eyre::ensure!(
471                        revert.wipe_storage,
472                        "Block {block_number}: {addr} slot {b256_key} in reverts but not in changeset",
473                    ),
474                }
475            }
476
477            // Any remaining cs_storage slots for this address must be from a destroyed account
478            if let Some(remaining) = cs_slots.filter(|s| !s.is_empty()) {
479                eyre::ensure!(
480                    revert.wipe_storage,
481                    "Block {block_number}: {addr} has {} unmatched storage slots in changeset",
482                    remaining.len(),
483                );
484            }
485        }
486
487        // Any remaining cs_accounts entries had no corresponding revert
488        if let Some(addr) = cs_accounts.keys().next() {
489            eyre::bail!("Block {block_number}: account {addr} in changeset but not in reverts");
490        }
491    }
492
493    Ok(())
494}