Skip to main content

reth_era_utils/export/
mod.rs

1//! Exports node block history from storage into ERA files.
2//!
3//! [`export`] is the format-agnostic driver: it resolves the export range, walks the requested
4//! blocks in `max_blocks_per_file` chunks, and hands each chunk to an [`EraBlockWriter`]. A writer
5//! turns one chunk of [`ExportBlock`]s into one on-disk file and owns every format-specific detail
6//! (receipt encoding, accumulator, block index, record layout, file naming).
7//!
8//! [`Era1`](crate::Era1) writes `.era1` files and [`Ere`](crate::Ere) writes `.ere` files.
9
10mod era1;
11mod ere;
12
13use crate::{calculate_td_by_number, history::verify_receipts};
14use alloy_consensus::{BlockHeader, Sealable};
15use alloy_primitives::{BlockNumber, B256, U256};
16use alloy_rlp::Encodable;
17use eyre::{eyre, Result};
18use reth_era::era1::types::execution::MAX_BLOCKS_PER_ERA1;
19use reth_fs_util as fs;
20use reth_primitives_traits::{Block, Receipt};
21use reth_storage_api::{BlockNumReader, BlockReader, HeaderProvider, ReceiptProvider};
22use std::{
23    path::{Path, PathBuf},
24    time::{Duration, Instant},
25};
26use tracing::{info, warn};
27
28/// Minimum delay between export progress log lines, so large exports report periodically without
29/// flooding the logs.
30const REPORT_INTERVAL_SECS: u64 = 10;
31
32/// Configuration to export block history to ERA files.
33///
34/// Shared by every [`EraBlockWriter`]; the per-file block ceiling is the same `8192` for all
35/// formats.
36#[derive(Clone, Debug)]
37pub struct ExportConfig {
38    /// Directory to export ERA files to
39    pub dir: PathBuf,
40    /// First block to export
41    pub first_block_number: BlockNumber,
42    /// Last block to export
43    pub last_block_number: BlockNumber,
44    /// Number of blocks per ERA file.
45    /// It can never be larger than `MAX_BLOCKS_PER_ERA1 = 8192`
46    /// See also <`https://github.com/eth-clients/e2store-format-specs/blob/main/formats/era1.md`>
47    pub max_blocks_per_file: u64,
48    /// Network name.
49    pub network: String,
50}
51
52impl Default for ExportConfig {
53    fn default() -> Self {
54        Self {
55            dir: PathBuf::new(),
56            first_block_number: 0,
57            last_block_number: (MAX_BLOCKS_PER_ERA1 - 1) as u64,
58            max_blocks_per_file: MAX_BLOCKS_PER_ERA1 as u64,
59            network: "mainnet".to_string(),
60        }
61    }
62}
63
64impl ExportConfig {
65    /// Validates the export configuration parameters
66    pub fn validate(&self) -> Result<()> {
67        if self.max_blocks_per_file > MAX_BLOCKS_PER_ERA1 as u64 {
68            return Err(eyre!(
69                "Max blocks per file ({}) exceeds ERA1 limit ({})",
70                self.max_blocks_per_file,
71                MAX_BLOCKS_PER_ERA1
72            ));
73        }
74
75        if self.max_blocks_per_file == 0 {
76            return Err(eyre!("Max blocks per file cannot be zero"));
77        }
78
79        Ok(())
80    }
81}
82
83/// One block's data, gathered by [`export`] and handed to an [`EraBlockWriter`].
84#[derive(Debug)]
85pub struct ExportBlock<H, B, R> {
86    /// Block header.
87    pub header: H,
88    /// Hash of `header`, feeding the file's accumulator.
89    pub block_hash: B256,
90    /// Block body.
91    pub body: B,
92    /// Block receipts in the provider's native, bloom-bearing form. A writer re-encodes them into
93    /// its own form (`era1` keeps the bloom, `ere` stores the slim variant).
94    pub receipts: Vec<R>,
95    /// Total difficulty up to and including this block.
96    pub total_difficulty: U256,
97}
98
99impl<H, B, R> ExportBlock<H, B, R> {
100    /// The `(block_hash, total_difficulty)` pair that feeds an ERA file's header-record
101    /// accumulator.
102    ///
103    /// The accumulator record type differs per format, so each writer wraps this pair in its own
104    /// `HeaderRecord`.
105    pub const fn header_record(&self) -> (B256, U256) {
106        (self.block_hash, self.total_difficulty)
107    }
108}
109
110/// Writes a chunk of consecutive blocks as a single ERA file.
111///
112/// One implementor exists per ERA format. A chunk is ordered, non-empty, and at most
113/// [`ExportConfig::max_blocks_per_file`] blocks long.
114pub trait EraBlockWriter {
115    /// Writes `blocks` as a single ERA file in `dir`, returning the created file's path.
116    ///
117    /// `max_blocks_per_file` is the configured per-file ceiling; a writer compares it against its
118    /// own format limit to decide whether the filename carries an era-count segment.
119    fn write_file<H, B, R>(
120        network: &str,
121        max_blocks_per_file: u64,
122        blocks: &[ExportBlock<H, B, R>],
123        dir: &Path,
124    ) -> Result<PathBuf>
125    where
126        H: BlockHeader + Encodable,
127        B: Encodable,
128        R: Receipt;
129}
130
131/// Per-format accumulator over a chunk's header records.
132///
133/// Each ERA format defines its own accumulator and header-record types in [`reth_era`], yet both
134/// build the accumulator from the same `(block_hash, total_difficulty)` pairs. This trait is the
135/// seam that keeps [`accumulator`] format-agnostic.
136pub(crate) trait ChunkAccumulator: Sized {
137    /// Builds the accumulator from the chunk's `(block_hash, total_difficulty)` header records.
138    fn from_pairs(records: &[(B256, U256)]) -> Result<Self>;
139}
140
141/// Computes the chunk's accumulator from each block's `(block_hash, total_difficulty)` header
142/// record, in the format `A`.
143fn accumulator<A, H, B, R>(blocks: &[ExportBlock<H, B, R>]) -> Result<A>
144where
145    A: ChunkAccumulator,
146{
147    let records: Vec<(B256, U256)> = blocks.iter().map(ExportBlock::header_record).collect();
148    A::from_pairs(&records)
149}
150
151/// A chunk of [`ExportBlock`]s sourced from provider `P`.
152type Chunk<P> =
153    Vec<ExportBlock<<P as HeaderProvider>::Header, BodyOf<P>, <P as ReceiptProvider>::Receipt>>;
154
155/// The block body type produced by provider `P`.
156type BodyOf<P> = <<P as BlockReader>::Block as Block>::Body;
157
158/// Fetches block history from `provider` and writes it to ERA files in the `W` format, chunked by
159/// [`ExportConfig::max_blocks_per_file`].
160///
161/// Returns the paths of the files that were created. A receipt mismatch with the block header
162/// returns an error before the affected chunk is written. Files from earlier chunks remain in
163/// the output directory.
164pub fn export<W, P>(provider: &P, config: &ExportConfig) -> Result<Vec<PathBuf>>
165where
166    W: EraBlockWriter,
167    P: BlockReader,
168    P::Header: BlockHeader + Sealable + Encodable,
169    BodyOf<P>: Encodable,
170    P::Receipt: Receipt,
171{
172    config.validate()?;
173
174    // `best_block_number()` can be stale behind static files, so reconcile against what is actually
175    // available.
176    let last_block = determine_export_range(provider, config)?;
177
178    info!(
179        target: "era::history::export",
180        first = config.first_block_number,
181        last = last_block,
182        max_blocks_per_file = config.max_blocks_per_file,
183        "Preparing ERA export data"
184    );
185
186    if !config.dir.exists() {
187        fs::create_dir_all(&config.dir)
188            .map_err(|e| eyre!("Failed to create output directory: {}", e))?;
189    }
190
191    let mut progress = ExportProgress::new(last_block - config.first_block_number + 1);
192    let mut total_difficulty = seed_total_difficulty(provider, config)?;
193    let mut created_files = Vec::new();
194
195    for start_block in
196        (config.first_block_number..=last_block).step_by(config.max_blocks_per_file as usize)
197    {
198        let end_block = (start_block + config.max_blocks_per_file - 1).min(last_block);
199
200        let blocks = gather_chunk(
201            provider,
202            start_block..=end_block,
203            last_block,
204            &mut total_difficulty,
205            &mut progress,
206        )?;
207        if blocks.is_empty() {
208            continue;
209        }
210
211        let file_path =
212            W::write_file(&config.network, config.max_blocks_per_file, &blocks, &config.dir)?;
213
214        info!(target: "era::history::export", "Wrote ERA file: {file_path:?} with {} blocks", blocks.len());
215        created_files.push(file_path);
216    }
217
218    info!(
219        target: "era::history::export",
220        "Successfully wrote {} ERA files in {:?}",
221        created_files.len(),
222        progress.elapsed()
223    );
224
225    Ok(created_files)
226}
227
228/// The four-byte short hash an ERA file name carries, taken from its accumulator root.
229fn short_hash(root: B256) -> [u8; 4] {
230    root[..4].try_into().expect("root is 32 bytes")
231}
232
233/// Total difficulty up to the block preceding the export range, the starting point for the running
234/// total threaded through every chunk.
235fn seed_total_difficulty<P: BlockReader>(provider: &P, config: &ExportConfig) -> Result<U256> {
236    if config.first_block_number > 0 {
237        calculate_td_by_number(provider, config.first_block_number - 1)
238    } else {
239        Ok(U256::ZERO)
240    }
241}
242
243/// Loads the headers, bodies and receipts for `range` into a [`Chunk`], advancing
244/// `total_difficulty` by each header's difficulty.
245fn gather_chunk<P>(
246    provider: &P,
247    range: std::ops::RangeInclusive<BlockNumber>,
248    last_block: BlockNumber,
249    total_difficulty: &mut U256,
250    progress: &mut ExportProgress,
251) -> Result<Chunk<P>>
252where
253    P: BlockReader,
254    P::Header: BlockHeader + Sealable,
255{
256    let start_block = *range.start();
257    let headers = provider.headers_range(range)?;
258    let mut blocks = Vec::with_capacity(headers.len());
259
260    for (i, header) in headers.into_iter().enumerate() {
261        let expected = start_block + i as u64;
262        let actual = header.number();
263        if expected != actual {
264            return Err(eyre!("Expected block {expected}, got {actual}"));
265        }
266
267        // `CompressedBody` holds rlp(body), not rlp(block), so take the body off the full block.
268        let body = provider
269            .block_by_number(actual)?
270            .ok_or_else(|| eyre!("Block not found for block {actual}"))?
271            .into_body();
272        let receipts = provider
273            .receipts_by_block(actual.into())?
274            .ok_or_else(|| eyre!("Receipts not found for block {actual}"))?;
275
276        // Stored status receipts cannot reproduce pre-Byzantium post-state receipts.
277        verify_receipts(&header, &receipts, true)?;
278
279        let block_hash = header.hash_slow();
280        *total_difficulty += header.difficulty();
281
282        blocks.push(ExportBlock {
283            header,
284            block_hash,
285            body,
286            receipts,
287            total_difficulty: *total_difficulty,
288        });
289        progress.record(actual, last_block);
290    }
291
292    Ok(blocks)
293}
294
295/// Caps the requested export range at the last known canonical header.
296fn determine_export_range(
297    provider: &impl BlockNumReader,
298    config: &ExportConfig,
299) -> Result<BlockNumber> {
300    let best_block_number = provider.best_block_number()?;
301
302    if best_block_number >= config.last_block_number {
303        return Ok(config.last_block_number);
304    }
305
306    match provider.last_block_number() {
307        Ok(last_header) => Ok(last_header.clamp(best_block_number, config.last_block_number)),
308        Err(err) => {
309            warn!(%err, best_block_number, "Failed to read canonical header tip, using best block number");
310            Ok(best_block_number)
311        }
312    }
313}
314
315/// Throttled progress reporter for a running export.
316struct ExportProgress {
317    start: Instant,
318    last_report: Instant,
319    interval: Duration,
320    total_blocks: u64,
321    processed: u64,
322}
323
324impl ExportProgress {
325    fn new(total_blocks: u64) -> Self {
326        let now = Instant::now();
327        Self {
328            start: now,
329            last_report: now,
330            interval: Duration::from_secs(REPORT_INTERVAL_SECS),
331            total_blocks,
332            processed: 0,
333        }
334    }
335
336    /// Counts one processed block and logs progress at most once per [`REPORT_INTERVAL_SECS`].
337    fn record(&mut self, current_block: BlockNumber, last_block: BlockNumber) {
338        self.processed += 1;
339        if self.last_report.elapsed() >= self.interval {
340            info!(
341                target: "era::history::export",
342                "Export progress: block {current_block}/{last_block} ({:.2}%) - elapsed: {:?}",
343                self.processed as f64 / self.total_blocks as f64 * 100.0,
344                self.start.elapsed()
345            );
346            self.last_report = Instant::now();
347        }
348    }
349
350    fn elapsed(&self) -> Duration {
351        self.start.elapsed()
352    }
353}
354
355#[cfg(test)]
356mod tests {
357    use super::*;
358    use alloy_consensus::Header;
359    use reth_primitives_traits::SealedHeader;
360    use reth_provider::{
361        test_utils::{create_test_provider_factory, insert_headers},
362        StageCheckpointWriter,
363    };
364    use reth_stages_types::{StageCheckpoint, StageId};
365    use tempfile::tempdir;
366
367    #[test]
368    fn test_export_config_validation() {
369        let temp_dir = tempdir().unwrap();
370
371        // Default config should pass
372        let default_config = ExportConfig::default();
373        assert!(default_config.validate().is_ok(), "Default config should be valid");
374
375        // Exactly at the limit should pass
376        let limit_config =
377            ExportConfig { max_blocks_per_file: MAX_BLOCKS_PER_ERA1 as u64, ..Default::default() };
378        assert!(limit_config.validate().is_ok(), "Config at ERA1 limit should pass validation");
379
380        // Valid config should pass
381        let valid_config = ExportConfig {
382            dir: temp_dir.path().to_path_buf(),
383            max_blocks_per_file: 1000,
384            ..Default::default()
385        };
386        assert!(valid_config.validate().is_ok(), "Valid config should pass validation");
387
388        // Zero blocks per file should fail
389        let zero_blocks_config = ExportConfig {
390            max_blocks_per_file: 0, // Invalid
391            ..Default::default()
392        };
393        let result = zero_blocks_config.validate();
394        assert!(result.is_err(), "Zero blocks per file should fail validation");
395        assert!(result.unwrap_err().to_string().contains("cannot be zero"));
396
397        // Exceeding era1 limit should fail
398        let oversized_config = ExportConfig {
399            max_blocks_per_file: MAX_BLOCKS_PER_ERA1 as u64 + 1, // Invalid
400            ..Default::default()
401        };
402        let result = oversized_config.validate();
403        assert!(result.is_err(), "Oversized blocks per file should fail validation");
404        assert!(result.unwrap_err().to_string().contains("exceeds ERA1 limit"));
405    }
406
407    #[test]
408    fn export_range_uses_the_canonical_header_tip() {
409        let factory = create_test_provider_factory();
410        let mut parent_hash = B256::ZERO;
411        let headers = [0, 1, 2].map(|number| {
412            let header =
413                SealedHeader::seal_slow(Header { number, parent_hash, ..Default::default() });
414            parent_hash = header.hash();
415            header
416        });
417        insert_headers(&factory, &headers);
418        let provider = factory.provider_rw().unwrap().0;
419
420        for (finish, requested, expected) in
421            [(0, 1, 1), (0, 2, 2), (0, 3, 2), (0, u64::MAX, 2), (3, 4, 3), (3, 1, 1)]
422        {
423            provider.save_stage_checkpoint(StageId::Finish, StageCheckpoint::new(finish)).unwrap();
424            let config = ExportConfig { last_block_number: requested, ..Default::default() };
425            assert_eq!(determine_export_range(&provider, &config).unwrap(), expected);
426        }
427    }
428}