Skip to main content

reth_cli_commands/
export_era.rs

1//! Command that exports block history from the database into ERA files.
2
3use crate::common::{AccessRights, CliNodeTypes, Environment, EnvironmentArgs};
4use clap::{Args, Parser};
5use reth_chainspec::{EthChainSpec, EthereumHardfork, EthereumHardforks, ForkCondition};
6use reth_cli::chainspec::ChainSpecParser;
7use reth_era::era1::types::execution::MAX_BLOCKS_PER_ERA1;
8use reth_era_utils as era;
9use reth_provider::{BlockBodyIndicesProvider, BlockNumReader, DatabaseProviderFactory};
10use std::{ops::RangeInclusive, path::PathBuf, sync::Arc};
11use tracing::info;
12
13#[derive(Debug, Parser)]
14pub struct ExportEraCommand<C: ChainSpecParser> {
15    #[command(flatten)]
16    env: EnvironmentArgs<C>,
17
18    #[clap(flatten)]
19    export: ExportArgs,
20}
21
22#[derive(Debug, Args)]
23pub struct ExportArgs {
24    /// The ERA file format to export: `era1` writes `.era1` files, `ere` writes `.ere` files.
25    #[arg(long, value_enum, default_value_t = ExportFileType::Era1, verbatim_doc_comment)]
26    file_type: ExportFileType,
27    /// Optional first block number to export from the db.
28    /// It is by default 0.
29    /// Blocks before Byzantium can only be exported if they have no receipts.
30    #[arg(long, value_name = "first-block-number", verbatim_doc_comment)]
31    first_block_number: Option<u64>,
32    /// Optional last block number to export from the db.
33    /// It is by default 8191.
34    #[arg(long, value_name = "last-block-number", verbatim_doc_comment)]
35    last_block_number: Option<u64>,
36    /// The maximum number of blocks per file, it can help you to decrease the size of the files.
37    /// Must be less than or equal to 8192.
38    #[arg(long, value_name = "max-blocks-per-file", verbatim_doc_comment)]
39    max_blocks_per_file: Option<u64>,
40    /// The directory where the exported ERA files are written.
41    /// Defaults to `<data-dir>/<chain>/<format>-export/`, where `<format>` is `era1` or `ere`.
42    #[arg(long, value_name = "EXPORT_PATH", verbatim_doc_comment)]
43    path: Option<PathBuf>,
44}
45
46/// ERA formats accepted by `--file-type`.
47///
48/// Only `era1`/`ere` are exportable; `era` is listed but rejected at runtime.
49#[derive(Debug, Clone, Copy, clap::ValueEnum)]
50enum ExportFileType {
51    /// Execution blocks written in the `.era1` format.
52    Era1,
53    /// Execution blocks written in the `.ere` format.
54    Ere,
55    /// Consensus-layer `.era` format. Not exportable from an execution client; selecting it is an
56    /// error.
57    Era,
58}
59
60impl ExportFileType {
61    /// The format name (`era1` / `ere` / `era`), used for log lines and the default directory name.
62    const fn format(&self) -> &'static str {
63        match self {
64            Self::Era1 => "era1",
65            Self::Ere => "ere",
66            Self::Era => "era",
67        }
68    }
69
70    /// Rejects consensus-layer `.era`, which can't be produced from the execution database.
71    fn ensure_exportable(self) -> eyre::Result<()> {
72        if matches!(self, Self::Era) {
73            return Err(era_not_exportable());
74        }
75        Ok(())
76    }
77}
78
79/// Error returned when a consensus-layer `.era` export is requested. Such files require beacon
80/// blocks and state that the execution database does not store.
81fn era_not_exportable() -> eyre::Report {
82    eyre::eyre!(
83        "Consensus-layer ERA (.era) files cannot be exported: they require beacon blocks and \
84         state that the execution database does not store. Export `era1` or `ere` instead."
85    )
86}
87
88impl<C: ChainSpecParser<ChainSpec: EthChainSpec + EthereumHardforks>> ExportEraCommand<C> {
89    /// Execute `export-era` command
90    pub async fn execute<N>(self, runtime: reth_tasks::Runtime) -> eyre::Result<()>
91    where
92        N: CliNodeTypes<ChainSpec = C::ChainSpec>,
93    {
94        let file_type = self.export.file_type;
95        file_type.ensure_exportable()?;
96        let format = file_type.format();
97
98        let Environment { provider_factory, .. } = self.env.init::<N>(AccessRights::RO, runtime)?;
99
100        // Either the specified path or default to `<data-dir>/<chain>/<format>-export/`.
101        let data_dir = match &self.export.path {
102            Some(path) => path.clone(),
103            None => self
104                .env
105                .datadir
106                .resolve_datadir(self.env.chain.chain())
107                .data_dir()
108                .join(format!("{format}-export")),
109        };
110
111        let export_config = era::ExportConfig {
112            network: self.env.chain.chain().to_string(),
113            first_block_number: self.export.first_block_number.unwrap_or(0),
114            last_block_number: self
115                .export
116                .last_block_number
117                .unwrap_or(MAX_BLOCKS_PER_ERA1 as u64 - 1),
118            max_blocks_per_file: self
119                .export
120                .max_blocks_per_file
121                .unwrap_or(MAX_BLOCKS_PER_ERA1 as u64),
122            dir: data_dir,
123        };
124
125        export_config.validate()?;
126
127        info!(
128            target: "reth::cli",
129            "Starting {format} block export: blocks {}-{} to {}",
130            export_config.first_block_number,
131            export_config.last_block_number,
132            export_config.dir.display()
133        );
134
135        // Only read access is needed for the database provider.
136        let provider = provider_factory.database_provider_ro()?;
137
138        ensure_receipts_exportable(
139            &provider,
140            export_config.first_block_number..=export_config.last_block_number,
141            self.env.chain.ethereum_fork_activation(EthereumHardfork::Byzantium),
142        )?;
143
144        let exported_files = match file_type {
145            ExportFileType::Era1 => era::export::<era::Era1, _>(&provider, &export_config)?,
146            ExportFileType::Ere => era::export::<era::Ere, _>(&provider, &export_config)?,
147            // Rejected above by `ensure_exportable`.
148            ExportFileType::Era => return Err(era_not_exportable()),
149        };
150
151        info!(
152            target: "reth::cli",
153            "Successfully exported {} {format} files to {}",
154            exported_files.len(),
155            export_config.dir.display()
156        );
157
158        Ok(())
159    }
160}
161
162impl<C: ChainSpecParser> ExportEraCommand<C> {
163    /// Returns the underlying chain being used to run this command
164    pub fn chain_spec(&self) -> Option<&Arc<C::ChainSpec>> {
165        Some(&self.env.chain)
166    }
167}
168
169/// Check the transaction numbers at the two ends of the pre-Byzantium range before writing files.
170/// Equal numbers mean that every block in the range has an empty receipt list.
171fn ensure_receipts_exportable(
172    provider: &(impl BlockBodyIndicesProvider + BlockNumReader),
173    range: RangeInclusive<u64>,
174    byzantium: ForkCondition,
175) -> eyre::Result<()> {
176    let first = *range.start();
177    let mut last = *range.end();
178    if let Some(activation) = byzantium.block_number() {
179        if first >= activation {
180            return Ok(())
181        }
182        last = last.min(activation - 1);
183    }
184    let last = last.min(provider.last_block_number()?);
185    if first > last {
186        return Ok(())
187    }
188    let first_tx = match first.checked_sub(1) {
189        Some(previous) => provider.next_tx_num_after_block(previous)?,
190        None => 0,
191    };
192    if first_tx < provider.next_tx_num_after_block(last)? {
193        eyre::bail!(
194            "cannot export blocks {first}..={last}: the range contains pre-Byzantium receipts, \
195             which require post-state roots. The Reth database stores only success flags"
196        )
197    }
198    Ok(())
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204    use alloy_consensus::Header;
205    use reth_db::models::StoredBlockBodyIndices;
206    use reth_provider::test_utils::MockEthProvider;
207
208    #[test]
209    fn checks_only_transactions_in_the_pre_byzantium_part_of_the_range() {
210        let provider = MockEthProvider::default().with_genesis_block();
211        // Only block 2 has a transaction. Block 3 is the last available block.
212        for (number, first_tx_num, tx_count) in [(0, 0, 0), (1, 0, 0), (2, 0, 1), (3, 1, 0)] {
213            provider
214                .add_block_body_indices(number, StoredBlockBodyIndices { first_tx_num, tx_count });
215            let header = Header { number, ..Default::default() };
216            provider.add_header(header.hash_slow(), header);
217        }
218        let byzantium = ForkCondition::Block(3);
219        assert_eq!(
220            ensure_receipts_exportable(&provider, 0..=3, byzantium).unwrap_err().to_string(),
221            "cannot export blocks 0..=2: the range contains pre-Byzantium receipts, \
222             which require post-state roots. The Reth database stores only success flags"
223        );
224        ensure_receipts_exportable(&provider, 0..=1, byzantium).unwrap();
225        ensure_receipts_exportable(&provider, 3..=3, byzantium).unwrap();
226        ensure_receipts_exportable(&provider, 0..=3, ForkCondition::Block(2)).unwrap();
227        ensure_receipts_exportable(&provider, 3..=10, ForkCondition::Never).unwrap();
228        ensure_receipts_exportable(&provider, 4..=10, ForkCondition::Never).unwrap();
229    }
230}