Skip to main content

reth_era_utils/
history.rs

1use alloy_consensus::{
2    proofs::calculate_receipt_root, BlockHeader, ReceiptEnvelope, ReceiptWithBloom,
3    RlpDecodableReceipt, TxReceipt,
4};
5use alloy_primitives::{BlockHash, BlockNumber, Bloom, U256};
6use alloy_rlp::Decodable;
7use futures_util::{FutureExt, Stream, StreamExt};
8use reth_codecs::Compact;
9use reth_db_api::{
10    cursor::{DbCursorRO, DbCursorRW},
11    table::Value,
12    tables,
13    transaction::{DbTx, DbTxMut},
14    RawKey, RawTable, RawValue,
15};
16use reth_era::{
17    common::{decode::DecodeCompressedRlp, file_ops::StreamReader},
18    e2s::error::E2sError,
19    era::{file::EraReader, types::consensus::CompressedSignedBeaconBlock},
20    era1::{file::Era1Reader, types::execution::BlockTuple},
21    ere::{file::EreReader, types::execution::BlockTuple as EreBlockTuple},
22};
23use reth_era_downloader::EraMeta;
24use reth_etl::Collector;
25use reth_fs_util as fs;
26use reth_primitives_traits::{
27    Block, BlockBody, FullBlockBody, FullBlockHeader, NodePrimitives, Receipt,
28};
29use reth_provider::{
30    providers::StaticFileProviderRWRefMut, BlockReader, BlockWriter, EitherWriter,
31    EitherWriterDestination, StaticFileProviderFactory, StaticFileSegment, StaticFileWriter,
32};
33use reth_stages_types::{
34    CheckpointBlockRange, EntitiesCheckpoint, HeadersCheckpoint, StageCheckpoint, StageId,
35};
36use reth_storage_api::{
37    errors::{ProviderError, ProviderResult},
38    BlockBodyIndicesProvider, BlockHashReader, DBProvider, DatabaseProviderFactory,
39    NodePrimitivesProvider, StageCheckpointReader, StageCheckpointWriter, StorageSettingsCache,
40};
41use std::{collections::Bound, error::Error, ops::RangeBounds, sync::mpsc};
42use tracing::info;
43
44/// A decoded ERA block: header, body, and optionally its receipts.
45type EraBlock<BH, BB, R> = (BH, BB, Option<Vec<R>>);
46
47/// The receipt type of the node primitives behind provider `P`.
48type ReceiptOf<P> = <<P as NodePrimitivesProvider>::Primitives as NodePrimitives>::Receipt;
49
50/// Reads execution `(header, body, receipts)` tuples out of an ERA file.
51///
52/// `receipts` is `None` when `decode_receipts` is `false`, or the file has none (`.era` never
53/// does; `.ere` receipts are optional). `decode_receipts = false` skips decoding entirely.
54///
55/// Per-format seam of the import pipeline.
56pub trait EraBlockReader<BH, BB, R> {
57    /// Opens the ERA file at `meta` and iterates its execution blocks.
58    fn blocks<M: EraMeta + ?Sized>(
59        meta: &M,
60        decode_receipts: bool,
61    ) -> eyre::Result<impl Iterator<Item = eyre::Result<EraBlock<BH, BB, R>>>>;
62}
63
64/// [`EraBlockReader`] for `.era1` files.
65#[derive(Debug)]
66pub struct Era1;
67
68impl<BH, BB, R> EraBlockReader<BH, BB, R> for Era1
69where
70    BH: FullBlockHeader + Value,
71    BB: FullBlockBody<OmmerHeader = BH>,
72    R: RlpDecodableReceipt,
73{
74    fn blocks<M: EraMeta + ?Sized>(
75        meta: &M,
76        decode_receipts: bool,
77    ) -> eyre::Result<impl Iterator<Item = eyre::Result<EraBlock<BH, BB, R>>>> {
78        let reader: Era1Reader<std::fs::File> = open(meta)?;
79        Ok(reader
80            .iter()
81            .map(move |block| decode_with_receipts::<BH, BB, R, E2sError>(block, decode_receipts)))
82    }
83}
84
85impl<BH, BB, R> EraBlockReader<BH, BB, R> for Ere
86where
87    BH: FullBlockHeader + Value,
88    BB: FullBlockBody<OmmerHeader = BH>,
89    R: RlpDecodableReceipt,
90{
91    fn blocks<M: EraMeta + ?Sized>(
92        meta: &M,
93        decode_receipts: bool,
94    ) -> eyre::Result<impl Iterator<Item = eyre::Result<EraBlock<BH, BB, R>>>> {
95        let reader: EreReader<std::fs::File> = open(meta)?;
96        Ok(reader.iter().map(move |block| Self::decode_with_receipts(block, decode_receipts)))
97    }
98}
99
100/// [`EraBlockReader`] for `.ere`/`.erae` files.
101#[derive(Debug)]
102pub struct Ere;
103
104impl Ere {
105    /// Extracts a `(header, body)` pair from an ERE block tuple, whose header and body are
106    /// RLP-compressed. Ignores any receipts entry; callers that need receipts should use
107    /// [`decode_with_receipts`](Self::decode_with_receipts).
108    pub fn decode<BH, BB, E>(block: Result<EreBlockTuple, E>) -> eyre::Result<(BH, BB)>
109    where
110        BH: FullBlockHeader + Value,
111        BB: FullBlockBody<OmmerHeader = BH>,
112        E: From<E2sError> + Error + Send + Sync + 'static,
113    {
114        let block = block?;
115        let header: BH = block.header.decode()?;
116        let body: BB = block.body.decode()?;
117        Ok((header, body))
118    }
119
120    /// Like [`decode`](Self::decode), but also extracts receipts when `decode_receipts` is `true`.
121    /// `receipts` is `None` if `decode_receipts` is `false`, or if the block tuple carries no
122    /// receipts entry (`.ere` receipts are optional per spec).
123    pub fn decode_with_receipts<BH, BB, R, E>(
124        block: Result<EreBlockTuple, E>,
125        decode_receipts: bool,
126    ) -> eyre::Result<EraBlock<BH, BB, R>>
127    where
128        BH: FullBlockHeader + Value,
129        BB: FullBlockBody<OmmerHeader = BH>,
130        R: RlpDecodableReceipt,
131        E: From<E2sError> + Error + Send + Sync + 'static,
132    {
133        let block = block?;
134        let header: BH = block.header.decode()?;
135        let body: BB = block.body.decode()?;
136        let number = header.number();
137        let receipts = decode_receipts
138            .then(|| block.receipts.as_ref().map(|r| r.decode_receipts()))
139            .flatten()
140            .transpose()?
141            .map(|slim| receipts_from_envelopes(number, slim.into_iter().map(Into::into).collect()))
142            .transpose()?;
143
144        Ok((header, body, receipts))
145    }
146}
147
148/// [`EraBlockReader`] for consensus-layer `.era` files.
149///
150/// `.era` files store consensus `SignedBeaconBlock`s. Post-merge
151/// blocks embed an execution payload; this source SSZ-decodes each beacon block, extracts that
152/// payload, and converts it into an execution `(header, body)` pair. Pre-merge slots carry no
153/// payload and are skipped. `.era` files carry no receipt data at all, so this source always
154/// yields `None` for receipts.
155#[derive(Debug)]
156pub struct Era;
157
158impl<BH, BB, R> EraBlockReader<BH, BB, R> for Era
159where
160    BH: FullBlockHeader,
161    BB: FullBlockBody,
162{
163    /// `.era` files carry no receipt data, so `decode_receipts` has no effect.
164    fn blocks<M: EraMeta + ?Sized>(
165        meta: &M,
166        _decode_receipts: bool,
167    ) -> eyre::Result<impl Iterator<Item = eyre::Result<EraBlock<BH, BB, R>>>> {
168        let reader: EraReader<std::fs::File> = open(meta)?;
169        let mut buf = Vec::new();
170        Ok(reader.iter().filter_map(move |block| {
171            Self::decode(block, &mut buf)
172                .map(|opt| opt.map(|(header, body)| (header, body, None)))
173                .transpose()
174        }))
175    }
176}
177
178impl Era {
179    /// Decodes the execution `(header, body)` embedded in a consensus `SignedBeaconBlock`.
180    ///
181    /// Returns `Ok(None)` for pre-merge slots, which carry no execution payload.
182    pub fn decode<BH, BB>(
183        block: Result<CompressedSignedBeaconBlock, E2sError>,
184        buf: &mut Vec<u8>,
185    ) -> eyre::Result<Option<(BH, BB)>>
186    where
187        BH: FullBlockHeader,
188        BB: FullBlockBody,
189    {
190        let Some(alloy_consensus::Block { header, body }) =
191            block?.decode_execution_block::<<BB as BlockBody>::Transaction>()?
192        else {
193            return Ok(None);
194        };
195        // The beacon payload decodes into alloy execution types; re-encode and decode into the
196        // node's own primitives through the same RLP representation the `.era1`/`.ere` paths use.
197        Ok(Some((reencode_rlp(&header, buf)?, reencode_rlp(&body, buf)?)))
198    }
199}
200
201/// Re-encodes an alloy execution type as RLP and decodes it back into the node's primitive type.
202///
203/// `.era` files yield alloy execution headers/bodies, while the import pipeline writes the node's
204/// own primitives. Both share the canonical execution RLP encoding, so a round-trip bridges them
205/// without requiring a direct `From` conversion.
206fn reencode_rlp<T, U>(value: &T, buf: &mut Vec<u8>) -> eyre::Result<U>
207where
208    T: alloy_rlp::Encodable,
209    U: alloy_rlp::Decodable,
210{
211    buf.clear();
212    alloy_rlp::Encodable::encode(value, buf);
213    Ok(<U as alloy_rlp::Decodable>::decode(&mut buf.as_slice())?)
214}
215
216/// Opens the ERA file at `meta` with the format's [`StreamReader`].
217pub fn open<Reader>(meta: &(impl EraMeta + ?Sized)) -> eyre::Result<Reader>
218where
219    Reader: StreamReader<std::fs::File>,
220{
221    Ok(Reader::new(fs::open(meta.path())?))
222}
223
224/// Imports blocks from `downloader`, decoding each file with the [`EraBlockReader`] `S`.
225///
226/// When `to_block` is set, the import stops after reaching that block height; otherwise it
227/// continues until the source has no more files.
228///
229/// `store_receipts` backfills the `Receipts` segment from its tip up to the `Execution`
230/// checkpoint, which it must reach exactly: receipts above the checkpoint are pruned on the next
231/// node start, and receipts below it leave the node unable to start. Only a missing tail is
232/// detected, never a gap inside the existing segment.
233///
234/// `is_receipt_verifiable` decides which blocks have their receipts checked against the header,
235/// as pre-Byzantium receipts can't be recomputed here.
236///
237/// Returns current block height.
238pub fn import<S, Downloader, Era, PF, B, BB, BH>(
239    mut downloader: Downloader,
240    provider_factory: &PF,
241    hash_collector: &mut Collector<BlockHash, BlockNumber>,
242    to_block: Option<BlockNumber>,
243    store_receipts: bool,
244    is_receipt_verifiable: &dyn Fn(BlockNumber) -> bool,
245) -> eyre::Result<BlockNumber>
246where
247    S: EraBlockReader<BH, BB, ReceiptOf<<PF as DatabaseProviderFactory>::ProviderRW>>,
248    B: Block<Header = BH, Body = BB>,
249    BH: FullBlockHeader + Value,
250    BB: FullBlockBody<
251        Transaction = <<<PF as DatabaseProviderFactory>::ProviderRW as NodePrimitivesProvider>::Primitives as NodePrimitives>::SignedTx,
252        OmmerHeader = BH,
253    >,
254    Downloader: Stream<Item = eyre::Result<Era>> + Send + 'static + Unpin,
255    Era: EraMeta + Send + 'static,
256    PF: DatabaseProviderFactory<
257        ProviderRW: BlockWriter<Block = B>
258            + DBProvider
259            + BlockBodyIndicesProvider
260            + BlockHashReader
261            + StaticFileProviderFactory<Primitives: NodePrimitives<Block = B, BlockHeader = BH, BlockBody = BB>>
262            + StageCheckpointReader
263            + StageCheckpointWriter
264            + StorageSettingsCache,
265    > + StaticFileProviderFactory<Primitives = <<PF as DatabaseProviderFactory>::ProviderRW as NodePrimitivesProvider>::Primitives>,
266    ReceiptOf<<PF as DatabaseProviderFactory>::ProviderRW>: Compact + Receipt,
267{
268    let (tx, rx) = mpsc::channel();
269
270    // Handle IO-bound async download in a background tokio task
271    tokio::spawn(
272        async move {
273            while let Some(file) = downloader.next().await {
274                if tx.send(Some(file)).is_err() {
275                    return;
276                }
277            }
278            // A closed channel means the import stopped early.
279            tx.send(None).ok();
280        }
281        .boxed(),
282    );
283
284    let static_file_provider = provider_factory.static_file_provider();
285
286    // The chain's first block, which is not necessarily 0: reth supports a non-zero genesis.
287    let genesis_block_number = static_file_provider.genesis_block_number();
288
289    // Consistency check of expected headers in static files vs DB is done on provider::sync_gap
290    // when poll_execute_ready is polled.
291    let headers_tip = static_file_provider
292        .get_highest_static_file_block(StaticFileSegment::Headers)
293        .unwrap_or(genesis_block_number);
294
295    // When backfilling receipts, resume from the receipts tip so blocks whose headers were already
296    // imported still get their receipts; only blocks above `headers_tip` are written in full.
297    let receipts_tip = store_receipts
298        .then(|| static_file_provider.get_highest_static_file_block(StaticFileSegment::Receipts));
299    let mut height = match receipts_tip {
300        Some(tip) => headers_tip.min(tip.unwrap_or(genesis_block_number)),
301        None => headers_tip,
302    };
303
304    // Only the executed range can hold receipts durably, so the repair has to land exactly on the
305    // Execution checkpoint.
306    let receipts_target = store_receipts
307        .then(|| -> eyre::Result<_> {
308            let provider = provider_factory.database_provider_rw()?;
309
310            // Writing the segment under a config that routes receipts to the database would leave
311            // two sources and keep data the prune config wants dropped.
312            if !matches!(
313                EitherWriter::receipts_destination(&provider),
314                EitherWriterDestination::StaticFile
315            ) {
316                eyre::bail!(
317                    "receipt import writes the Receipts static file segment, but this node's \
318                     prune configuration keeps receipts elsewhere. Remove the receipt pruning \
319                     configuration, or import without receipts"
320                );
321            }
322
323            let target = provider
324                .get_stage_checkpoint(StageId::Execution)?
325                .map(|checkpoint| checkpoint.block_number)
326                .unwrap_or(genesis_block_number);
327
328            if target <= genesis_block_number {
329                eyre::bail!(
330                    "receipt import repairs the receipt static files of an already-executed \
331                     range, but this database has executed no blocks. Sync the node first, or \
332                     import without receipts"
333                );
334            }
335            if height >= target {
336                eyre::bail!(
337                    "receipts already cover the executed range up to block {target}, nothing to \
338                     repair"
339                );
340            }
341            if let Some(to_block) = to_block &&
342                to_block != target
343            {
344                eyre::bail!(
345                    "--to-block {to_block} does not match the Execution checkpoint {target}. A \
346                     receipt repair must cover the executed range exactly, so either drop \
347                     --to-block or set it to {target}"
348                );
349            }
350            // Such a repair can never complete, so fail before committing the empty blocks that
351            // precede the first pre-Byzantium receipt.
352            if !is_receipt_verifiable(height + 1) {
353                eyre::bail!(
354                    "receipt repair would start at block {}, which predates Byzantium. Those \
355                     receipts commit to a post-state root this node's receipt type cannot \
356                     represent, so the Receipts segment has to already cover the pre-Byzantium \
357                     range",
358                    height + 1,
359                );
360            }
361
362            Ok(target)
363        })
364        .transpose()?;
365
366    // A segment that doesn't exist yet holds no receipts for genesis, which has none of its own.
367    // The backfill resumes at the block after it, so seed that entry the way `init_genesis` does,
368    // or the writer rejects the first append. Setting the range directly rather than incrementing
369    // also covers a genesis that doesn't sit on a static file boundary.
370    if matches!(receipts_tip, Some(None)) {
371        let mut writer = static_file_provider.latest_writer(StaticFileSegment::Receipts)?;
372        writer.user_header_mut().set_block_range(genesis_block_number, genesis_block_number);
373        writer.commit()?;
374    }
375
376    let to_block = receipts_target.or(to_block);
377    let end = to_block.map_or(Bound::Unbounded, Bound::Included);
378    let policy = ImportPolicy { headers_tip, is_receipt_verifiable };
379
380    while let Some(meta) = rx.recv()? {
381        let meta = meta?;
382        let from = height;
383        let provider = provider_factory.database_provider_rw()?;
384
385        // Headers and receipts are separate static file segments, each with its own writer, only
386        // open the receipts one when `--with-receipts` was requested.
387        let mut receipts_writer = store_receipts
388            .then(|| static_file_provider.latest_writer(StaticFileSegment::Receipts))
389            .transpose()?;
390
391        height = process::<S, _, _, _, _>(
392            &meta,
393            &mut static_file_provider.latest_writer(StaticFileSegment::Headers)?,
394            receipts_writer.as_mut(),
395            &provider,
396            hash_collector,
397            (Bound::Included(height), end),
398            policy,
399        )?;
400
401        // Drop the receipts writer's lock before `provider.commit()`, which locks every static
402        // file segment (including receipts) via `has_unwind_queued`.
403        drop(receipts_writer);
404
405        // A receipts-only backfill trails `headers_tip`; the checkpoints must not regress below
406        // the headers already in static files.
407        let checkpoint = height.max(headers_tip);
408        save_stage_checkpoints(&provider, from, checkpoint, checkpoint, checkpoint)?;
409
410        provider.commit()?;
411
412        info!(target: "era::history::import", first = from, last = height, file = %meta.path().display(), "Imported ERA file");
413
414        if to_block.is_some_and(|to| height >= to) {
415            break;
416        }
417    }
418
419    let provider = provider_factory.database_provider_rw()?;
420
421    build_index(&provider, hash_collector)?;
422
423    provider.commit()?;
424
425    // A repair that stops short leaves the receipts behind the executed range, which the Execution
426    // stage reports as missing static file data on the next node start.
427    if let Some(target) = receipts_target &&
428        height < target
429    {
430        eyre::bail!(
431            "receipt repair reached block {height} but the executed range ends at {target}. The \
432             source ran out of files, re-run with the files covering blocks {}..={target}",
433            height + 1,
434        );
435    }
436
437    Ok(height)
438}
439
440/// Saves progress of ERA import into stages sync.
441///
442/// Never marks `Execution` done: this import writes no state, so moving that checkpoint would let
443/// a node start from blocks whose accounts and storage were never written.
444pub fn save_stage_checkpoints<P>(
445    provider: P,
446    from: BlockNumber,
447    to: BlockNumber,
448    processed: u64,
449    total: u64,
450) -> ProviderResult<()>
451where
452    P: StageCheckpointWriter,
453{
454    provider.save_stage_checkpoint(
455        StageId::Headers,
456        StageCheckpoint::new(to).with_headers_stage_checkpoint(HeadersCheckpoint {
457            block_range: CheckpointBlockRange { from, to },
458            progress: EntitiesCheckpoint { processed, total },
459        }),
460    )?;
461    provider.save_stage_checkpoint(
462        StageId::Bodies,
463        StageCheckpoint::new(to)
464            .with_entities_stage_checkpoint(EntitiesCheckpoint { processed, total }),
465    )?;
466    Ok(())
467}
468
469/// Reads `meta` with the [`EraBlockReader`] `S`, appends its blocks within `block_numbers`, and
470/// marks `meta` processed if the file was fully consumed. Returns last block height.
471pub fn process<S, P, B, BB, BH>(
472    meta: &(impl EraMeta + ?Sized),
473    writer: &mut StaticFileProviderRWRefMut<'_, <P as NodePrimitivesProvider>::Primitives>,
474    receipts_writer: Option<
475        &mut StaticFileProviderRWRefMut<'_, <P as NodePrimitivesProvider>::Primitives>,
476    >,
477    provider: &P,
478    hash_collector: &mut Collector<BlockHash, BlockNumber>,
479    block_numbers: impl RangeBounds<BlockNumber>,
480    policy: ImportPolicy<'_>,
481) -> eyre::Result<BlockNumber>
482where
483    S: EraBlockReader<BH, BB, ReceiptOf<P>>,
484    B: Block<Header = BH, Body = BB>,
485    BH: FullBlockHeader + Value,
486    BB: FullBlockBody<
487        Transaction = <<P as NodePrimitivesProvider>::Primitives as NodePrimitives>::SignedTx,
488        OmmerHeader = BH,
489    >,
490    P: DBProvider<Tx: DbTxMut>
491        + NodePrimitivesProvider
492        + BlockWriter<Block = B>
493        + BlockBodyIndicesProvider
494        + BlockHashReader,
495    <P as NodePrimitivesProvider>::Primitives: NodePrimitives<BlockHeader = BH, BlockBody = BB>,
496    ReceiptOf<P>: Compact + Receipt,
497{
498    let decode_receipts = receipts_writer.is_some();
499    let iter = S::blocks(meta, decode_receipts)?
500        .map(Some)
501        .chain(std::iter::once_with(|| match meta.mark_as_processed() {
502            Ok(()) => None,
503            Err(error) => Some(Err(error)),
504        }))
505        .flatten();
506
507    process_iter(iter, writer, receipts_writer, provider, hash_collector, block_numbers, policy)
508}
509
510/// Per-block import policy for [`process`] and [`process_iter`].
511#[derive(Clone, Copy)]
512pub struct ImportPolicy<'a> {
513    /// Blocks at or below this are backfilled receipts-only; blocks above it are written in full.
514    pub headers_tip: BlockNumber,
515    /// Whether a block's receipts are verified against its header commitments.
516    pub is_receipt_verifiable: &'a dyn Fn(BlockNumber) -> bool,
517}
518
519impl std::fmt::Debug for ImportPolicy<'_> {
520    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
521        // `is_receipt_verifiable` is a `dyn Fn` and can't be formatted.
522        f.debug_struct("ImportPolicy")
523            .field("headers_tip", &self.headers_tip)
524            .finish_non_exhaustive()
525    }
526}
527
528/// Extracts a `(header, body)` pair from [`BlockTuple`].
529pub fn decode<BH, BB, E>(block: Result<BlockTuple, E>) -> eyre::Result<(BH, BB)>
530where
531    BH: FullBlockHeader + Value,
532    BB: FullBlockBody<OmmerHeader = BH>,
533    E: From<E2sError> + Error + Send + Sync + 'static,
534{
535    let block = block?;
536    let header: BH = block.header.decode()?;
537    let body: BB = block.body.decode()?;
538    Ok((header, body))
539}
540
541/// Like [`decode`], but also extracts receipts when `decode_receipts` is `true`. `receipts` is
542/// `Some` whenever `decode_receipts` is `true`: `era1`'s `CompressedReceipts` entry is mandatory
543/// per spec, so (unlike `.ere`) it is never `None` just because the file omits it.
544pub fn decode_with_receipts<BH, BB, R, E>(
545    block: Result<BlockTuple, E>,
546    decode_receipts: bool,
547) -> eyre::Result<EraBlock<BH, BB, R>>
548where
549    BH: FullBlockHeader + Value,
550    BB: FullBlockBody<OmmerHeader = BH>,
551    R: RlpDecodableReceipt,
552    E: From<E2sError> + Error + Send + Sync + 'static,
553{
554    let block = block?;
555    let header: BH = block.header.decode()?;
556    let body: BB = block.body.decode()?;
557    let number = header.number();
558    let receipts = decode_receipts
559        .then(|| -> eyre::Result<_> {
560            match block.receipts.decode::<Vec<ReceiptWithBloom<R>>>() {
561                Ok(receipts) => {
562                    Ok(receipts.into_iter().map(|with_bloom| with_bloom.receipt).collect())
563                }
564                // A status field holding a post-state root doesn't fit the node's receipt type, so
565                // re-read the entry to tell that apart from a genuinely malformed one.
566                Err(err) => match block.receipts.decode::<Vec<ReceiptEnvelope>>() {
567                    Ok(envelopes) => receipts_from_envelopes(number, envelopes),
568                    Err(_) => Err(err.into()),
569                },
570            }
571        })
572        .transpose()?;
573
574    Ok((header, body, receipts))
575}
576
577/// Converts decoded ERA receipts into the node's receipt type.
578///
579/// Rebuilds them through their canonical encoding, the only construction path every node receipt
580/// type supports. Receipts predating Byzantium are rejected: they commit to a post-state root
581/// rather than a success status, and nothing else in the file records whether the transaction
582/// succeeded, so no node receipt type can represent them.
583fn receipts_from_envelopes<R: RlpDecodableReceipt>(
584    number: BlockNumber,
585    envelopes: Vec<ReceiptEnvelope>,
586) -> eyre::Result<Vec<R>> {
587    for envelope in &envelopes {
588        if envelope.status_or_post_state().is_post_state() {
589            eyre::bail!(
590                "block {number} has pre-Byzantium receipts, which commit to a post-state root \
591                 rather than a success status and so cannot be represented by this node's receipt \
592                 type. Receipt import is only supported from Byzantium onwards"
593            );
594        }
595    }
596
597    let encoded = alloy_rlp::encode(&envelopes);
598
599    Ok(Vec::<ReceiptWithBloom<R>>::decode(&mut encoded.as_slice())?
600        .into_iter()
601        .map(|with_bloom| with_bloom.receipt)
602        .collect())
603}
604
605/// Extracts block headers, bodies and (optionally) receipts from `iter` and appends them using
606/// `writer`, `receipts_writer` and `provider`.
607///
608/// Collects hash to height using `hash_collector`.
609///
610/// Skips all blocks below the [`start_bound`] of `block_numbers` and stops when reaching past the
611/// [`end_bound`] or the end of the file.
612///
613/// Blocks at or below `headers_tip` only have their receipts backfilled; blocks above it get
614/// header, body and receipts written.
615///
616/// When `receipts_writer` is `Some`, every block must carry receipts, a block without them,
617/// possible for `.ere` files, whose receipts are optional per spec is an error. Receipts are
618/// checked against the header's logs bloom, and against its receipts root when
619/// `is_receipt_verifiable` returns `true`.
620///
621/// Returns last block height.
622///
623/// [`start_bound`]: RangeBounds::start_bound
624/// [`end_bound`]: RangeBounds::end_bound
625pub fn process_iter<P, B, BB, BH>(
626    mut iter: impl Iterator<Item = eyre::Result<EraBlock<BH, BB, ReceiptOf<P>>>>,
627    writer: &mut StaticFileProviderRWRefMut<'_, <P as NodePrimitivesProvider>::Primitives>,
628    mut receipts_writer: Option<
629        &mut StaticFileProviderRWRefMut<'_, <P as NodePrimitivesProvider>::Primitives>,
630    >,
631    provider: &P,
632    hash_collector: &mut Collector<BlockHash, BlockNumber>,
633    block_numbers: impl RangeBounds<BlockNumber>,
634    policy: ImportPolicy<'_>,
635) -> eyre::Result<BlockNumber>
636where
637    B: Block<Header = BH, Body = BB>,
638    BH: FullBlockHeader + Value,
639    BB: FullBlockBody<
640        Transaction = <<P as NodePrimitivesProvider>::Primitives as NodePrimitives>::SignedTx,
641        OmmerHeader = BH,
642    >,
643    P: DBProvider<Tx: DbTxMut>
644        + NodePrimitivesProvider
645        + BlockWriter<Block = B>
646        + BlockBodyIndicesProvider
647        + BlockHashReader,
648    <P as NodePrimitivesProvider>::Primitives: NodePrimitives<BlockHeader = BH, BlockBody = BB>,
649    ReceiptOf<P>: Compact + Receipt,
650{
651    let mut last_header_number = match block_numbers.start_bound() {
652        Bound::Included(&number) => number,
653        Bound::Excluded(&number) => number.saturating_add(1),
654        Bound::Unbounded => 0,
655    };
656    let target = match block_numbers.end_bound() {
657        Bound::Included(&number) => Some(number),
658        Bound::Excluded(&number) => Some(number.saturating_sub(1)),
659        Bound::Unbounded => None,
660    };
661
662    for block in &mut iter {
663        let (header, body, receipts) = block?;
664        let number = header.number();
665
666        if number <= last_header_number {
667            continue;
668        }
669        if let Some(target) = target &&
670            number > target
671        {
672            break;
673        }
674
675        // Reject gaps: the import marks the Headers/Bodies stages complete up to `height`, so a
676        // non-contiguous append would leave earlier blocks missing while the stages report done.
677        if number != last_header_number + 1 {
678            eyre::bail!(
679                "non-contiguous ERA import: expected block {}, got {number}; the execution \
680                 database must be synced up to block {} before importing this file",
681                last_header_number + 1,
682                number - 1,
683            );
684        }
685
686        last_header_number = number;
687
688        // Header and body are only written for new blocks, when backfilling receipts onto an
689        // earlier import the block already has both persisted.
690        if number > policy.headers_tip {
691            let hash = header.hash_slow();
692            writer.append_header(&header, &hash)?;
693            provider.append_block_bodies(vec![(header.number(), Some(&body))])?;
694            hash_collector.insert(hash, number)?;
695        } else if provider.block_hash(number)? != Some(header.hash_slow()) {
696            // Receipts are verified against the source header, so it must be the block already
697            // persisted at this height, not merely a self-consistent one.
698            eyre::bail!(
699                "block {number} in this ERA file does not match the block already imported at \
700                 that height"
701            );
702        }
703
704        if let Some(receipts_writer) = receipts_writer.as_deref_mut() {
705            if let Some(receipts) = receipts.as_deref() {
706                verify_receipts(&header, receipts, (policy.is_receipt_verifiable)(number))?;
707            }
708            provider.write_block_receipts(receipts_writer, number, receipts)?;
709        }
710    }
711
712    Ok(last_header_number)
713}
714
715/// Checks a block's receipts against its header.
716///
717/// The bloom is always checked. Set `check_root` to also verify the receipt encodings against
718/// the header. Before Byzantium, this requires the original post-state roots.
719pub(super) fn verify_receipts<BH, R>(
720    header: &BH,
721    receipts: &[R],
722    check_root: bool,
723) -> eyre::Result<()>
724where
725    BH: BlockHeader,
726    R: Receipt,
727{
728    let with_bloom = receipts.iter().map(TxReceipt::with_bloom_ref).collect::<Vec<_>>();
729    let logs_bloom = with_bloom.iter().fold(Bloom::ZERO, |bloom, r| bloom | r.bloom_ref());
730
731    if logs_bloom != header.logs_bloom() {
732        eyre::bail!("logs bloom mismatch for block {}", header.number());
733    }
734
735    if check_root {
736        let receipts_root = calculate_receipt_root(&with_bloom);
737        if receipts_root != header.receipts_root() {
738            eyre::bail!(
739                "receipts root mismatch for block {}: computed {receipts_root}, header has {}",
740                header.number(),
741                header.receipts_root(),
742            );
743        }
744    }
745
746    Ok(())
747}
748
749/// Lets a provider append one block's receipts to a `Receipts` static file writer, using itself
750/// to look up the block's transaction range.
751trait BlockReceiptsWriterExt: BlockBodyIndicesProvider {
752    /// Appends `receipts` for block `number` to `receipts_writer`.
753    ///
754    /// Errors if the block has no receipts, or if the receipt count doesn't match the block's
755    /// transaction count.
756    fn write_block_receipts<N: NodePrimitives>(
757        &self,
758        receipts_writer: &mut StaticFileProviderRWRefMut<'_, N>,
759        number: BlockNumber,
760        receipts: Option<Vec<N::Receipt>>,
761    ) -> eyre::Result<()>
762    where
763        N::Receipt: Compact;
764}
765
766impl<P: BlockBodyIndicesProvider> BlockReceiptsWriterExt for P {
767    fn write_block_receipts<N: NodePrimitives>(
768        &self,
769        receipts_writer: &mut StaticFileProviderRWRefMut<'_, N>,
770        number: BlockNumber,
771        receipts: Option<Vec<N::Receipt>>,
772    ) -> eyre::Result<()>
773    where
774        N::Receipt: Compact,
775    {
776        let Some(block_receipts) = receipts else {
777            eyre::bail!(
778                "block {number} has no receipts in the imported ERA file; drop --with-receipts, \
779                 or import files that carry receipts for every block (`.era1` always includes \
780                 them; `.ere` receipts are optional per spec)"
781            );
782        };
783
784        let indices = self
785            .block_body_indices(number)?
786            .ok_or_else(|| eyre::eyre!("missing block body indices for block {number}"))?;
787
788        if block_receipts.len() as u64 != indices.tx_count {
789            eyre::bail!(
790                "receipt count mismatch for block {number}: {} receipt(s) for {} transaction(s)",
791                block_receipts.len(),
792                indices.tx_count,
793            );
794        }
795
796        receipts_writer.increment_block(number)?;
797        receipts_writer.append_receipts(
798            (indices.first_tx_num..).zip(block_receipts.iter()).map(Ok::<_, ProviderError>),
799        )?;
800
801        Ok(())
802    }
803}
804
805/// Dumps the contents of `hash_collector` into [`tables::HeaderNumbers`].
806pub fn build_index<P>(
807    provider: &P,
808    hash_collector: &mut Collector<BlockHash, BlockNumber>,
809) -> eyre::Result<()>
810where
811    P: DBProvider<Tx: DbTxMut>,
812{
813    let total_headers = hash_collector.len();
814    info!(target: "era::history::import", total = total_headers, "Writing headers hash index");
815
816    // Database cursor for hash to number index
817    let mut cursor_header_numbers =
818        provider.tx_ref().cursor_write::<RawTable<tables::HeaderNumbers>>()?;
819    // If we only have the genesis block hash, then we are at first sync, and we can remove it,
820    // add it to the collector and use tx.append on all hashes.
821    let first_sync = if provider.tx_ref().entries::<RawTable<tables::HeaderNumbers>>()? == 1 &&
822        let Some((hash, block_number)) = cursor_header_numbers.last()? &&
823        block_number.value()? == 0
824    {
825        hash_collector.insert(hash.key()?, 0)?;
826        cursor_header_numbers.delete_current()?;
827        true
828    } else {
829        false
830    };
831
832    let interval = (total_headers / 10).max(8192);
833
834    // Build block hash to block number index
835    for (index, hash_to_number) in hash_collector.iter()?.enumerate() {
836        let (hash, number) = hash_to_number?;
837
838        if index != 0 && index.is_multiple_of(interval) {
839            info!(target: "era::history::import", progress = %format_args!("{:.2}%", (index as f64 / total_headers as f64) * 100.0), "Writing headers hash index");
840        }
841
842        let hash = RawKey::<BlockHash>::from_vec(hash);
843        let number = RawValue::<BlockNumber>::from_vec(number);
844
845        if first_sync {
846            cursor_header_numbers.append(hash, &number)?;
847        } else {
848            cursor_header_numbers.upsert(hash, &number)?;
849        }
850    }
851
852    Ok(())
853}
854
855/// Calculates the total difficulty for a given block number by summing the difficulty
856/// of all blocks from genesis to the given block.
857///
858/// Very expensive - iterates through all blocks in batches of 1000.
859///
860/// Returns an error if any block is missing.
861pub fn calculate_td_by_number<P>(provider: &P, num: BlockNumber) -> eyre::Result<U256>
862where
863    P: BlockReader,
864{
865    let mut total_difficulty = U256::ZERO;
866    let mut start = 0;
867
868    while start <= num {
869        let end = (start + 1000 - 1).min(num);
870
871        total_difficulty +=
872            provider.headers_range(start..=end)?.iter().map(|h| h.difficulty()).sum::<U256>();
873
874        start = end + 1;
875    }
876
877    Ok(total_difficulty)
878}
879
880#[cfg(test)]
881mod tests {
882    use super::*;
883    use crate::{export, ExportConfig};
884    use alloy_consensus::{
885        Eip658Value, Header, Receipt as RlpReceipt, ReceiptWithBloom, TxLegacy, TxType,
886    };
887    use alloy_primitives::{Address, Bytes, Log, Signature, B256};
888    use reth_db_common::init::init_genesis;
889    use reth_era::{
890        era1::types::execution::{
891            CompressedBody, CompressedHeader, CompressedReceipts, TotalDifficulty,
892        },
893        ere::types::execution::{
894            CompressedBody as EreCompressedBody, CompressedHeader as EreCompressedHeader,
895            CompressedSlimReceipts, SlimReceipt,
896        },
897    };
898    use reth_ethereum_primitives::{Block, BlockBody, Receipt, TransactionSigned};
899    use reth_provider::{
900        test_utils::{
901            create_test_provider_factory, create_test_provider_factory_with_genesis_block_number,
902            MockEthProvider,
903        },
904        DatabaseProviderFactory, ReceiptProvider, StageCheckpointReader, StaticFileProviderFactory,
905        StaticFileSegment, StaticFileWriter,
906    };
907    use reth_prune_types::{PruneMode, PruneModes, ReceiptsLogPruneConfig};
908    use std::{cell::Cell, path::Path};
909    use tempfile::tempdir;
910
911    /// Builds an `.era1` block tuple for a transaction-less block carrying `receipts`.
912    fn era1_block_tuple(number: u64, receipts: Vec<ReceiptEnvelope>) -> BlockTuple {
913        let header = Header { number, ..Default::default() };
914        BlockTuple::new(
915            CompressedHeader::from_rlp(&alloy_rlp::encode(&header)).unwrap(),
916            CompressedBody::from_rlp(&alloy_rlp::encode(BlockBody::default())).unwrap(),
917            CompressedReceipts::from_rlp(&alloy_rlp::encode(&receipts)).unwrap(),
918            TotalDifficulty::new(U256::ZERO),
919        )
920    }
921
922    /// Builds a block with one transaction, its receipt, and a header committing to that receipt.
923    fn block_with_one_receipt(number: u64) -> (Header, BlockBody, Receipt) {
924        let tx = TransactionSigned::new_unhashed(
925            TxLegacy::default().into(),
926            Signature::test_signature(),
927        );
928        let receipt = Receipt {
929            tx_type: TxType::Legacy,
930            success: true,
931            cumulative_gas_used: 21_000,
932            logs: vec![],
933        };
934
935        let with_bloom = vec![TxReceipt::with_bloom_ref(&receipt)];
936        let header = Header {
937            number,
938            receipts_root: calculate_receipt_root(&with_bloom),
939            logs_bloom: with_bloom.iter().fold(Bloom::ZERO, |bloom, r| bloom | r.bloom_ref()),
940            ..Default::default()
941        };
942
943        (header, BlockBody { transactions: vec![tx], ..Default::default() }, receipt)
944    }
945
946    /// Wraps `status` in a legacy `.era1` receipt envelope.
947    fn era1_receipt(status: Eip658Value) -> ReceiptEnvelope {
948        ReceiptEnvelope::Legacy(ReceiptWithBloom::new(
949            RlpReceipt { status, cumulative_gas_used: 21_000, logs: vec![] },
950            Bloom::ZERO,
951        ))
952    }
953
954    /// Builds an `.ere` block tuple carrying canonical slim receipts.
955    fn ere_block_tuple(number: u64, receipts: &[SlimReceipt]) -> EreBlockTuple {
956        let header = Header { number, ..Default::default() };
957        EreBlockTuple::new(
958            EreCompressedHeader::from_rlp(&alloy_rlp::encode(&header)).unwrap(),
959            EreCompressedBody::from_rlp(&alloy_rlp::encode(BlockBody::default())).unwrap(),
960        )
961        .with_receipts(CompressedSlimReceipts::from_receipts(receipts).unwrap())
962    }
963
964    struct TestEra;
965
966    impl<R> EraBlockReader<Header, BlockBody, R> for TestEra {
967        fn blocks<M: EraMeta + ?Sized>(
968            _meta: &M,
969            _decode_receipts: bool,
970        ) -> eyre::Result<impl Iterator<Item = eyre::Result<(Header, BlockBody, Option<Vec<R>>)>>>
971        {
972            Ok([1, 2].into_iter().map(|number| {
973                Ok((Header { number, ..Default::default() }, BlockBody::default(), None))
974            }))
975        }
976    }
977
978    /// Like [`TestEra`], but yields `Some(vec![])` receipts for each (transaction-less) block.
979    struct TestEraWithEmptyReceipts;
980
981    impl<R> EraBlockReader<Header, BlockBody, R> for TestEraWithEmptyReceipts {
982        fn blocks<M: EraMeta + ?Sized>(
983            _meta: &M,
984            _decode_receipts: bool,
985        ) -> eyre::Result<impl Iterator<Item = eyre::Result<(Header, BlockBody, Option<Vec<R>>)>>>
986        {
987            Ok([1, 2].into_iter().map(|number| {
988                Ok((Header { number, ..Default::default() }, BlockBody::default(), Some(vec![])))
989            }))
990        }
991    }
992
993    /// Empty receipts for the two blocks immediately after a genesis at block 100.
994    struct TestEraWithNonZeroGenesis;
995
996    impl<R> EraBlockReader<Header, BlockBody, R> for TestEraWithNonZeroGenesis {
997        fn blocks<M: EraMeta + ?Sized>(
998            _meta: &M,
999            _decode_receipts: bool,
1000        ) -> eyre::Result<impl Iterator<Item = eyre::Result<(Header, BlockBody, Option<Vec<R>>)>>>
1001        {
1002            Ok([101, 102].into_iter().map(|number| {
1003                Ok((Header { number, ..Default::default() }, BlockBody::default(), Some(vec![])))
1004            }))
1005        }
1006    }
1007
1008    /// Like [`TestEra`], but yields a single receipt for a transaction-less block, provoking a
1009    /// receipt/transaction count mismatch.
1010    struct TestEraWithMismatchedReceipts;
1011
1012    impl EraBlockReader<Header, BlockBody, reth_ethereum_primitives::Receipt>
1013        for TestEraWithMismatchedReceipts
1014    {
1015        fn blocks<M: EraMeta + ?Sized>(
1016            _meta: &M,
1017            _decode_receipts: bool,
1018        ) -> eyre::Result<
1019            impl Iterator<
1020                Item = eyre::Result<EraBlock<Header, BlockBody, reth_ethereum_primitives::Receipt>>,
1021            >,
1022        > {
1023            Ok(std::iter::once(Ok((
1024                Header { number: 1, ..Default::default() },
1025                BlockBody::default(),
1026                Some(vec![reth_ethereum_primitives::Receipt {
1027                    tx_type: alloy_consensus::TxType::Legacy,
1028                    success: true,
1029                    cumulative_gas_used: 0,
1030                    logs: vec![],
1031                }]),
1032            ))))
1033        }
1034    }
1035
1036    #[derive(Debug)]
1037    struct TestMeta {
1038        marked: Cell<bool>,
1039    }
1040
1041    impl EraMeta for TestMeta {
1042        fn mark_as_processed(&self) -> eyre::Result<()> {
1043            self.marked.set(true);
1044            Ok(())
1045        }
1046
1047        fn path(&self) -> &Path {
1048            Path::new("test.era1")
1049        }
1050    }
1051
1052    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1053    async fn import_stops_at_to_block() {
1054        let pf = create_test_provider_factory();
1055        init_genesis(&pf).unwrap();
1056
1057        let folder = tempdir().unwrap();
1058        let mut hash_collector = Collector::new(4096, Some(folder.path().to_owned()));
1059
1060        // Each file yields blocks 1 and 2; without `to_block` the import would reach 2.
1061        let stream = futures_util::stream::iter(vec![
1062            Ok(TestMeta { marked: Cell::new(false) }),
1063            Ok(TestMeta { marked: Cell::new(false) }),
1064        ]);
1065
1066        let height = import::<TestEra, _, _, _, Block, _, _>(
1067            stream,
1068            &pf,
1069            &mut hash_collector,
1070            Some(1),
1071            false,
1072            &|_| false,
1073        )
1074        .unwrap();
1075
1076        assert_eq!(height, 1);
1077    }
1078
1079    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1080    async fn backfill_does_not_move_header_checkpoints_backwards() {
1081        let pf = create_test_provider_factory();
1082        init_genesis(&pf).unwrap();
1083        let static_file_provider = pf.static_file_provider();
1084        let folder = tempdir().unwrap();
1085        let mut hash_collector = Collector::new(4096, Some(folder.path().to_owned()));
1086
1087        // Import headers and bodies for blocks 1 and 2 first.
1088        let provider = pf.database_provider_rw().unwrap();
1089        {
1090            let mut writer =
1091                static_file_provider.latest_writer(StaticFileSegment::Headers).unwrap();
1092            let meta = TestMeta { marked: Cell::new(false) };
1093            process::<TestEra, _, Block, _, _>(
1094                &meta,
1095                &mut writer,
1096                None,
1097                &provider,
1098                &mut hash_collector,
1099                0..=2,
1100                ImportPolicy { headers_tip: 0, is_receipt_verifiable: &|_| false },
1101            )
1102            .unwrap();
1103            writer.commit().unwrap();
1104        }
1105        save_stage_checkpoints(&provider, 0, 2, 2, 2).unwrap();
1106        // Only block 1 was executed, so the repair ends below the headers already in static files.
1107        provider.save_stage_checkpoint(StageId::Execution, StageCheckpoint::new(1)).unwrap();
1108        provider.commit().unwrap();
1109
1110        let stream = futures_util::stream::iter(vec![Ok(TestMeta { marked: Cell::new(false) })]);
1111        let height = import::<TestEraWithEmptyReceipts, _, _, _, Block, _, _>(
1112            stream,
1113            &pf,
1114            &mut hash_collector,
1115            None,
1116            true,
1117            &|_| true,
1118        )
1119        .unwrap();
1120
1121        assert_eq!(height, 1);
1122        let provider = pf.database_provider_rw().unwrap();
1123        for stage in [StageId::Headers, StageId::Bodies] {
1124            assert_eq!(
1125                provider.get_stage_checkpoint(stage).unwrap().map(|c| c.block_number),
1126                Some(2),
1127                "{stage} checkpoint must not regress below the headers already in static files"
1128            );
1129        }
1130    }
1131
1132    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1133    async fn receipt_import_requires_an_executed_range() {
1134        let pf = create_test_provider_factory();
1135        init_genesis(&pf).unwrap();
1136        let folder = tempdir().unwrap();
1137        let mut hash_collector = Collector::new(4096, Some(folder.path().to_owned()));
1138
1139        // Nothing executed, so there is no range whose receipts could survive a node start.
1140        let stream = futures_util::stream::iter(vec![Ok(TestMeta { marked: Cell::new(false) })]);
1141        let result = import::<TestEraWithEmptyReceipts, _, _, _, Block, _, _>(
1142            stream,
1143            &pf,
1144            &mut hash_collector,
1145            None,
1146            true,
1147            &|_| true,
1148        );
1149
1150        assert!(result.is_err());
1151    }
1152
1153    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1154    async fn receipt_import_rejects_a_to_block_off_the_execution_checkpoint() {
1155        let pf = create_test_provider_factory();
1156        init_genesis(&pf).unwrap();
1157        let folder = tempdir().unwrap();
1158        let mut hash_collector = Collector::new(4096, Some(folder.path().to_owned()));
1159
1160        let provider = pf.database_provider_rw().unwrap();
1161        provider.save_stage_checkpoint(StageId::Execution, StageCheckpoint::new(2)).unwrap();
1162        provider.commit().unwrap();
1163
1164        // Stopping at 1 would leave the receipts behind the executed range.
1165        let stream = futures_util::stream::iter(vec![Ok(TestMeta { marked: Cell::new(false) })]);
1166        let result = import::<TestEraWithEmptyReceipts, _, _, _, Block, _, _>(
1167            stream,
1168            &pf,
1169            &mut hash_collector,
1170            Some(1),
1171            true,
1172            &|_| true,
1173        );
1174
1175        assert!(result.is_err());
1176    }
1177
1178    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1179    async fn receipt_import_backfills_a_completely_absent_segment() {
1180        // No genesis, so the Receipts segment does not exist at all.
1181        let pf = create_test_provider_factory();
1182        let static_file_provider = pf.static_file_provider();
1183        let folder = tempdir().unwrap();
1184        let mut hash_collector = Collector::new(4096, Some(folder.path().to_owned()));
1185
1186        // Stand in for the genesis entries `init_genesis` would write to every segment, leaving
1187        // only `Receipts` absent.
1188        {
1189            let mut writer =
1190                static_file_provider.latest_writer(StaticFileSegment::Transactions).unwrap();
1191            writer.increment_block(0).unwrap();
1192            writer.commit().unwrap();
1193        }
1194
1195        let provider = pf.database_provider_rw().unwrap();
1196        {
1197            let mut writer =
1198                static_file_provider.latest_writer(StaticFileSegment::Headers).unwrap();
1199            let genesis = Header::default();
1200            writer.append_header(&genesis, &genesis.hash_slow()).unwrap();
1201
1202            let meta = TestMeta { marked: Cell::new(false) };
1203            process::<TestEra, _, Block, _, _>(
1204                &meta,
1205                &mut writer,
1206                None,
1207                &provider,
1208                &mut hash_collector,
1209                0..=2,
1210                ImportPolicy { headers_tip: 0, is_receipt_verifiable: &|_| true },
1211            )
1212            .unwrap();
1213            writer.commit().unwrap();
1214        }
1215        provider.save_stage_checkpoint(StageId::Execution, StageCheckpoint::new(2)).unwrap();
1216        provider.commit().unwrap();
1217
1218        assert_eq!(
1219            static_file_provider.get_highest_static_file_block(StaticFileSegment::Receipts),
1220            None
1221        );
1222
1223        let stream = futures_util::stream::iter(vec![Ok(TestMeta { marked: Cell::new(false) })]);
1224        let height = import::<TestEraWithEmptyReceipts, _, _, _, Block, _, _>(
1225            stream,
1226            &pf,
1227            &mut hash_collector,
1228            None,
1229            true,
1230            &|_| true,
1231        )
1232        .unwrap();
1233
1234        assert_eq!(height, 2);
1235        assert_eq!(
1236            static_file_provider.get_highest_static_file_block(StaticFileSegment::Receipts),
1237            Some(2)
1238        );
1239    }
1240
1241    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1242    async fn receipt_import_backfills_an_absent_segment_after_non_zero_genesis() {
1243        const GENESIS: u64 = 100;
1244
1245        let pf = create_test_provider_factory_with_genesis_block_number(GENESIS);
1246        let static_file_provider = pf.static_file_provider();
1247        let folder = tempdir().unwrap();
1248        let mut hash_collector = Collector::new(4096, Some(folder.path().to_owned()));
1249
1250        {
1251            let mut writer =
1252                static_file_provider.get_writer(GENESIS, StaticFileSegment::Transactions).unwrap();
1253            writer.user_header_mut().set_block_range(GENESIS, GENESIS);
1254            writer.commit().unwrap();
1255        }
1256
1257        let provider = pf.database_provider_rw().unwrap();
1258        {
1259            let mut writer =
1260                static_file_provider.get_writer(GENESIS, StaticFileSegment::Headers).unwrap();
1261            let genesis = Header { number: GENESIS, ..Default::default() };
1262            writer.user_header_mut().set_block_range(GENESIS, GENESIS);
1263            writer
1264                .append_header_direct(&genesis, genesis.difficulty, &genesis.hash_slow())
1265                .unwrap();
1266
1267            let meta = TestMeta { marked: Cell::new(false) };
1268            process::<TestEraWithNonZeroGenesis, _, Block, _, _>(
1269                &meta,
1270                &mut writer,
1271                None,
1272                &provider,
1273                &mut hash_collector,
1274                GENESIS..=102,
1275                ImportPolicy { headers_tip: GENESIS, is_receipt_verifiable: &|_| true },
1276            )
1277            .unwrap();
1278            writer.commit().unwrap();
1279        }
1280        provider.save_stage_checkpoint(StageId::Execution, StageCheckpoint::new(102)).unwrap();
1281        provider.commit().unwrap();
1282
1283        assert_eq!(static_file_provider.genesis_block_number(), GENESIS);
1284        assert_eq!(
1285            static_file_provider.get_highest_static_file_block(StaticFileSegment::Receipts),
1286            None
1287        );
1288
1289        let stream = futures_util::stream::iter(vec![Ok(TestMeta { marked: Cell::new(false) })]);
1290        let height = import::<TestEraWithNonZeroGenesis, _, _, _, Block, _, _>(
1291            stream,
1292            &pf,
1293            &mut hash_collector,
1294            None,
1295            true,
1296            &|_| true,
1297        )
1298        .unwrap();
1299
1300        assert_eq!(height, 102);
1301        assert_eq!(
1302            static_file_provider.get_highest_static_file_block(StaticFileSegment::Receipts),
1303            Some(102)
1304        );
1305    }
1306
1307    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1308    async fn receipt_import_rejects_a_prune_config_that_bypasses_static_files() {
1309        let prune_modes = PruneModes {
1310            receipts_log_filter: ReceiptsLogPruneConfig(
1311                std::iter::once((Address::ZERO, PruneMode::Full)).collect(),
1312            ),
1313            ..Default::default()
1314        };
1315        let pf = create_test_provider_factory().with_prune_modes(prune_modes);
1316        init_genesis(&pf).unwrap();
1317        let folder = tempdir().unwrap();
1318        let mut hash_collector = Collector::new(4096, Some(folder.path().to_owned()));
1319
1320        let provider = pf.database_provider_rw().unwrap();
1321        provider.save_stage_checkpoint(StageId::Execution, StageCheckpoint::new(2)).unwrap();
1322        provider.commit().unwrap();
1323
1324        let stream = futures_util::stream::iter(vec![Ok(TestMeta { marked: Cell::new(false) })]);
1325        let result = import::<TestEraWithEmptyReceipts, _, _, _, Block, _, _>(
1326            stream,
1327            &pf,
1328            &mut hash_collector,
1329            None,
1330            true,
1331            &|_| true,
1332        );
1333
1334        assert!(result.is_err());
1335    }
1336
1337    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1338    async fn receipt_import_rejects_a_repair_starting_before_byzantium() {
1339        let pf = create_test_provider_factory();
1340        init_genesis(&pf).unwrap();
1341        let folder = tempdir().unwrap();
1342        let mut hash_collector = Collector::new(4096, Some(folder.path().to_owned()));
1343
1344        let provider = pf.database_provider_rw().unwrap();
1345        provider.save_stage_checkpoint(StageId::Execution, StageCheckpoint::new(2)).unwrap();
1346        provider.commit().unwrap();
1347
1348        // Receipts resume at block 1, before this chain's Byzantium activation at block 2.
1349        let stream = futures_util::stream::iter(vec![Ok(TestMeta { marked: Cell::new(false) })]);
1350        let result = import::<TestEraWithEmptyReceipts, _, _, _, Block, _, _>(
1351            stream,
1352            &pf,
1353            &mut hash_collector,
1354            None,
1355            true,
1356            &|number| number >= 2,
1357        );
1358
1359        assert!(result.is_err());
1360    }
1361
1362    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1363    async fn receipt_import_errors_when_the_source_stops_short() {
1364        let pf = create_test_provider_factory();
1365        init_genesis(&pf).unwrap();
1366        let folder = tempdir().unwrap();
1367        let mut hash_collector = Collector::new(4096, Some(folder.path().to_owned()));
1368
1369        let provider = pf.database_provider_rw().unwrap();
1370        provider.save_stage_checkpoint(StageId::Execution, StageCheckpoint::new(10)).unwrap();
1371        provider.commit().unwrap();
1372
1373        // The source only carries blocks 1 and 2, far short of the executed range.
1374        let stream = futures_util::stream::iter(vec![Ok(TestMeta { marked: Cell::new(false) })]);
1375        let result = import::<TestEraWithEmptyReceipts, _, _, _, Block, _, _>(
1376            stream,
1377            &pf,
1378            &mut hash_collector,
1379            None,
1380            true,
1381            &|_| true,
1382        );
1383
1384        assert!(result.is_err());
1385    }
1386
1387    #[test]
1388    fn process_does_not_mark_partially_consumed_file_processed() {
1389        let pf = create_test_provider_factory();
1390        init_genesis(&pf).unwrap();
1391
1392        let static_file_provider = pf.static_file_provider();
1393        let mut writer = static_file_provider.latest_writer(StaticFileSegment::Headers).unwrap();
1394        let provider = pf.database_provider_rw().unwrap();
1395        let folder = tempdir().unwrap();
1396        let mut hash_collector = Collector::new(4096, Some(folder.path().to_owned()));
1397        let meta = TestMeta { marked: Cell::new(false) };
1398
1399        let height = process::<TestEra, _, Block, _, _>(
1400            &meta,
1401            &mut writer,
1402            None,
1403            &provider,
1404            &mut hash_collector,
1405            0..=1,
1406            ImportPolicy { headers_tip: 0, is_receipt_verifiable: &|_| false },
1407        )
1408        .unwrap();
1409
1410        assert_eq!(height, 1);
1411        assert!(!meta.marked.get());
1412    }
1413
1414    #[test]
1415    fn process_iter_rejects_non_contiguous_blocks() {
1416        let pf = create_test_provider_factory();
1417        init_genesis(&pf).unwrap();
1418
1419        let static_file_provider = pf.static_file_provider();
1420        let mut writer = static_file_provider.latest_writer(StaticFileSegment::Headers).unwrap();
1421        let provider = pf.database_provider_rw().unwrap();
1422        let folder = tempdir().unwrap();
1423        let mut hash_collector = Collector::new(4096, Some(folder.path().to_owned()));
1424
1425        // Genesis DB sits at height 0, but the first block is 5: a gap that must be rejected
1426        // rather than appended (as a pre-merge `.era` import would otherwise produce).
1427        let blocks = [5u64, 6].into_iter().map(|number| {
1428            Ok((Header { number, ..Default::default() }, BlockBody::default(), None))
1429        });
1430
1431        let result = process_iter::<_, Block, _, _>(
1432            blocks,
1433            &mut writer,
1434            None,
1435            &provider,
1436            &mut hash_collector,
1437            0..,
1438            ImportPolicy { headers_tip: 0, is_receipt_verifiable: &|_| false },
1439        );
1440
1441        assert!(result.is_err());
1442    }
1443
1444    #[test]
1445    fn process_iter_errors_when_receipts_missing() {
1446        let pf = create_test_provider_factory();
1447        init_genesis(&pf).unwrap();
1448
1449        let static_file_provider = pf.static_file_provider();
1450        let mut writer = static_file_provider.latest_writer(StaticFileSegment::Headers).unwrap();
1451        let mut receipts_writer =
1452            static_file_provider.latest_writer(StaticFileSegment::Receipts).unwrap();
1453        let provider = pf.database_provider_rw().unwrap();
1454        let folder = tempdir().unwrap();
1455        let mut hash_collector = Collector::new(4096, Some(folder.path().to_owned()));
1456
1457        // `TestEra` never yields receipts; requesting them must fail rather than silently import
1458        // headers/bodies without them.
1459        let blocks: Vec<
1460            eyre::Result<EraBlock<Header, BlockBody, reth_ethereum_primitives::Receipt>>,
1461        > = vec![Ok((Header { number: 1, ..Default::default() }, BlockBody::default(), None))];
1462
1463        let result = process_iter::<_, Block, _, _>(
1464            blocks.into_iter(),
1465            &mut writer,
1466            Some(&mut receipts_writer),
1467            &provider,
1468            &mut hash_collector,
1469            0..,
1470            ImportPolicy { headers_tip: 0, is_receipt_verifiable: &|_| false },
1471        );
1472
1473        assert!(result.is_err());
1474    }
1475
1476    #[test]
1477    fn process_errors_on_receipt_count_mismatch() {
1478        let pf = create_test_provider_factory();
1479        init_genesis(&pf).unwrap();
1480
1481        let static_file_provider = pf.static_file_provider();
1482        let mut writer = static_file_provider.latest_writer(StaticFileSegment::Headers).unwrap();
1483        let mut receipts_writer =
1484            static_file_provider.latest_writer(StaticFileSegment::Receipts).unwrap();
1485        let provider = pf.database_provider_rw().unwrap();
1486        let folder = tempdir().unwrap();
1487        let mut hash_collector = Collector::new(4096, Some(folder.path().to_owned()));
1488        let meta = TestMeta { marked: Cell::new(false) };
1489
1490        // One receipt for a transaction-less body: a count mismatch that must be rejected rather
1491        // than silently misaligning the Receipts static file against Transactions.
1492        let result = process::<TestEraWithMismatchedReceipts, _, Block, _, _>(
1493            &meta,
1494            &mut writer,
1495            Some(&mut receipts_writer),
1496            &provider,
1497            &mut hash_collector,
1498            0..,
1499            ImportPolicy { headers_tip: 0, is_receipt_verifiable: &|_| false },
1500        );
1501
1502        assert!(result.is_err());
1503    }
1504
1505    #[test]
1506    fn save_stage_checkpoints_leaves_execution_unset() {
1507        let pf = create_test_provider_factory();
1508        init_genesis(&pf).unwrap();
1509        let provider = pf.database_provider_rw().unwrap();
1510
1511        let execution_before = provider.get_stage_checkpoint(StageId::Execution).unwrap();
1512        save_stage_checkpoints(&provider, 0, 10, 10, 10).unwrap();
1513
1514        assert_eq!(
1515            provider.get_stage_checkpoint(StageId::Headers).unwrap().map(|c| c.block_number),
1516            Some(10)
1517        );
1518        assert_eq!(
1519            provider.get_stage_checkpoint(StageId::Bodies).unwrap().map(|c| c.block_number),
1520            Some(10)
1521        );
1522        // Receipt import doesn't produce state, so it must not advance Execution.
1523        assert_eq!(provider.get_stage_checkpoint(StageId::Execution).unwrap(), execution_before);
1524    }
1525
1526    #[test]
1527    fn backfills_receipts_onto_existing_headers() {
1528        let pf = create_test_provider_factory();
1529        init_genesis(&pf).unwrap();
1530        let static_file_provider = pf.static_file_provider();
1531        let folder = tempdir().unwrap();
1532        let mut hash_collector = Collector::new(4096, Some(folder.path().to_owned()));
1533
1534        // First pass: import headers and bodies only, no receipts.
1535        {
1536            let provider = pf.database_provider_rw().unwrap();
1537            // The writer holds the Headers segment lock, which `provider.commit()` also takes when
1538            // it finalizes every segment, so it must be released first.
1539            {
1540                let mut writer =
1541                    static_file_provider.latest_writer(StaticFileSegment::Headers).unwrap();
1542                let meta = TestMeta { marked: Cell::new(false) };
1543                process::<TestEra, _, Block, _, _>(
1544                    &meta,
1545                    &mut writer,
1546                    None,
1547                    &provider,
1548                    &mut hash_collector,
1549                    0..=2,
1550                    ImportPolicy { headers_tip: 0, is_receipt_verifiable: &|_| false },
1551                )
1552                .unwrap();
1553                writer.commit().unwrap();
1554            }
1555            provider.commit().unwrap();
1556        }
1557        assert_eq!(
1558            static_file_provider.get_highest_static_file_block(StaticFileSegment::Headers),
1559            Some(2)
1560        );
1561        // Receipts still only cover genesis; blocks 1 and 2 have headers but no receipts yet.
1562        assert_eq!(
1563            static_file_provider.get_highest_static_file_block(StaticFileSegment::Receipts),
1564            Some(0)
1565        );
1566
1567        // Second pass: backfill receipts for the already-imported headers (`headers_tip = 2`).
1568        {
1569            let provider = pf.database_provider_rw().unwrap();
1570            {
1571                let mut writer =
1572                    static_file_provider.latest_writer(StaticFileSegment::Headers).unwrap();
1573                let mut receipts_writer =
1574                    static_file_provider.latest_writer(StaticFileSegment::Receipts).unwrap();
1575                let meta = TestMeta { marked: Cell::new(false) };
1576                process::<TestEraWithEmptyReceipts, _, Block, _, _>(
1577                    &meta,
1578                    &mut writer,
1579                    Some(&mut receipts_writer),
1580                    &provider,
1581                    &mut hash_collector,
1582                    0..,
1583                    ImportPolicy { headers_tip: 2, is_receipt_verifiable: &|_| false },
1584                )
1585                .unwrap();
1586                receipts_writer.commit().unwrap();
1587                writer.commit().unwrap();
1588            }
1589            provider.commit().unwrap();
1590        }
1591
1592        // Receipts now cover the previously header-only range, and headers weren't re-appended.
1593        assert_eq!(
1594            static_file_provider.get_highest_static_file_block(StaticFileSegment::Receipts),
1595            Some(2)
1596        );
1597        assert_eq!(
1598            static_file_provider.get_highest_static_file_block(StaticFileSegment::Headers),
1599            Some(2)
1600        );
1601    }
1602
1603    #[test]
1604    fn process_iter_persists_verified_receipts() {
1605        let pf = create_test_provider_factory();
1606        init_genesis(&pf).unwrap();
1607        let static_file_provider = pf.static_file_provider();
1608        let folder = tempdir().unwrap();
1609        let mut hash_collector = Collector::new(4096, Some(folder.path().to_owned()));
1610
1611        let (header, body, receipt) = block_with_one_receipt(1);
1612        let provider = pf.database_provider_rw().unwrap();
1613        {
1614            let mut writer =
1615                static_file_provider.latest_writer(StaticFileSegment::Headers).unwrap();
1616            let mut receipts_writer =
1617                static_file_provider.latest_writer(StaticFileSegment::Receipts).unwrap();
1618
1619            process_iter::<_, Block, _, _>(
1620                std::iter::once(Ok((header, body, Some(vec![receipt.clone()])))),
1621                &mut writer,
1622                Some(&mut receipts_writer),
1623                &provider,
1624                &mut hash_collector,
1625                0..,
1626                ImportPolicy { headers_tip: 0, is_receipt_verifiable: &|_| true },
1627            )
1628            .unwrap();
1629
1630            receipts_writer.commit().unwrap();
1631            writer.commit().unwrap();
1632        }
1633        provider.commit().unwrap();
1634
1635        let provider = pf.provider().unwrap();
1636        assert_eq!(provider.receipts_by_block(1.into()).unwrap(), Some(vec![receipt]));
1637    }
1638
1639    #[test]
1640    fn process_iter_rejects_receipts_the_header_does_not_commit_to() {
1641        let pf = create_test_provider_factory();
1642        init_genesis(&pf).unwrap();
1643        let static_file_provider = pf.static_file_provider();
1644        let folder = tempdir().unwrap();
1645        let mut hash_collector = Collector::new(4096, Some(folder.path().to_owned()));
1646
1647        // Right receipt count, wrong contents: only the recomputed root catches this.
1648        let (header, body, receipt) = block_with_one_receipt(1);
1649        let tampered = Receipt { cumulative_gas_used: 42_000, ..receipt };
1650
1651        let provider = pf.database_provider_rw().unwrap();
1652        let mut writer = static_file_provider.latest_writer(StaticFileSegment::Headers).unwrap();
1653        let mut receipts_writer =
1654            static_file_provider.latest_writer(StaticFileSegment::Receipts).unwrap();
1655
1656        let result = process_iter::<_, Block, _, _>(
1657            std::iter::once(Ok((header, body, Some(vec![tampered])))),
1658            &mut writer,
1659            Some(&mut receipts_writer),
1660            &provider,
1661            &mut hash_collector,
1662            0..,
1663            ImportPolicy { headers_tip: 0, is_receipt_verifiable: &|_| true },
1664        );
1665
1666        assert!(result.is_err());
1667    }
1668
1669    #[test]
1670    fn decodes_post_byzantium_era1_receipts() {
1671        let tuple = era1_block_tuple(4_370_000, vec![era1_receipt(Eip658Value::Eip658(true))]);
1672
1673        let (_, _, receipts) =
1674            decode_with_receipts::<Header, BlockBody, Receipt, E2sError>(Ok(tuple), true).unwrap();
1675
1676        let receipts = receipts.unwrap();
1677        assert_eq!(receipts.len(), 1);
1678        assert!(receipts[0].success);
1679        assert_eq!(receipts[0].cumulative_gas_used, 21_000);
1680    }
1681
1682    #[test]
1683    fn decodes_typed_ere_receipts_into_node_receipts() {
1684        let logs = vec![Log::new_unchecked(
1685            Address::repeat_byte(0x11),
1686            vec![B256::repeat_byte(0x22)],
1687            Bytes::from_static(b"typed"),
1688        )];
1689        let slim = vec![
1690            SlimReceipt {
1691                tx_type: TxType::Eip2930,
1692                status: Eip658Value::Eip658(true),
1693                cumulative_gas_used: 21_000,
1694                logs: logs.clone(),
1695            },
1696            SlimReceipt {
1697                tx_type: TxType::Eip1559,
1698                status: Eip658Value::Eip658(false),
1699                cumulative_gas_used: 42_000,
1700                logs: vec![],
1701            },
1702        ];
1703        let tuple = ere_block_tuple(12_965_000, &slim);
1704
1705        let (_, _, receipts) =
1706            Ere::decode_with_receipts::<Header, BlockBody, Receipt, E2sError>(Ok(tuple), true)
1707                .unwrap();
1708
1709        assert_eq!(
1710            receipts,
1711            Some(vec![
1712                Receipt {
1713                    tx_type: TxType::Eip2930,
1714                    success: true,
1715                    cumulative_gas_used: 21_000,
1716                    logs,
1717                },
1718                Receipt {
1719                    tx_type: TxType::Eip1559,
1720                    success: false,
1721                    cumulative_gas_used: 42_000,
1722                    logs: vec![],
1723                },
1724            ])
1725        );
1726    }
1727
1728    #[test]
1729    fn rejects_pre_byzantium_era1_receipts() {
1730        // Mainnet's first transaction: its receipt commits to a post-state root.
1731        let tuple = era1_block_tuple(
1732            46_147,
1733            vec![era1_receipt(Eip658Value::PostState(B256::repeat_byte(1)))],
1734        );
1735
1736        let err = decode_with_receipts::<Header, BlockBody, Receipt, E2sError>(Ok(tuple), true)
1737            .unwrap_err()
1738            .to_string();
1739
1740        assert!(err.contains("pre-Byzantium"), "unexpected error: {err}");
1741        assert!(err.contains("46147"), "error should name the offending block: {err}");
1742    }
1743
1744    #[test]
1745    fn skips_pre_byzantium_receipts_when_not_requested() {
1746        // A header-only import of the same file must stay unaffected.
1747        let tuple = era1_block_tuple(
1748            46_147,
1749            vec![era1_receipt(Eip658Value::PostState(B256::repeat_byte(1)))],
1750        );
1751
1752        let (header, _, receipts) =
1753            decode_with_receipts::<Header, BlockBody, Receipt, E2sError>(Ok(tuple), false).unwrap();
1754
1755        assert_eq!(header.number, 46_147);
1756        assert!(receipts.is_none());
1757    }
1758
1759    #[test]
1760    fn backfill_rejects_a_header_that_differs_from_the_persisted_one() {
1761        let pf = create_test_provider_factory();
1762        init_genesis(&pf).unwrap();
1763        let static_file_provider = pf.static_file_provider();
1764        let folder = tempdir().unwrap();
1765        let mut hash_collector = Collector::new(4096, Some(folder.path().to_owned()));
1766
1767        let provider = pf.database_provider_rw().unwrap();
1768        {
1769            let mut writer =
1770                static_file_provider.latest_writer(StaticFileSegment::Headers).unwrap();
1771            let meta = TestMeta { marked: Cell::new(false) };
1772            process::<TestEra, _, Block, _, _>(
1773                &meta,
1774                &mut writer,
1775                None,
1776                &provider,
1777                &mut hash_collector,
1778                0..=2,
1779                ImportPolicy { headers_tip: 0, is_receipt_verifiable: &|_| false },
1780            )
1781            .unwrap();
1782            writer.commit().unwrap();
1783        }
1784        provider.commit().unwrap();
1785
1786        // Same height and receipt count as the persisted block, but a different header.
1787        let provider = pf.database_provider_rw().unwrap();
1788        let mut writer = static_file_provider.latest_writer(StaticFileSegment::Headers).unwrap();
1789        let mut receipts_writer =
1790            static_file_provider.latest_writer(StaticFileSegment::Receipts).unwrap();
1791
1792        let result = process_iter::<_, Block, _, _>(
1793            std::iter::once(Ok((
1794                Header { number: 1, gas_limit: 42, ..Default::default() },
1795                BlockBody::default(),
1796                Some(vec![]),
1797            ))),
1798            &mut writer,
1799            Some(&mut receipts_writer),
1800            &provider,
1801            &mut hash_collector,
1802            0..,
1803            ImportPolicy { headers_tip: 2, is_receipt_verifiable: &|_| false },
1804        );
1805
1806        assert!(result.is_err());
1807    }
1808
1809    #[test]
1810    fn verify_receipts_checks_the_bloom_even_without_the_root() {
1811        let receipts = vec![Receipt {
1812            tx_type: TxType::Legacy,
1813            success: true,
1814            cumulative_gas_used: 21_000,
1815            logs: vec![Log::new_unchecked(
1816                Address::ZERO,
1817                vec![B256::repeat_byte(1)],
1818                Bytes::default(),
1819            )],
1820        }];
1821
1822        // The header commits to no logs at all, so the bloom cannot match.
1823        assert!(verify_receipts(&Header::default(), &receipts, false).is_err());
1824    }
1825
1826    #[test]
1827    fn export_rejects_status_receipt_for_post_state_root() {
1828        let provider = MockEthProvider::default().with_genesis_block();
1829        let (header, body, receipt) = block_with_one_receipt(1);
1830        provider.add_block(header.hash_slow(), Block { header, body });
1831        provider.add_receipts(1, vec![receipt]);
1832        let (mut header, body, receipt) = block_with_one_receipt(2);
1833        let status_root = header.receipts_root;
1834        let post_state_root =
1835            calculate_receipt_root(&[era1_receipt(Eip658Value::PostState(B256::repeat_byte(1)))]);
1836        header.receipts_root = post_state_root;
1837        provider.add_block(header.hash_slow(), Block { header, body });
1838        provider.add_receipts(2, vec![receipt]);
1839
1840        for write in [export::<Era1, _>, export::<Ere, _>] {
1841            for max_blocks_per_file in [1, 2] {
1842                let dir = tempdir().unwrap();
1843                let config = ExportConfig {
1844                    dir: dir.path().to_owned(),
1845                    first_block_number: 1,
1846                    last_block_number: 2,
1847                    max_blocks_per_file,
1848                    ..Default::default()
1849                };
1850                assert_eq!(
1851                    write(&provider, &config).unwrap_err().to_string(),
1852                    format!("receipts root mismatch for block 2: computed {status_root}, header has {post_state_root}")
1853                );
1854                // The failing chunk is never written. A previously completed chunk is kept.
1855                assert_eq!(
1856                    fs::read_dir(dir.path()).unwrap().count(),
1857                    usize::from(max_blocks_per_file == 1)
1858                );
1859            }
1860        }
1861    }
1862}