Skip to main content

reth_provider/providers/static_file/
manager.rs

1use super::{
2    metrics::StaticFileProviderMetrics, writer::StaticFileWriters, LoadedJar,
3    StaticFileJarProvider, StaticFileProviderRW, StaticFileProviderRWRefMut,
4};
5use crate::{
6    changeset_walker::{
7        changeset_block_range, StaticFileAccountChangesetWalker, StaticFileStorageChangesetWalker,
8    },
9    to_range, BlockHashReader, BlockNumReader, BlockReader, BlockSource, EitherWriter,
10    EitherWriterDestination, HeaderProvider, ReceiptProvider, StageCheckpointReader, StatsReader,
11    TransactionVariant, TransactionsProvider, TransactionsProviderExt,
12};
13use alloy_consensus::{
14    transaction::{TransactionMeta, TxHashRef},
15    Header,
16};
17use alloy_eips::BlockHashOrNumber;
18use alloy_primitives::{b256, Address, BlockHash, BlockNumber, TxHash, TxNumber, B256};
19
20use parking_lot::RwLock;
21use reth_chain_state::ExecutedBlock;
22use reth_chainspec::{ChainInfo, ChainSpecProvider, EthChainSpec, NamedChain};
23use reth_concurrency::sync::{channel::mpsc, rayon};
24use reth_db::{
25    lockfile::StorageLock,
26    static_file::{
27        iter_static_files, BlockHashMask, HeaderMask, HeaderWithHashMask, ReceiptMask,
28        StaticFileCursor, StaticFileEntry, StorageChangesetMask, TransactionMask,
29        TransactionSenderMask,
30    },
31};
32use reth_db_api::{
33    cursor::DbCursorRO,
34    models::{AccountBeforeTx, BlockNumberAddress, StorageBeforeTx, StoredBlockBodyIndices},
35    table::{Decompress, Table, Value},
36    tables,
37    transaction::DbTx,
38};
39use reth_ethereum_primitives::{Receipt, TransactionSigned};
40use reth_execution_types::RecoveredBlockAndExecutionOutput;
41use reth_nippy_jar::{NippyJar, NippyJarChecker};
42use reth_node_types::NodePrimitives;
43use reth_primitives_traits::{
44    dashmap::DashMap, AlloyBlockHeader as _, BlockBody as _, RecoveredBlock, SealedHeader,
45    SignedTransaction, StorageEntry,
46};
47use reth_prune_types::{PruneCheckpoint, PruneSegment};
48use reth_stages_types::PipelineTarget;
49use reth_static_file_types::{
50    find_fixed_range, HighestStaticFiles, SegmentHeader, SegmentRangeInclusive, StaticFileMap,
51    StaticFileSegment, DEFAULT_BLOCKS_PER_STATIC_FILE,
52};
53use reth_storage_api::{
54    metadata::keys, BlockBodyIndicesProvider, ChangeSetReader, DBProvider, PruneCheckpointReader,
55    StorageChangeSetReader, StorageSettingsCache,
56};
57use reth_storage_errors::provider::{ProviderError, ProviderResult, StaticFileWriterError};
58use std::{
59    collections::BTreeMap,
60    fmt::Debug,
61    ops::{Deref, Range, RangeBounds, RangeInclusive},
62    path::{Path, PathBuf},
63    sync::{
64        atomic::{AtomicU64, Ordering},
65        Arc,
66    },
67};
68use tracing::{debug, info, info_span, instrument, trace, warn};
69
70/// Alias type for a map that can be queried for block or transaction ranges. It uses `u64` to
71/// represent either a block or a transaction number end of a static file range.
72type SegmentRanges = BTreeMap<u64, SegmentRangeInclusive>;
73
74/// Access mode on a static file provider. RO/RW.
75#[derive(Debug, Default, PartialEq, Eq)]
76pub enum StaticFileAccess {
77    /// Read-only access.
78    #[default]
79    RO,
80    /// Read-write access.
81    RW,
82}
83
84impl StaticFileAccess {
85    /// Returns `true` if read-only access.
86    pub const fn is_read_only(&self) -> bool {
87        matches!(self, Self::RO)
88    }
89
90    /// Returns `true` if read-write access.
91    pub const fn is_read_write(&self) -> bool {
92        matches!(self, Self::RW)
93    }
94}
95
96/// Context for static file block writes.
97///
98/// Contains target segments and pruning configuration.
99#[derive(Debug, Clone, Copy, Default)]
100pub struct StaticFileWriteCtx {
101    /// Whether transaction senders should be written to static files.
102    pub write_senders: bool,
103    /// Whether receipts should be written to static files.
104    pub write_receipts: bool,
105    /// Whether account changesets should be written to static files.
106    pub write_account_changesets: bool,
107    /// Whether storage changesets should be written to static files.
108    pub write_storage_changesets: bool,
109    /// The current chain tip block number (for pruning).
110    pub tip: BlockNumber,
111    /// The prune mode for receipts, if any.
112    pub receipts_prune_mode: Option<reth_prune_types::PruneMode>,
113    /// Whether receipts are prunable (based on storage settings and prune distance).
114    pub receipts_prunable: bool,
115}
116
117/// [`StaticFileProvider`] manages all existing [`StaticFileJarProvider`].
118///
119/// "Static files" contain immutable chain history data, such as:
120///  - transactions
121///  - headers
122///  - receipts
123///
124/// This provider type is responsible for reading and writing to static files.
125#[derive(Debug)]
126pub struct StaticFileProvider<N>(pub(crate) Arc<StaticFileProviderInner<N>>);
127
128impl<N> Clone for StaticFileProvider<N> {
129    fn clone(&self) -> Self {
130        Self(self.0.clone())
131    }
132}
133
134/// Builder for [`StaticFileProvider`] that allows configuration before initialization.
135#[derive(Debug)]
136pub struct StaticFileProviderBuilder<P> {
137    access: StaticFileAccess,
138    use_metrics: bool,
139    blocks_per_file: StaticFileMap<u64>,
140    path: P,
141    genesis_block_number: u64,
142}
143
144impl<P: AsRef<Path>> StaticFileProviderBuilder<P> {
145    /// Creates a new builder with read-write access.
146    pub fn read_write(path: P) -> Self {
147        Self {
148            path,
149            access: StaticFileAccess::RW,
150            blocks_per_file: Default::default(),
151            use_metrics: false,
152            genesis_block_number: 0,
153        }
154    }
155
156    /// Creates a new builder with read-only access.
157    pub fn read_only(path: P) -> Self {
158        Self {
159            path,
160            access: StaticFileAccess::RO,
161            blocks_per_file: Default::default(),
162            use_metrics: false,
163            genesis_block_number: 0,
164        }
165    }
166
167    /// Set custom blocks per file for specific segments.
168    ///
169    /// Each static file segment is stored across multiple files, and each of these files contains
170    /// up to the specified number of blocks of data. When the file gets full, a new file is
171    /// created with the new block range.
172    ///
173    /// This setting affects the size of each static file, and can be set per segment.
174    ///
175    /// If it is changed for an existing node, existing static files will not be affected and will
176    /// be finished with the old blocks per file setting, but new static files will use the new
177    /// setting.
178    pub fn with_blocks_per_file_for_segments(
179        mut self,
180        segments: &<StaticFileMap<u64> as Deref>::Target,
181    ) -> Self {
182        for (segment, &blocks_per_file) in segments {
183            self.blocks_per_file.insert(segment, blocks_per_file);
184        }
185        self
186    }
187
188    /// Set a custom number of blocks per file for all segments.
189    pub fn with_blocks_per_file(mut self, blocks_per_file: u64) -> Self {
190        for segment in StaticFileSegment::iter() {
191            self.blocks_per_file.insert(segment, blocks_per_file);
192        }
193        self
194    }
195
196    /// Set a custom number of blocks per file for a specific segment.
197    pub fn with_blocks_per_file_for_segment(
198        mut self,
199        segment: StaticFileSegment,
200        blocks_per_file: u64,
201    ) -> Self {
202        self.blocks_per_file.insert(segment, blocks_per_file);
203        self
204    }
205
206    /// Enables metrics on the [`StaticFileProvider`].
207    pub const fn with_metrics(mut self) -> Self {
208        self.use_metrics = true;
209        self
210    }
211
212    /// Sets the genesis block number for the [`StaticFileProvider`].
213    ///
214    /// This configures the genesis block number, which is used to determine the starting point
215    /// for block indexing and querying operations.
216    ///
217    /// # Arguments
218    ///
219    /// * `genesis_block_number` - The block number of the genesis block.
220    ///
221    /// # Returns
222    ///
223    /// Returns `Self` to allow method chaining.
224    pub const fn with_genesis_block_number(mut self, genesis_block_number: u64) -> Self {
225        self.genesis_block_number = genesis_block_number;
226        self
227    }
228
229    /// Builds the final [`StaticFileProvider`] and initializes the index.
230    pub fn build<N: NodePrimitives>(self) -> ProviderResult<StaticFileProvider<N>> {
231        let mut provider = StaticFileProviderInner::new(self.path, self.access)?;
232        if self.use_metrics {
233            provider.metrics = Some(Arc::new(StaticFileProviderMetrics::default()));
234        }
235
236        for (segment, blocks_per_file) in *self.blocks_per_file {
237            provider.blocks_per_file.insert(segment, blocks_per_file);
238        }
239        provider.genesis_block_number = self.genesis_block_number;
240
241        let provider = StaticFileProvider(Arc::new(provider));
242        provider.initialize_index()?;
243        Ok(provider)
244    }
245}
246
247impl<N: NodePrimitives> StaticFileProvider<N> {
248    /// Creates a new [`StaticFileProvider`] with the given [`StaticFileAccess`].
249    fn new(path: impl AsRef<Path>, access: StaticFileAccess) -> ProviderResult<Self> {
250        let provider = Self(Arc::new(StaticFileProviderInner::new(path, access)?));
251        provider.initialize_index()?;
252        Ok(provider)
253    }
254}
255
256impl<N: NodePrimitives> StaticFileProvider<N> {
257    /// Creates a new [`StaticFileProvider`] with read-only access.
258    ///
259    /// The caller is responsible for calling [`StaticFileProvider::initialize_index`] when
260    /// underlying data changes.
261    pub fn read_only(path: impl AsRef<Path>) -> ProviderResult<Self> {
262        Self::new(path, StaticFileAccess::RO)
263    }
264
265    /// Creates a new [`StaticFileProvider`] with read-write access.
266    pub fn read_write(path: impl AsRef<Path>) -> ProviderResult<Self> {
267        Self::new(path, StaticFileAccess::RW)
268    }
269}
270
271impl<N: NodePrimitives> Deref for StaticFileProvider<N> {
272    type Target = StaticFileProviderInner<N>;
273
274    fn deref(&self) -> &Self::Target {
275        &self.0
276    }
277}
278
279#[cfg(test)]
280type BeforeCacheInsert = Box<dyn FnOnce(StaticFileSegment) + Send + 'static>;
281
282#[cfg(test)]
283#[derive(Default)]
284struct BeforeCacheInsertHook(parking_lot::Mutex<Option<BeforeCacheInsert>>);
285
286#[cfg(test)]
287impl Debug for BeforeCacheInsertHook {
288    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
289        f.debug_struct("BeforeCacheInsertHook").finish_non_exhaustive()
290    }
291}
292
293#[cfg(test)]
294impl BeforeCacheInsertHook {
295    fn set(&self, hook: impl FnOnce(StaticFileSegment) + Send + 'static) {
296        let previous = self.0.lock().replace(Box::new(hook));
297        assert!(previous.is_none(), "cache fill hook already installed");
298    }
299
300    fn fire(&self, segment: StaticFileSegment) {
301        if let Some(hook) = self.0.lock().take() {
302            hook(segment);
303        }
304    }
305}
306
307/// [`StaticFileProviderInner`] manages all existing [`StaticFileJarProvider`].
308#[derive(Debug)]
309pub struct StaticFileProviderInner<N> {
310    /// Maintains a map which allows for concurrent access to different `NippyJars`, over different
311    /// segments and ranges.
312    map: DashMap<(BlockNumber, StaticFileSegment), LoadedJar>,
313    /// Incremented before clearing the jar cache so in-flight loads cannot repopulate it with a
314    /// snapshot from before the invalidation.
315    cache_generation: AtomicU64,
316    /// Indexes per segment.
317    indexes: RwLock<StaticFileMap<StaticFileSegmentIndex>>,
318    /// This is an additional index that tracks the expired height, this will track the highest
319    /// block number that has been expired (missing). The first, non expired block is
320    /// `expired_history_height + 1`.
321    ///
322    /// This is effectively the transaction range that has been expired:
323    /// [`StaticFileProvider::delete_segment_below_block`] and mirrors
324    /// `static_files_min_block[transactions] - blocks_per_file`.
325    ///
326    /// This additional tracker exists for more efficient lookups because the node must be aware of
327    /// the expired height.
328    earliest_history_height: AtomicU64,
329    /// Directory where `static_files` are located
330    path: PathBuf,
331    /// Maintains a writer set of [`StaticFileSegment`].
332    writers: StaticFileWriters<N>,
333    /// Metrics for the static files.
334    metrics: Option<Arc<StaticFileProviderMetrics>>,
335    /// Access rights of the provider.
336    access: StaticFileAccess,
337    /// Number of blocks per file, per segment.
338    blocks_per_file: StaticFileMap<u64>,
339    /// Write lock for when access is [`StaticFileAccess::RW`].
340    _lock_file: Option<StorageLock>,
341    /// Genesis block number, default is 0;
342    genesis_block_number: u64,
343    #[cfg(test)]
344    before_cache_insert: BeforeCacheInsertHook,
345    #[cfg(test)]
346    after_cache_validation: BeforeCacheInsertHook,
347}
348
349impl<N: NodePrimitives> StaticFileProviderInner<N> {
350    /// Creates a new [`StaticFileProviderInner`].
351    fn new(path: impl AsRef<Path>, access: StaticFileAccess) -> ProviderResult<Self> {
352        let _lock_file = if access.is_read_write() {
353            StorageLock::try_acquire(path.as_ref()).map_err(ProviderError::other)?.into()
354        } else {
355            None
356        };
357
358        let mut blocks_per_file = StaticFileMap::default();
359        for segment in StaticFileSegment::iter() {
360            blocks_per_file.insert(segment, DEFAULT_BLOCKS_PER_STATIC_FILE);
361        }
362
363        let provider = Self {
364            map: Default::default(),
365            cache_generation: Default::default(),
366            indexes: Default::default(),
367            writers: Default::default(),
368            earliest_history_height: Default::default(),
369            path: path.as_ref().to_path_buf(),
370            metrics: None,
371            access,
372            blocks_per_file,
373            _lock_file,
374            genesis_block_number: 0,
375            #[cfg(test)]
376            before_cache_insert: Default::default(),
377            #[cfg(test)]
378            after_cache_validation: Default::default(),
379        };
380
381        Ok(provider)
382    }
383
384    pub const fn is_read_only(&self) -> bool {
385        self.access.is_read_only()
386    }
387
388    /// Each static file has a fixed number of blocks. This gives out the range where the requested
389    /// block is positioned.
390    ///
391    /// If the specified block falls into one of the ranges of already initialized static files,
392    /// this function will return that range.
393    ///
394    /// If no matching file exists, this function will derive a new range from the end of the last
395    /// existing file, if any.
396    pub fn find_fixed_range_with_block_index(
397        &self,
398        segment: StaticFileSegment,
399        block_index: Option<&SegmentRanges>,
400        block: BlockNumber,
401    ) -> SegmentRangeInclusive {
402        let blocks_per_file =
403            self.blocks_per_file.get(segment).copied().unwrap_or(DEFAULT_BLOCKS_PER_STATIC_FILE);
404
405        if let Some(block_index) = block_index {
406            // Find first block range that contains the requested block
407            if let Some((_, range)) = block_index.range(block..).next() {
408                // Found matching range for an existing file using block index
409                return *range;
410            } else if let Some((_, range)) = block_index.last_key_value() {
411                // Didn't find matching range for an existing file, derive a new range from the end
412                // of the last existing file range.
413                //
414                // `block` is always higher than `range.end()` here, because `block_index` holds no
415                // range with a `max_block` greater than or equal to `block`
416                let blocks_after_last_range = block - range.end();
417                let segments_to_skip = (blocks_after_last_range - 1) / blocks_per_file;
418                let start = range.end() + 1 + segments_to_skip * blocks_per_file;
419                return SegmentRangeInclusive::new(start, start + blocks_per_file - 1);
420            }
421        }
422        // No block index is available, derive a new range using the fixed number of blocks,
423        // starting from the beginning.
424        find_fixed_range(block, blocks_per_file)
425    }
426
427    /// Each static file has a fixed number of blocks. This gives out the range where the requested
428    /// block is positioned.
429    ///
430    /// If the specified block falls into one of the ranges of already initialized static files,
431    /// this function will return that range.
432    ///
433    /// If no matching file exists, this function will derive a new range from the end of the last
434    /// existing file, if any.
435    ///
436    /// This function will block indefinitely if a write lock for
437    /// [`Self::indexes`] is already acquired. In that case, use
438    /// [`Self::find_fixed_range_with_block_index`].
439    pub fn find_fixed_range(
440        &self,
441        segment: StaticFileSegment,
442        block: BlockNumber,
443    ) -> SegmentRangeInclusive {
444        self.find_fixed_range_with_block_index(
445            segment,
446            self.indexes.read().get(segment).map(|index| &index.expected_block_ranges_by_max_block),
447            block,
448        )
449    }
450
451    /// Get genesis block number
452    pub const fn genesis_block_number(&self) -> u64 {
453        self.genesis_block_number
454    }
455}
456
457impl<N: NodePrimitives> StaticFileProvider<N> {
458    /// Reports metrics for the static files.
459    ///
460    /// This uses the in-memory index to get file sizes from mmap handles instead of reading
461    /// filesystem metadata.
462    pub fn report_metrics(&self) -> ProviderResult<()> {
463        let Some(metrics) = &self.metrics else { return Ok(()) };
464
465        let static_files = iter_static_files(&self.path).map_err(ProviderError::other)?;
466        for (segment, files) in &*static_files {
467            let mut entries = 0;
468            let mut size = 0;
469
470            for StaticFileEntry { block_range, .. } in files {
471                let fixed_block_range = self.find_fixed_range(segment, block_range.start());
472                let jar_provider = self
473                    .get_segment_provider_for_range(segment, || Some(fixed_block_range), None)?
474                    .ok_or_else(|| {
475                        ProviderError::MissingStaticFileBlock(segment, block_range.start())
476                    })?;
477
478                entries += jar_provider.rows();
479                size += jar_provider.size() as u64;
480            }
481
482            metrics.record_segment(segment, size, files.len(), entries);
483        }
484
485        Ok(())
486    }
487
488    /// Writes headers for all blocks to the static file segment.
489    #[instrument(level = "debug", target = "providers::static_file", skip_all)]
490    fn write_headers(
491        w: &mut StaticFileProviderRWRefMut<'_, N>,
492        blocks: &[ExecutedBlock<N>],
493    ) -> ProviderResult<()> {
494        for block in blocks {
495            let b = block.recovered_block();
496            w.append_header(b.header(), &b.hash())?;
497        }
498        Ok(())
499    }
500
501    /// Writes transactions for all blocks to the static file segment.
502    #[instrument(level = "debug", target = "providers::static_file", skip_all)]
503    fn write_transactions(
504        w: &mut StaticFileProviderRWRefMut<'_, N>,
505        blocks: &[ExecutedBlock<N>],
506        tx_nums: &[TxNumber],
507    ) -> ProviderResult<()> {
508        for (block, &first_tx) in blocks.iter().zip(tx_nums) {
509            let b = block.recovered_block();
510            w.increment_block(b.number())?;
511            for (i, tx) in b.body().transactions().iter().enumerate() {
512                w.append_transaction(first_tx + i as u64, tx)?;
513            }
514        }
515        Ok(())
516    }
517
518    /// Writes transaction senders for all blocks to the static file segment.
519    #[instrument(level = "debug", target = "providers::static_file", skip_all)]
520    fn write_transaction_senders(
521        w: &mut StaticFileProviderRWRefMut<'_, N>,
522        blocks: &[ExecutedBlock<N>],
523        tx_nums: &[TxNumber],
524    ) -> ProviderResult<()> {
525        for (block, &first_tx) in blocks.iter().zip(tx_nums) {
526            let b = block.recovered_block();
527            w.increment_block(b.number())?;
528            for (i, sender) in b.senders_iter().enumerate() {
529                w.append_transaction_sender(first_tx + i as u64, sender)?;
530            }
531        }
532        Ok(())
533    }
534
535    /// Writes receipts for all blocks to the static file segment.
536    #[instrument(level = "debug", target = "providers::static_file", skip_all)]
537    fn write_receipts(
538        w: &mut StaticFileProviderRWRefMut<'_, N>,
539        blocks: &[ExecutedBlock<N>],
540        tx_nums: &[TxNumber],
541        ctx: &StaticFileWriteCtx,
542    ) -> ProviderResult<()> {
543        for (block, &first_tx) in blocks.iter().zip(tx_nums) {
544            let block_number = block.recovered_block().number();
545            w.increment_block(block_number)?;
546
547            // skip writing receipts if pruning configuration requires us to.
548            if ctx.receipts_prunable &&
549                ctx.receipts_prune_mode
550                    .is_some_and(|mode| mode.should_prune(block_number, ctx.tip))
551            {
552                continue
553            }
554
555            for (i, receipt) in block.execution_outcome().receipts.iter().enumerate() {
556                w.append_receipt(first_tx + i as u64, receipt)?;
557            }
558        }
559        Ok(())
560    }
561
562    /// Writes account changesets for all blocks to the static file segment.
563    #[instrument(level = "debug", target = "providers::static_file", skip_all)]
564    fn write_account_changesets(
565        w: &mut StaticFileProviderRWRefMut<'_, N>,
566        blocks: &[ExecutedBlock<N>],
567    ) -> ProviderResult<()> {
568        for block in blocks {
569            let block_number = block.recovered_block().number();
570            let reverts = block.execution_outcome().state.reverts.to_plain_state_reverts();
571
572            let changeset: Vec<_> = reverts
573                .accounts
574                .into_iter()
575                .flatten()
576                .map(|(address, info)| AccountBeforeTx { address, info: info.map(Into::into) })
577                .collect();
578            w.append_account_changeset(changeset, block_number)?;
579        }
580        Ok(())
581    }
582
583    /// Writes storage changesets for all blocks to the static file segment.
584    #[instrument(level = "debug", target = "providers::db", skip_all)]
585    fn write_storage_changesets(
586        w: &mut StaticFileProviderRWRefMut<'_, N>,
587        blocks: &[ExecutedBlock<N>],
588    ) -> ProviderResult<()> {
589        for block in blocks {
590            let block_number = block.recovered_block().number();
591            let reverts = block.execution_outcome().state.reverts.to_plain_state_reverts();
592
593            let changeset: Vec<_> = reverts
594                .storage
595                .into_iter()
596                .flatten()
597                .flat_map(|revert| {
598                    revert.storage_revert.into_iter().map(move |(key, revert_to_slot)| {
599                        StorageBeforeTx {
600                            address: revert.address,
601                            key: key.into(),
602                            value: revert_to_slot.to_previous_value(),
603                        }
604                    })
605                })
606                .collect();
607            w.append_storage_changeset(changeset, block_number)?;
608        }
609        Ok(())
610    }
611
612    /// Writes to a static file segment using the provided closure.
613    ///
614    /// The closure receives a mutable reference to the segment writer. After the closure completes,
615    /// `sync_all()` is called to flush writes to disk.
616    #[instrument(level = "debug", target = "providers::static_file", skip_all, fields(?segment))]
617    fn write_segment<F>(
618        &self,
619        segment: StaticFileSegment,
620        first_block_number: BlockNumber,
621        f: F,
622    ) -> ProviderResult<()>
623    where
624        F: FnOnce(&mut StaticFileProviderRWRefMut<'_, N>) -> ProviderResult<()>,
625    {
626        let mut w = self.get_writer(first_block_number, segment)?;
627        f(&mut w)?;
628        w.sync_all()
629    }
630
631    /// Writes all static file data for multiple blocks in parallel per-segment.
632    ///
633    /// This spawns tasks on the storage thread pool for each segment type and each task calls
634    /// `sync_all()` on its writer when done.
635    #[instrument(level = "debug", target = "providers::static_file", skip_all)]
636    pub fn write_blocks_data(
637        &self,
638        blocks: &[ExecutedBlock<N>],
639        tx_nums: &[TxNumber],
640        ctx: StaticFileWriteCtx,
641        runtime: &reth_tasks::Runtime,
642    ) -> ProviderResult<()> {
643        if blocks.is_empty() {
644            return Ok(());
645        }
646
647        let first_block_number = blocks[0].recovered_block().number();
648
649        let mut r_headers = None;
650        let mut r_txs = None;
651        let mut r_senders = None;
652        let mut r_receipts = None;
653        let mut r_account_changesets = None;
654        let mut r_storage_changesets = None;
655
656        // Propagate tracing context into rayon-spawned threads so that per-segment
657        // write spans appear as children of write_blocks_data in traces.
658        let span = tracing::Span::current();
659        runtime.storage_pool().in_place_scope(|s| {
660            s.spawn(|_| {
661                let _guard = span.enter();
662                r_headers =
663                    Some(self.write_segment(StaticFileSegment::Headers, first_block_number, |w| {
664                        Self::write_headers(w, blocks)
665                    }));
666            });
667
668            s.spawn(|_| {
669                let _guard = span.enter();
670                r_txs = Some(self.write_segment(
671                    StaticFileSegment::Transactions,
672                    first_block_number,
673                    |w| Self::write_transactions(w, blocks, tx_nums),
674                ));
675            });
676
677            if ctx.write_senders {
678                s.spawn(|_| {
679                    let _guard = span.enter();
680                    r_senders = Some(self.write_segment(
681                        StaticFileSegment::TransactionSenders,
682                        first_block_number,
683                        |w| Self::write_transaction_senders(w, blocks, tx_nums),
684                    ));
685                });
686            }
687
688            if ctx.write_receipts {
689                s.spawn(|_| {
690                    let _guard = span.enter();
691                    r_receipts = Some(self.write_segment(
692                        StaticFileSegment::Receipts,
693                        first_block_number,
694                        |w| Self::write_receipts(w, blocks, tx_nums, &ctx),
695                    ));
696                });
697            }
698
699            if ctx.write_account_changesets {
700                s.spawn(|_| {
701                    let _guard = span.enter();
702                    r_account_changesets = Some(self.write_segment(
703                        StaticFileSegment::AccountChangeSets,
704                        first_block_number,
705                        |w| Self::write_account_changesets(w, blocks),
706                    ));
707                });
708            }
709
710            if ctx.write_storage_changesets {
711                s.spawn(|_| {
712                    let _guard = span.enter();
713                    r_storage_changesets = Some(self.write_segment(
714                        StaticFileSegment::StorageChangeSets,
715                        first_block_number,
716                        |w| Self::write_storage_changesets(w, blocks),
717                    ));
718                });
719            }
720        });
721
722        r_headers.ok_or(StaticFileWriterError::ThreadPanic("headers"))??;
723        r_txs.ok_or(StaticFileWriterError::ThreadPanic("transactions"))??;
724        if ctx.write_senders {
725            r_senders.ok_or(StaticFileWriterError::ThreadPanic("senders"))??;
726        }
727        if ctx.write_receipts {
728            r_receipts.ok_or(StaticFileWriterError::ThreadPanic("receipts"))??;
729        }
730        if ctx.write_account_changesets {
731            r_account_changesets
732                .ok_or(StaticFileWriterError::ThreadPanic("account_changesets"))??;
733        }
734        if ctx.write_storage_changesets {
735            r_storage_changesets
736                .ok_or(StaticFileWriterError::ThreadPanic("storage_changesets"))??;
737        }
738        Ok(())
739    }
740
741    /// Gets the [`StaticFileJarProvider`] of the requested segment and start index that can be
742    /// either block or transaction.
743    pub fn get_segment_provider(
744        &self,
745        segment: StaticFileSegment,
746        number: u64,
747    ) -> ProviderResult<StaticFileJarProvider<'_, N>> {
748        if segment.is_block_or_change_based() {
749            self.get_segment_provider_for_block(segment, number, None)
750        } else {
751            self.get_segment_provider_for_transaction(segment, number, None)
752        }
753    }
754
755    /// Gets the [`StaticFileJarProvider`] of the requested segment and start index that can be
756    /// either block or transaction.
757    ///
758    /// If the segment is not found, returns [`None`].
759    pub fn get_maybe_segment_provider(
760        &self,
761        segment: StaticFileSegment,
762        number: u64,
763    ) -> ProviderResult<Option<StaticFileJarProvider<'_, N>>> {
764        let provider = if segment.is_block_or_change_based() {
765            self.get_segment_provider_for_block(segment, number, None)
766        } else {
767            self.get_segment_provider_for_transaction(segment, number, None)
768        };
769
770        match provider {
771            Ok(provider) => Ok(Some(provider)),
772            Err(
773                ProviderError::MissingStaticFileBlock(_, _) |
774                ProviderError::MissingStaticFileTx(_, _),
775            ) => Ok(None),
776            Err(err) => Err(err),
777        }
778    }
779
780    /// Gets the [`StaticFileJarProvider`] of the requested segment and block.
781    pub fn get_segment_provider_for_block(
782        &self,
783        segment: StaticFileSegment,
784        block: BlockNumber,
785        path: Option<&Path>,
786    ) -> ProviderResult<StaticFileJarProvider<'_, N>> {
787        self.get_segment_provider_for_range(
788            segment,
789            || self.get_segment_ranges_from_block(segment, block),
790            path,
791        )?
792        .ok_or(ProviderError::MissingStaticFileBlock(segment, block))
793    }
794
795    /// Gets the [`StaticFileJarProvider`] of the requested segment and transaction.
796    pub fn get_segment_provider_for_transaction(
797        &self,
798        segment: StaticFileSegment,
799        tx: TxNumber,
800        path: Option<&Path>,
801    ) -> ProviderResult<StaticFileJarProvider<'_, N>> {
802        self.get_segment_provider_for_range(
803            segment,
804            || self.get_segment_ranges_from_transaction(segment, tx),
805            path,
806        )?
807        .ok_or(ProviderError::MissingStaticFileTx(segment, tx))
808    }
809
810    /// Gets the [`StaticFileJarProvider`] of the requested segment and block or transaction.
811    ///
812    /// `fn_range` should make sure the range goes through `find_fixed_range`.
813    pub fn get_segment_provider_for_range(
814        &self,
815        segment: StaticFileSegment,
816        fn_range: impl Fn() -> Option<SegmentRangeInclusive>,
817        path: Option<&Path>,
818    ) -> ProviderResult<Option<StaticFileJarProvider<'_, N>>> {
819        // If we have a path, then get the block range from its name.
820        // Otherwise, check `self.available_static_files`
821        let block_range = match path {
822            Some(path) => StaticFileSegment::parse_filename(
823                &path
824                    .file_name()
825                    .ok_or_else(|| {
826                        ProviderError::MissingStaticFileSegmentPath(segment, path.to_path_buf())
827                    })?
828                    .to_string_lossy(),
829            )
830            .and_then(|(parsed_segment, block_range)| {
831                if parsed_segment == segment {
832                    return Some(block_range);
833                }
834                None
835            }),
836            None => fn_range(),
837        };
838
839        // Return cached `LoadedJar` or insert it for the first time, and then, return it.
840        if let Some(block_range) = block_range {
841            return Ok(Some(self.get_or_create_jar_provider(segment, &block_range)?));
842        }
843
844        Ok(None)
845    }
846
847    /// Gets the [`StaticFileJarProvider`] of the requested path.
848    pub fn get_segment_provider_for_path(
849        &self,
850        path: &Path,
851    ) -> ProviderResult<Option<StaticFileJarProvider<'_, N>>> {
852        StaticFileSegment::parse_filename(
853            &path
854                .file_name()
855                .ok_or_else(|| ProviderError::MissingStaticFilePath(path.to_path_buf()))?
856                .to_string_lossy(),
857        )
858        .map(|(segment, block_range)| self.get_or_create_jar_provider(segment, &block_range))
859        .transpose()
860    }
861
862    /// Given a segment and block range it removes the cached provider from the map.
863    ///
864    /// CAUTION: cached provider should be dropped before calling this or IT WILL deadlock.
865    pub fn remove_cached_provider(
866        &self,
867        segment: StaticFileSegment,
868        fixed_block_range_end: BlockNumber,
869    ) {
870        self.map.remove(&(fixed_block_range_end, segment));
871    }
872
873    /// This handles history expiry by deleting all static files for the given segment below the
874    /// given block.
875    ///
876    /// For example if block is 1M and the blocks per file are 500K this will delete all individual
877    /// files below 1M, so 0-499K and 500K-999K.
878    ///
879    /// This will not delete the file that contains the block itself, because files can only be
880    /// removed entirely.
881    ///
882    /// # Safety
883    ///
884    /// This method will never delete the highest static file for the segment, even if the
885    /// requested block is higher than the highest block in static files. This ensures we always
886    /// maintain at least one static file if any exist.
887    ///
888    /// Returns a list of `SegmentHeader`s from the deleted jars.
889    pub fn delete_segment_below_block(
890        &self,
891        segment: StaticFileSegment,
892        block: BlockNumber,
893    ) -> ProviderResult<Vec<SegmentHeader>> {
894        // Nothing to delete if block is 0.
895        if block == 0 {
896            return Ok(Vec::new());
897        }
898
899        let highest_block = self.get_highest_static_file_block(segment);
900        let mut deleted_headers = Vec::new();
901
902        loop {
903            let Some(block_height) = self.get_lowest_range_end(segment) else {
904                return Ok(deleted_headers);
905            };
906
907            // Stop if we've reached the target block or the highest static file
908            if block_height >= block || Some(block_height) == highest_block {
909                return Ok(deleted_headers);
910            }
911
912            debug!(
913                target: "providers::static_file",
914                ?segment,
915                ?block_height,
916                "Deleting static file below block"
917            );
918
919            // now we need to wipe the static file, this will take care of updating the index and
920            // advance the lowest tracked block height for the segment.
921            let header = self.delete_jar(segment, block_height).inspect_err(|err| {
922                warn!( target: "providers::static_file", ?segment, %block_height, ?err, "Failed to delete static file below block")
923            })?;
924
925            deleted_headers.push(header);
926        }
927    }
928
929    /// Given a segment and block, it deletes the jar and all files from the respective block range.
930    ///
931    /// CAUTION: destructive. Deletes files on disk.
932    ///
933    /// This will re-initialize the index after deletion, so all files are tracked.
934    ///
935    /// Returns the `SegmentHeader` of the deleted jar.
936    pub fn delete_jar(
937        &self,
938        segment: StaticFileSegment,
939        block: BlockNumber,
940    ) -> ProviderResult<SegmentHeader> {
941        let fixed_block_range = self.find_fixed_range(segment, block);
942        let key = (fixed_block_range.end(), segment);
943        let file = self.path.join(segment.filename(&fixed_block_range));
944        let jar = if let Some((_, jar)) = self.map.remove(&key) {
945            jar.jar
946        } else {
947            debug!(
948                target: "providers::static_file",
949                ?file,
950                ?fixed_block_range,
951                ?block,
952                "Loading static file jar for deletion"
953            );
954            NippyJar::<SegmentHeader>::load(&file).map_err(ProviderError::other)?
955        };
956
957        let header = jar.user_header().clone();
958
959        // Delete the sidecar file for changeset segments before deleting the main jar
960        if segment.is_change_based() {
961            let csoff_path = file.with_extension("csoff");
962            if csoff_path.exists() {
963                std::fs::remove_file(&csoff_path).map_err(ProviderError::other)?;
964            }
965        }
966
967        jar.delete().map_err(ProviderError::other)?;
968
969        // SAFETY: this is currently necessary to ensure that certain indexes like
970        // `static_files_min_block` have the correct values after pruning.
971        self.initialize_index()?;
972
973        Ok(header)
974    }
975
976    /// Deletes ALL static file jars for the given segment, including the highest one.
977    ///
978    /// CAUTION: destructive. Deletes all files on disk for this segment.
979    ///
980    /// This is used for `PruneMode::Full` where all data should be removed.
981    ///
982    /// Returns a list of `SegmentHeader`s from the deleted jars.
983    pub fn delete_segment(&self, segment: StaticFileSegment) -> ProviderResult<Vec<SegmentHeader>> {
984        let mut deleted_headers = Vec::new();
985
986        self.writers.remove(segment);
987
988        while let Some(block_height) = self.get_highest_static_file_block(segment) {
989            debug!(
990                target: "providers::static_file",
991                ?segment,
992                ?block_height,
993                "Deleting static file jar"
994            );
995
996            let header = self.delete_jar(segment, block_height).inspect_err(|err| {
997                warn!(target: "providers::static_file", ?segment, %block_height, ?err, "Failed to delete static file jar")
998            })?;
999
1000            deleted_headers.push(header);
1001        }
1002
1003        Ok(deleted_headers)
1004    }
1005
1006    /// Given a segment and block range it returns a cached
1007    /// [`StaticFileJarProvider`]. TODO(joshie): we should check the size and pop N if there's too
1008    /// many.
1009    fn get_or_create_jar_provider(
1010        &self,
1011        segment: StaticFileSegment,
1012        fixed_block_range: &SegmentRangeInclusive,
1013    ) -> ProviderResult<StaticFileJarProvider<'_, N>> {
1014        let key = (fixed_block_range.end(), segment);
1015
1016        // Avoid using `entry` directly to avoid a write lock in the common case.
1017        trace!(target: "providers::static_file", ?segment, ?fixed_block_range, "Getting provider");
1018        let mut provider: StaticFileJarProvider<'_, N> = if let Some(jar) = self.map.get(&key) {
1019            trace!(target: "providers::static_file", ?segment, ?fixed_block_range, "Jar found in cache");
1020            jar.into()
1021        } else {
1022            let generation = self.cache_generation.load(Ordering::Acquire);
1023            trace!(target: "providers::static_file", ?segment, ?fixed_block_range, generation, "Creating jar from scratch");
1024            let path = self.path.join(segment.filename(fixed_block_range));
1025            let jar = NippyJar::load(&path).map_err(ProviderError::other)?;
1026            let loaded = LoadedJar::new(jar)?;
1027            #[cfg(test)]
1028            self.before_cache_insert.fire(segment);
1029
1030            // The cache may have been populated since the initial miss, including by
1031            // `update_index` publishing a newer snapshot while we loaded this jar without a lock.
1032            // Preserve that entry instead of overwriting it with our potentially stale snapshot.
1033            self.map
1034                .entry(key)
1035                .or_try_insert_with(|| -> ProviderResult<_> {
1036                    // Validate while holding the entry's shard lock so clearing the cache cannot
1037                    // slip between validation and insertion. If invalidated, reload once under
1038                    // this lock rather than retrying unboundedly during frequent pruning.
1039                    let loaded = if self.cache_generation.load(Ordering::Acquire) == generation {
1040                        loaded
1041                    } else {
1042                        trace!(target: "providers::static_file", ?segment, ?fixed_block_range, generation, "Reloading jar after cache invalidation");
1043                        drop(loaded);
1044                        LoadedJar::new(NippyJar::load(&path).map_err(ProviderError::other)?)?
1045                    };
1046                    #[cfg(test)]
1047                    self.after_cache_validation.fire(segment);
1048                    Ok(loaded)
1049                })?
1050                .downgrade()
1051                .into()
1052        };
1053
1054        if let Some(metrics) = &self.metrics {
1055            provider = provider.with_metrics(metrics.clone());
1056        }
1057        Ok(provider)
1058    }
1059
1060    /// Gets a static file segment's block range from the provider inner block
1061    /// index.
1062    fn get_segment_ranges_from_block(
1063        &self,
1064        segment: StaticFileSegment,
1065        block: u64,
1066    ) -> Option<SegmentRangeInclusive> {
1067        let indexes = self.indexes.read();
1068        let index = indexes.get(segment)?;
1069
1070        (index.max_block >= block).then(|| {
1071            self.find_fixed_range_with_block_index(
1072                segment,
1073                Some(&index.expected_block_ranges_by_max_block),
1074                block,
1075            )
1076        })
1077    }
1078
1079    /// Gets a static file segment's fixed block range from the provider inner
1080    /// transaction index.
1081    fn get_segment_ranges_from_transaction(
1082        &self,
1083        segment: StaticFileSegment,
1084        tx: u64,
1085    ) -> Option<SegmentRangeInclusive> {
1086        let indexes = self.indexes.read();
1087        let index = indexes.get(segment)?;
1088        let available_block_ranges_by_max_tx = index.available_block_ranges_by_max_tx.as_ref()?;
1089
1090        // It's more probable that the request comes from a newer tx height, so we iterate
1091        // the static_files in reverse.
1092        let mut static_files_rev_iter = available_block_ranges_by_max_tx.iter().rev().peekable();
1093
1094        while let Some((tx_end, block_range)) = static_files_rev_iter.next() {
1095            if tx > *tx_end {
1096                // request tx is higher than highest static file tx
1097                return None;
1098            }
1099            let tx_start = static_files_rev_iter.peek().map(|(tx_end, _)| *tx_end + 1).unwrap_or(0);
1100            if tx_start <= tx {
1101                return Some(self.find_fixed_range_with_block_index(
1102                    segment,
1103                    Some(&index.expected_block_ranges_by_max_block),
1104                    block_range.end(),
1105                ));
1106            }
1107        }
1108        None
1109    }
1110
1111    /// Updates the inner transaction and block indexes alongside the internal cached providers in
1112    /// `self.map`.
1113    ///
1114    /// Any entry higher than `segment_max_block` will be deleted from the previous structures.
1115    ///
1116    /// If `segment_max_block` is None it means there's no static file for this segment.
1117    pub fn update_index(
1118        &self,
1119        segment: StaticFileSegment,
1120        segment_max_block: Option<BlockNumber>,
1121    ) -> ProviderResult<()> {
1122        trace!(
1123            target: "providers::static_file",
1124            ?segment,
1125            ?segment_max_block,
1126            "Updating provider index"
1127        );
1128        let mut indexes = self.indexes.write();
1129
1130        match segment_max_block {
1131            Some(segment_max_block) => {
1132                let fixed_range = self.find_fixed_range_with_block_index(
1133                    segment,
1134                    indexes.get(segment).map(|index| &index.expected_block_ranges_by_max_block),
1135                    segment_max_block,
1136                );
1137
1138                let jar = NippyJar::<SegmentHeader>::load(
1139                    &self.path.join(segment.filename(&fixed_range)),
1140                )
1141                .map_err(ProviderError::other)?;
1142
1143                let index = indexes
1144                    .entry(segment)
1145                    .and_modify(|index| {
1146                        // Update max block
1147                        index.max_block = segment_max_block;
1148
1149                        // Update expected block range index
1150
1151                        // Remove all expected block ranges that are less than the new max block
1152                        index
1153                            .expected_block_ranges_by_max_block
1154                            .retain(|_, block_range| block_range.start() < fixed_range.start());
1155                        // Insert new expected block range
1156                        index
1157                            .expected_block_ranges_by_max_block
1158                            .insert(fixed_range.end(), fixed_range);
1159                    })
1160                    .or_insert_with(|| StaticFileSegmentIndex {
1161                        min_block_range: None,
1162                        max_block: segment_max_block,
1163                        expected_block_ranges_by_max_block: BTreeMap::from([(
1164                            fixed_range.end(),
1165                            fixed_range,
1166                        )]),
1167                        available_block_ranges_by_max_tx: None,
1168                    });
1169
1170                // Update min_block to track the lowest block range of the segment.
1171                // This is initially set by initialize_index() on node startup, but must be updated
1172                // as the file grows to prevent stale values.
1173                //
1174                // Without this update, min_block can remain at genesis (e.g. Some([0..=0]) or None)
1175                // even after syncing to higher blocks (e.g. [0..=100]). A stale
1176                // min_block causes get_lowest_static_file_block() to return the
1177                // wrong end value, which breaks pruning logic that relies on it for
1178                // safety checks.
1179                //
1180                // Example progression:
1181                // 1. Node starts, initialize_index() sets min_block = [0..=0]
1182                // 2. Sync to block 100, this update sets min_block = [0..=100]
1183                // 3. Pruner calls get_lowest_static_file_block() -> returns 100 (correct). Without
1184                //    this update, it would incorrectly return 0 (stale)
1185                if let Some(current_block_range) = jar.user_header().block_range() {
1186                    if let Some(min_block_range) = index.min_block_range.as_mut() {
1187                        // delete_jar WILL ALWAYS re-initialize all indexes, so we are always
1188                        // sure that current_min is always the lowest.
1189                        if current_block_range.start() == min_block_range.start() {
1190                            *min_block_range = current_block_range;
1191                        }
1192                    } else {
1193                        index.min_block_range = Some(current_block_range);
1194                    }
1195                }
1196
1197                // Updates the tx index by first removing all entries which have a higher
1198                // block_start than our current static file.
1199                if let Some(tx_range) = jar.user_header().tx_range() {
1200                    // Current block range has the same block start as `fixed_range``, but block end
1201                    // might be different if we are still filling this static file.
1202                    if let Some(current_block_range) = jar.user_header().block_range() {
1203                        let tx_end = tx_range.end();
1204
1205                        // Considering that `update_index` is called when we either append/truncate,
1206                        // we are sure that we are handling the latest data
1207                        // points.
1208                        //
1209                        // Here we remove every entry of the index that has a block start higher or
1210                        // equal than our current one. This is important in the case
1211                        // that we prune a lot of rows resulting in a file (and thus
1212                        // a higher block range) deletion.
1213                        if let Some(index) = index.available_block_ranges_by_max_tx.as_mut() {
1214                            index
1215                                .retain(|_, block_range| block_range.start() < fixed_range.start());
1216                            index.insert(tx_end, current_block_range);
1217                        } else {
1218                            index.available_block_ranges_by_max_tx =
1219                                Some(BTreeMap::from([(tx_end, current_block_range)]));
1220                        }
1221                    }
1222                } else if segment.is_tx_based() {
1223                    // The unwinded file has no more transactions/receipts. However, the highest
1224                    // block is within this files' block range. We only retain
1225                    // entries with block ranges before the current one.
1226                    if let Some(index) = index.available_block_ranges_by_max_tx.as_mut() {
1227                        index.retain(|_, block_range| block_range.start() < fixed_range.start());
1228                    }
1229
1230                    // If the index is empty, just remove it.
1231                    index.available_block_ranges_by_max_tx.take_if(|index| index.is_empty());
1232                }
1233
1234                // Update the cached provider.
1235                trace!(target: "providers::static_file", ?segment, "Inserting updated jar into cache");
1236                self.map.insert((fixed_range.end(), segment), LoadedJar::new(jar)?);
1237
1238                // Delete any cached provider that no longer has an associated jar.
1239                trace!(target: "providers::static_file", ?segment, "Cleaning up jar map");
1240                self.map.retain(|(end, seg), _| !(*seg == segment && *end > fixed_range.end()));
1241            }
1242            None => {
1243                debug!(target: "providers::static_file", ?segment, "Removing segment from index");
1244                indexes.remove(segment);
1245            }
1246        };
1247
1248        trace!(target: "providers::static_file", ?segment, "Updated provider index");
1249        Ok(())
1250    }
1251
1252    /// Initializes the inner transaction and block index
1253    pub fn initialize_index(&self) -> ProviderResult<()> {
1254        let mut indexes = self.indexes.write();
1255        indexes.clear();
1256
1257        for (segment, files) in &*iter_static_files(&self.path).map_err(ProviderError::other)? {
1258            // Update first and last block for each segment
1259            //
1260            // It's safe to call `expect` here, because every segment has at least one file
1261            // associated with it.
1262            let min_block_range = Some(files.first().expect("files are not empty").block_range);
1263            let max_block = files.last().expect("files are not empty").block_range.end();
1264
1265            let mut expected_block_ranges_by_max_block = BTreeMap::default();
1266            let mut available_block_ranges_by_max_tx = None;
1267
1268            for StaticFileEntry { file_range, block_range, header } in files {
1269                // Update max expected block -> expected_block_range index
1270                //
1271                // Keyed by the range the file is named after, as `update_index` does. The header's
1272                // expected range may start later than the name: `init_genesis` moves the first
1273                // changeset file's expected start to a non-zero genesis block.
1274                expected_block_ranges_by_max_block.insert(file_range.end(), *file_range);
1275
1276                // Update max tx -> block_range index
1277                if let Some(tx_range) = header.tx_range() {
1278                    let tx_end = tx_range.end();
1279
1280                    available_block_ranges_by_max_tx
1281                        .get_or_insert_with(BTreeMap::default)
1282                        .insert(tx_end, *block_range);
1283                }
1284            }
1285
1286            indexes.insert(
1287                segment,
1288                StaticFileSegmentIndex {
1289                    min_block_range,
1290                    max_block,
1291                    expected_block_ranges_by_max_block,
1292                    available_block_ranges_by_max_tx,
1293                },
1294            );
1295        }
1296
1297        // If this is a re-initialization, invalidate in-flight cache fills before clearing the
1298        // cache. A fill that started before this point either reloads under its shard lock or
1299        // publishes before the clear reaches that shard and is removed by it.
1300        self.cache_generation.fetch_add(1, Ordering::AcqRel);
1301        self.map.clear();
1302
1303        // initialize the expired history height to the lowest static file block
1304        if let Some(lowest_range) =
1305            indexes.get(StaticFileSegment::Transactions).and_then(|index| index.min_block_range)
1306        {
1307            // the earliest height is the lowest available block number
1308            self.earliest_history_height
1309                .store(lowest_range.start(), std::sync::atomic::Ordering::Relaxed);
1310        }
1311
1312        Ok(())
1313    }
1314
1315    /// Ensures that any broken invariants which cannot be healed on the spot return a pipeline
1316    /// target to unwind to.
1317    ///
1318    /// Two types of consistency checks are done for:
1319    ///
1320    /// 1) When a static file fails to commit but the underlying data was changed.
1321    /// 2) When a static file was committed, but the required database transaction was not.
1322    ///
1323    /// For 1) it can self-heal if `self.access.is_read_only()` is set to `false`. Otherwise, it
1324    /// will return an error.
1325    /// For 2) the invariants below are checked, and if broken, might require a pipeline unwind
1326    /// to heal.
1327    ///
1328    /// For each static file segment:
1329    /// * the corresponding database table should overlap or have continuity in their keys
1330    ///   ([`TxNumber`] or [`BlockNumber`]).
1331    /// * its highest block should match the stage checkpoint block number if it's equal or higher
1332    ///   than the corresponding database table last entry.
1333    ///
1334    /// Returns a [`Option`] of [`PipelineTarget::Unwind`] if any healing is further required.
1335    ///
1336    /// WARNING: No static file writer should be held before calling this function, otherwise it
1337    /// will deadlock.
1338    #[instrument(skip(self, provider), fields(read_only = self.is_read_only()))]
1339    pub fn check_consistency<Provider>(
1340        &self,
1341        provider: &Provider,
1342    ) -> ProviderResult<Option<PipelineTarget>>
1343    where
1344        Provider: DBProvider
1345            + BlockReader
1346            + StageCheckpointReader
1347            + PruneCheckpointReader
1348            + ChainSpecProvider
1349            + StorageSettingsCache,
1350        N: NodePrimitives<Receipt: Value, BlockHeader: Value, SignedTx: Value>,
1351    {
1352        // OVM historical import is broken and does not work with this check. It's importing
1353        // duplicated receipts resulting in having more receipts than the expected transaction
1354        // range.
1355        //
1356        // If we detect an OVM import was done (block #1 <https://optimistic.etherscan.io/block/1>), skip it.
1357        // More on [#11099](https://github.com/paradigmxyz/reth/pull/11099).
1358        if provider.chain_spec().is_optimism() &&
1359            reth_chainspec::Chain::optimism_mainnet() == provider.chain_spec().chain_id()
1360        {
1361            // check whether we have the first OVM block: <https://optimistic.etherscan.io/block/0xbee7192e575af30420cae0c7776304ac196077ee72b048970549e4f08e875453>
1362            const OVM_HEADER_1_HASH: B256 =
1363                b256!("0xbee7192e575af30420cae0c7776304ac196077ee72b048970549e4f08e875453");
1364            if provider.block_number(OVM_HEADER_1_HASH)?.is_some() {
1365                info!(target: "reth::cli",
1366                    "Skipping storage verification for OP mainnet, expected inconsistency in OVM chain"
1367                );
1368                return Ok(None);
1369            }
1370        }
1371
1372        info!(target: "reth::cli", "Verifying storage consistency.");
1373
1374        let mut unwind_target: Option<BlockNumber> = None;
1375
1376        let mut update_unwind_target = |new_target| {
1377            unwind_target =
1378                unwind_target.map(|current| current.min(new_target)).or(Some(new_target));
1379        };
1380
1381        for segment in self.segments_to_check(provider) {
1382            let span = info_span!(
1383                "Checking consistency for segment",
1384                ?segment,
1385                initial_highest_block = tracing::field::Empty,
1386                highest_block = tracing::field::Empty,
1387                highest_tx = tracing::field::Empty,
1388            );
1389            let _guard = span.enter();
1390
1391            debug!(target: "reth::providers::static_file", "Checking consistency for segment");
1392
1393            // Heal file-level inconsistencies and get before/after highest block
1394            let (initial_highest_block, mut highest_block) = self.maybe_heal_segment(segment)?;
1395            span.record("initial_highest_block", initial_highest_block);
1396            span.record("highest_block", highest_block);
1397
1398            // Only applies to block-based static files. (Headers)
1399            //
1400            // The updated `highest_block` may have decreased if we healed from a pruning
1401            // interruption.
1402            if initial_highest_block != highest_block {
1403                info!(
1404                    target: "reth::providers::static_file",
1405                    unwind_target = highest_block,
1406                    "Setting unwind target."
1407                );
1408                update_unwind_target(highest_block.unwrap_or_default());
1409            }
1410
1411            // Only applies to transaction-based static files. (Receipts & Transactions)
1412            //
1413            // Make sure the last transaction matches the last block from its indices, since a heal
1414            // from a pruning interruption might have decreased the number of transactions without
1415            // being able to update the last block of the static file segment.
1416            let highest_tx = if segment == StaticFileSegment::Transactions {
1417                self.highest_transaction_for_consistency(provider.tx_ref(), highest_block)?
1418            } else {
1419                self.get_highest_static_file_tx(segment)
1420            };
1421            span.record("highest_tx", highest_tx);
1422            debug!(target: "reth::providers::static_file", "Checking tx index segment");
1423
1424            if let Some(highest_tx) = highest_tx {
1425                let mut last_block = highest_block.unwrap_or_default();
1426                debug!(target: "reth::providers::static_file", last_block, highest_tx, "Verifying last transaction matches last block indices");
1427                loop {
1428                    let Some(indices) = provider.block_body_indices(last_block)? else {
1429                        debug!(target: "reth::providers::static_file", last_block, "Block body indices not found, static files ahead of database");
1430                        // If the block body indices can not be found, then it means that static
1431                        // files is ahead of database, and the `ensure_invariants` check will fix
1432                        // it by comparing with stage checkpoints.
1433                        break
1434                    };
1435
1436                    debug!(target: "reth::providers::static_file", last_block, last_tx_num = indices.last_tx_num(), "Found block body indices");
1437
1438                    if indices.last_tx_num() <= highest_tx {
1439                        break
1440                    }
1441
1442                    if last_block == 0 {
1443                        debug!(target: "reth::providers::static_file", "Reached block 0 in verification loop");
1444                        break
1445                    }
1446
1447                    last_block -= 1;
1448
1449                    info!(
1450                        target: "reth::providers::static_file",
1451                        highest_block = self.get_highest_static_file_block(segment),
1452                        unwind_target = last_block,
1453                        "Setting unwind target."
1454                    );
1455                    span.record("highest_block", last_block);
1456                    highest_block = Some(last_block);
1457                    update_unwind_target(last_block);
1458                }
1459            }
1460
1461            debug!(target: "reth::providers::static_file", "Ensuring invariants for segment");
1462
1463            match self.ensure_invariants_for(provider, segment, highest_tx, highest_block)? {
1464                Some(unwind) => {
1465                    debug!(target: "reth::providers::static_file", unwind_target=unwind, "Invariants check returned unwind target");
1466                    update_unwind_target(unwind);
1467                }
1468                None => {
1469                    debug!(target: "reth::providers::static_file", "Invariants check completed, no unwind needed")
1470                }
1471            }
1472        }
1473
1474        Ok(unwind_target.map(PipelineTarget::Unwind))
1475    }
1476
1477    /// Heals file-level (`NippyJar`) inconsistencies for eligible static file
1478    /// segments.
1479    ///
1480    /// Call before [`Self::check_consistency`] so files are internally
1481    /// consistent.
1482    ///
1483    /// Uses the same segment-skip logic as [`Self::check_consistency`], but
1484    /// does not compare with database checkpoints or prune against them.
1485    pub fn check_file_consistency<Provider>(&self, provider: &Provider) -> ProviderResult<()>
1486    where
1487        Provider: DBProvider + ChainSpecProvider + StorageSettingsCache + PruneCheckpointReader,
1488    {
1489        info!(target: "reth::cli", "Healing static file inconsistencies.");
1490
1491        for segment in self.segments_to_check(provider) {
1492            let _guard = info_span!("healing_static_file_segment", ?segment).entered();
1493            let _ = self.maybe_heal_segment(segment)?;
1494        }
1495
1496        Ok(())
1497    }
1498
1499    /// Returns the static file segments that should be checked/healed for this provider.
1500    fn segments_to_check<'a, Provider>(
1501        &'a self,
1502        provider: &'a Provider,
1503    ) -> impl Iterator<Item = StaticFileSegment> + 'a
1504    where
1505        Provider: DBProvider + ChainSpecProvider + StorageSettingsCache + PruneCheckpointReader,
1506    {
1507        StaticFileSegment::iter()
1508            .filter(move |segment| self.should_check_segment(provider, *segment))
1509    }
1510
1511    /// True if the given segment should be checked/healed for this provider.
1512    fn should_check_segment<Provider>(
1513        &self,
1514        provider: &Provider,
1515        segment: StaticFileSegment,
1516    ) -> bool
1517    where
1518        Provider: DBProvider + ChainSpecProvider + StorageSettingsCache + PruneCheckpointReader,
1519    {
1520        match segment {
1521            StaticFileSegment::Headers | StaticFileSegment::Transactions => true,
1522            StaticFileSegment::Receipts => {
1523                if EitherWriter::receipts_destination(provider).is_database() {
1524                    // Old pruned nodes (including full node) do not store receipts as static
1525                    // files.
1526                    debug!(target: "reth::providers::static_file", ?segment, "Skipping receipts segment: receipts stored in database");
1527                    return false;
1528                }
1529
1530                if NamedChain::Gnosis == provider.chain_spec().chain_id() ||
1531                    NamedChain::Chiado == provider.chain_spec().chain_id()
1532                {
1533                    // Gnosis and Chiado's historical import is broken and does not work with
1534                    // this check. They are importing receipts along
1535                    // with importing headers/bodies.
1536                    debug!(target: "reth::providers::static_file", ?segment, "Skipping receipts segment: broken historical import for gnosis/chiado");
1537                    return false;
1538                }
1539
1540                true
1541            }
1542            StaticFileSegment::TransactionSenders => {
1543                if EitherWriterDestination::senders(provider).is_database() {
1544                    debug!(target: "reth::providers::static_file", ?segment, "Skipping senders segment: senders stored in database");
1545                    return false;
1546                }
1547
1548                if Self::is_segment_fully_pruned(provider, PruneSegment::SenderRecovery) {
1549                    debug!(target: "reth::providers::static_file", ?segment, "Skipping senders segment: fully pruned");
1550                    return false;
1551                }
1552
1553                // With `Full` sender recovery the engine persists blocks without senders, but
1554                // only the sender recovery stage and the pruner write the `Full` prune checkpoint.
1555                // A node that never ran the pipeline has none until the pruner first runs, which
1556                // the block interval, the minimum pruning distance, or a lagging ExEx can delay.
1557                // With no senders on disk, checking would unwind to genesis.
1558                if provider.prune_modes_ref().sender_recovery.is_some_and(|mode| mode.is_full()) &&
1559                    self.get_highest_static_file_tx(segment).is_none()
1560                {
1561                    debug!(target: "reth::providers::static_file", ?segment, "Skipping senders segment: configured as fully pruned and empty");
1562                    return false;
1563                }
1564
1565                true
1566            }
1567            StaticFileSegment::AccountChangeSets => {
1568                if EitherWriter::account_changesets_destination(provider).is_database() {
1569                    debug!(target: "reth::providers::static_file", ?segment, "Skipping account changesets segment: changesets stored in database");
1570                    return false;
1571                }
1572                true
1573            }
1574            StaticFileSegment::StorageChangeSets => {
1575                if EitherWriter::storage_changesets_destination(provider).is_database() {
1576                    debug!(target: "reth::providers::static_file", ?segment, "Skipping storage changesets segment: changesets stored in database");
1577                    return false
1578                }
1579                true
1580            }
1581        }
1582    }
1583
1584    /// Returns `true` if the given prune segment has a checkpoint with
1585    /// [`reth_prune_types::PruneMode::Full`], indicating all data for this segment has been
1586    /// intentionally deleted.
1587    fn is_segment_fully_pruned<Provider>(provider: &Provider, segment: PruneSegment) -> bool
1588    where
1589        Provider: PruneCheckpointReader,
1590    {
1591        provider
1592            .get_prune_checkpoint(segment)
1593            .ok()
1594            .flatten()
1595            .is_some_and(|checkpoint| checkpoint.prune_mode.is_full())
1596    }
1597
1598    /// Returns the first transaction number after `block`, or `None` if it can't be derived.
1599    ///
1600    /// Falls back to the `Bodies` prune checkpoint when bodies through `block` were never stored,
1601    /// e.g. below a snap sync pivot, where transaction numbers restart at 0.
1602    fn next_tx_num_after<Provider>(
1603        provider: &Provider,
1604        block: BlockNumber,
1605    ) -> ProviderResult<Option<TxNumber>>
1606    where
1607        Provider: BlockReader + PruneCheckpointReader,
1608    {
1609        if let Some(indices) = provider.block_body_indices(block)? {
1610            return Ok(Some(indices.next_tx_num()))
1611        }
1612        Ok(provider
1613            .get_prune_checkpoint(PruneSegment::Bodies)?
1614            .filter(|pruned| {
1615                pruned.tx_number.is_none() &&
1616                    pruned.block_number.is_some_and(|pruned| pruned >= block)
1617            })
1618            .map(|_| 0))
1619    }
1620
1621    /// Checks consistency of the latest static file segment and throws an
1622    /// error if at fault.
1623    ///
1624    /// Read-only.
1625    fn check_segment_consistency(&self, segment: StaticFileSegment) -> ProviderResult<()> {
1626        debug!(target: "reth::providers::static_file", "Checking segment consistency");
1627        if let Some(latest_block) = self.get_highest_static_file_block(segment) {
1628            let file_path = self
1629                .directory()
1630                .join(segment.filename(&self.find_fixed_range(segment, latest_block)));
1631            debug!(target: "reth::providers::static_file", ?file_path, latest_block, "Loading NippyJar for consistency check");
1632
1633            let jar = NippyJar::<SegmentHeader>::load(&file_path).map_err(ProviderError::other)?;
1634            debug!(target: "reth::providers::static_file", "NippyJar loaded, checking consistency");
1635
1636            NippyJarChecker::new(jar).check_consistency().map_err(ProviderError::other)?;
1637            debug!(target: "reth::providers::static_file", "NippyJar consistency check passed");
1638        } else {
1639            debug!(target: "reth::providers::static_file", "No static file block found, skipping consistency check");
1640        }
1641        Ok(())
1642    }
1643
1644    /// Attempts to heal file-level (`NippyJar`) inconsistencies for a single static file segment.
1645    ///
1646    /// Returns the highest block before and after healing, which can be used to detect
1647    /// if healing from a pruning interruption decreased the highest block.
1648    ///
1649    /// File consistency is broken if:
1650    ///
1651    /// * appending data was interrupted before a config commit, then data file will be truncated
1652    ///   according to the config.
1653    ///
1654    /// * pruning data was interrupted before a config commit, then we have deleted data that we are
1655    ///   expected to still have. We need to check the Database and unwind everything accordingly.
1656    ///
1657    /// **Note:** In read-only mode, this will return an error if a consistency issue is detected,
1658    /// since healing requires write access.
1659    fn maybe_heal_segment(
1660        &self,
1661        segment: StaticFileSegment,
1662    ) -> ProviderResult<(Option<BlockNumber>, Option<BlockNumber>)> {
1663        let initial_highest_block = self.get_highest_static_file_block(segment);
1664        debug!(target: "reth::providers::static_file", ?initial_highest_block, "Initial highest block for segment");
1665
1666        if self.access.is_read_only() {
1667            // Read-only mode: cannot modify files, so just validate consistency and error if
1668            // broken.
1669            debug!(target: "reth::providers::static_file", "Checking segment consistency (read-only)");
1670            self.check_segment_consistency(segment)?;
1671        } else {
1672            // Writable mode: fetching the writer will automatically heal any file-level
1673            // inconsistency by truncating data to match the last committed config.
1674            debug!(target: "reth::providers::static_file", "Fetching latest writer which might heal any potential inconsistency");
1675            self.latest_writer(segment)?;
1676        }
1677
1678        // The updated `highest_block` may have decreased if we healed from a
1679        // pruning interruption.
1680        let highest_block = self.get_highest_static_file_block(segment);
1681
1682        Ok((initial_highest_block, highest_block))
1683    }
1684
1685    /// Ensure invariants for each corresponding table and static file segment.
1686    fn ensure_invariants_for<Provider>(
1687        &self,
1688        provider: &Provider,
1689        segment: StaticFileSegment,
1690        highest_tx: Option<u64>,
1691        highest_block: Option<BlockNumber>,
1692    ) -> ProviderResult<Option<BlockNumber>>
1693    where
1694        Provider: DBProvider + BlockReader + StageCheckpointReader + PruneCheckpointReader,
1695        N: NodePrimitives<Receipt: Value, BlockHeader: Value, SignedTx: Value>,
1696    {
1697        match segment {
1698            StaticFileSegment::Headers => self
1699                .ensure_invariants::<_, tables::Headers<N::BlockHeader>>(
1700                    provider,
1701                    segment,
1702                    highest_block,
1703                    highest_block,
1704                ),
1705            StaticFileSegment::Transactions => self
1706                .ensure_invariants::<_, tables::Transactions<N::SignedTx>>(
1707                    provider,
1708                    segment,
1709                    highest_tx,
1710                    highest_block,
1711                ),
1712            StaticFileSegment::Receipts => self
1713                .ensure_invariants::<_, tables::Receipts<N::Receipt>>(
1714                    provider,
1715                    segment,
1716                    highest_tx,
1717                    highest_block,
1718                ),
1719            StaticFileSegment::TransactionSenders => self
1720                .ensure_invariants::<_, tables::TransactionSenders>(
1721                    provider,
1722                    segment,
1723                    highest_tx,
1724                    highest_block,
1725                ),
1726            StaticFileSegment::AccountChangeSets => self
1727                .ensure_invariants::<_, tables::AccountChangeSets>(
1728                    provider,
1729                    segment,
1730                    highest_tx,
1731                    highest_block,
1732                ),
1733            StaticFileSegment::StorageChangeSets => self
1734                .ensure_changeset_invariants_by_block::<_, tables::StorageChangeSets, _>(
1735                    provider,
1736                    segment,
1737                    highest_block,
1738                    |key| key.block_number(),
1739                ),
1740        }
1741    }
1742
1743    /// Check invariants for each corresponding table and static file segment:
1744    ///
1745    /// * the corresponding database table should overlap or have continuity in their keys
1746    ///   ([`TxNumber`] or [`BlockNumber`]).
1747    /// * its highest block should match the stage checkpoint block number if it's equal or higher
1748    ///   than the corresponding database table last entry.
1749    ///   * If the checkpoint block is higher, then request a pipeline unwind to the static file
1750    ///     block. This is expressed by returning [`Some`] with the requested pipeline unwind
1751    ///     target.
1752    ///   * If the checkpoint block is lower, then heal by removing rows from the static file. In
1753    ///     this case, the rows will be removed and [`None`] will be returned.
1754    ///
1755    /// * If the database tables overlap with static files and have contiguous keys, or the
1756    ///   checkpoint block matches the highest static files block, then [`None`] will be returned.
1757    #[instrument(skip(self, provider, segment), fields(table = T::NAME))]
1758    fn ensure_invariants<Provider, T: Table<Key = u64>>(
1759        &self,
1760        provider: &Provider,
1761        segment: StaticFileSegment,
1762        highest_static_file_entry: Option<u64>,
1763        highest_static_file_block: Option<BlockNumber>,
1764    ) -> ProviderResult<Option<BlockNumber>>
1765    where
1766        Provider: DBProvider + BlockReader + StageCheckpointReader + PruneCheckpointReader,
1767    {
1768        debug!(target: "reth::providers::static_file", "Ensuring invariants");
1769        let mut db_cursor = provider.tx_ref().cursor_read::<T>()?;
1770
1771        if let Some((db_first_entry, _)) = db_cursor.first()? {
1772            debug!(target: "reth::providers::static_file", db_first_entry, "Found first database entry");
1773            if let (Some(highest_entry), Some(highest_block)) =
1774                (highest_static_file_entry, highest_static_file_block)
1775            {
1776                // If there is a gap between the entry found in static file and
1777                // database, then we have most likely lost static file data and need to unwind so we
1778                // can load it again
1779                if !(db_first_entry <= highest_entry || highest_entry + 1 == db_first_entry) {
1780                    info!(
1781                        target: "reth::providers::static_file",
1782                        ?db_first_entry,
1783                        ?highest_entry,
1784                        unwind_target = highest_block,
1785                        "Setting unwind target."
1786                    );
1787                    return Ok(Some(highest_block));
1788                }
1789            }
1790
1791            if let Some((db_last_entry, _)) = db_cursor.last()? &&
1792                highest_static_file_entry
1793                    .is_none_or(|highest_entry| db_last_entry > highest_entry)
1794            {
1795                debug!(target: "reth::providers::static_file", db_last_entry, "Database has entries beyond static files, no unwind needed");
1796                return Ok(None)
1797            }
1798        } else {
1799            debug!(target: "reth::providers::static_file", "No database entries found");
1800        }
1801
1802        let highest_static_file_entry = highest_static_file_entry.unwrap_or_default();
1803        let highest_static_file_block = highest_static_file_block.unwrap_or_default();
1804
1805        // If static file entry is ahead of the database entries, then ensure the checkpoint block
1806        // number matches.
1807        let stage_id = segment.to_stage_id();
1808        let checkpoint_block_number =
1809            provider.get_stage_checkpoint(stage_id)?.unwrap_or_default().block_number;
1810        debug!(target: "reth::providers::static_file", ?stage_id, checkpoint_block_number, "Retrieved stage checkpoint");
1811
1812        let effective_coverage_block =
1813            Self::effective_coverage_block(provider, segment, highest_static_file_block)?;
1814
1815        // If the checkpoint is ahead, then we lost static file data. May be data corruption.
1816        if checkpoint_block_number > effective_coverage_block {
1817            info!(
1818                target: "reth::providers::static_file",
1819                checkpoint_block_number,
1820                unwind_target = effective_coverage_block,
1821                "Setting unwind target."
1822            );
1823            return Ok(Some(effective_coverage_block));
1824        }
1825
1826        // If the checkpoint is ahead, or matches, then nothing to do.
1827        if checkpoint_block_number >= highest_static_file_block {
1828            debug!(target: "reth::providers::static_file", "Invariants ensured, returning None");
1829            return Ok(None);
1830        }
1831
1832        // If the checkpoint is behind, then we failed to do a database commit
1833        // **but committed** to static files on executing a stage, or the
1834        // reverse on unwinding a stage.
1835        //
1836        // All we need to do is to prune the extra static file rows.
1837        info!(
1838            target: "reth::providers",
1839            from = highest_static_file_block,
1840            to = checkpoint_block_number,
1841            "Unwinding static file segment."
1842        );
1843        let mut writer = self.latest_writer(segment)?;
1844
1845        match segment {
1846            StaticFileSegment::Headers => {
1847                let prune_count = highest_static_file_block - checkpoint_block_number;
1848                debug!(target: "reth::providers::static_file", prune_count, "Pruning headers");
1849                // TODO(joshie): is_block_meta
1850                writer.prune_headers(prune_count)?;
1851            }
1852            StaticFileSegment::Transactions |
1853            StaticFileSegment::Receipts |
1854            StaticFileSegment::TransactionSenders => {
1855                if let Some(next_tx_num) =
1856                    Self::next_tx_num_after(provider, checkpoint_block_number)?
1857                {
1858                    // `last_tx_num()` saturates to zero for an empty genesis block, but row zero
1859                    // belongs to the first non-empty block and must be removed as well.
1860                    let number =
1861                        highest_static_file_entry.saturating_add(1).saturating_sub(next_tx_num);
1862                    debug!(target: "reth::providers::static_file", prune_count = number, checkpoint_block_number, "Pruning transaction based segment");
1863
1864                    match segment {
1865                        StaticFileSegment::Transactions => {
1866                            writer.prune_transactions(number, checkpoint_block_number)?
1867                        }
1868                        StaticFileSegment::Receipts => {
1869                            writer.prune_receipts(number, checkpoint_block_number)?
1870                        }
1871                        StaticFileSegment::TransactionSenders => {
1872                            writer.prune_transaction_senders(number, checkpoint_block_number)?
1873                        }
1874                        StaticFileSegment::Headers |
1875                        StaticFileSegment::AccountChangeSets |
1876                        StaticFileSegment::StorageChangeSets => {
1877                            unreachable!()
1878                        }
1879                    }
1880                } else {
1881                    debug!(target: "reth::providers::static_file", checkpoint_block_number, "No block body indices found for checkpoint block");
1882                }
1883            }
1884            StaticFileSegment::AccountChangeSets => {
1885                writer.prune_account_changesets(checkpoint_block_number)?;
1886            }
1887            StaticFileSegment::StorageChangeSets => {
1888                writer.prune_storage_changesets(checkpoint_block_number)?;
1889            }
1890        }
1891
1892        debug!(target: "reth::providers::static_file", "Committing writer after pruning");
1893        writer.commit()?;
1894        debug!(target: "reth::providers::static_file", "Writer committed successfully");
1895
1896        debug!(target: "reth::providers::static_file", "Invariants ensured, returning None");
1897        Ok(None)
1898    }
1899
1900    fn ensure_changeset_invariants_by_block<Provider, T, F>(
1901        &self,
1902        provider: &Provider,
1903        segment: StaticFileSegment,
1904        highest_static_file_block: Option<BlockNumber>,
1905        block_from_key: F,
1906    ) -> ProviderResult<Option<BlockNumber>>
1907    where
1908        Provider: DBProvider + BlockReader + StageCheckpointReader + PruneCheckpointReader,
1909        T: Table,
1910        F: Fn(&T::Key) -> BlockNumber,
1911    {
1912        debug!(
1913            target: "reth::providers::static_file",
1914            ?segment,
1915            ?highest_static_file_block,
1916            "Ensuring changeset invariants"
1917        );
1918        let mut db_cursor = provider.tx_ref().cursor_read::<T>()?;
1919
1920        if let Some((db_first_key, _)) = db_cursor.first()? {
1921            let db_first_block = block_from_key(&db_first_key);
1922            if let Some(highest_block) = highest_static_file_block &&
1923                !(db_first_block <= highest_block || highest_block + 1 == db_first_block)
1924            {
1925                info!(
1926                    target: "reth::providers::static_file",
1927                    ?db_first_block,
1928                    ?highest_block,
1929                    unwind_target = highest_block,
1930                    ?segment,
1931                    "Setting unwind target."
1932                );
1933                return Ok(Some(highest_block))
1934            }
1935
1936            if let Some((db_last_key, _)) = db_cursor.last()? &&
1937                highest_static_file_block
1938                    .is_none_or(|highest_block| block_from_key(&db_last_key) > highest_block)
1939            {
1940                debug!(
1941                    target: "reth::providers::static_file",
1942                    ?segment,
1943                    "Database has entries beyond static files, no unwind needed"
1944                );
1945                return Ok(None)
1946            }
1947        } else {
1948            debug!(target: "reth::providers::static_file", ?segment, "No database entries found");
1949        }
1950
1951        let highest_static_file_block = highest_static_file_block.unwrap_or_default();
1952
1953        let stage_id = segment.to_stage_id();
1954        let checkpoint_block_number =
1955            provider.get_stage_checkpoint(stage_id)?.unwrap_or_default().block_number;
1956
1957        let effective_coverage_block =
1958            Self::effective_coverage_block(provider, segment, highest_static_file_block)?;
1959
1960        if checkpoint_block_number > effective_coverage_block {
1961            info!(
1962                target: "reth::providers::static_file",
1963                checkpoint_block_number,
1964                unwind_target = effective_coverage_block,
1965                ?segment,
1966                "Setting unwind target."
1967            );
1968            return Ok(Some(effective_coverage_block))
1969        }
1970
1971        if checkpoint_block_number < highest_static_file_block {
1972            info!(
1973                target: "reth::providers",
1974                ?segment,
1975                from = highest_static_file_block,
1976                to = checkpoint_block_number,
1977                "Unwinding static file segment."
1978            );
1979            let mut writer = self.latest_writer(segment)?;
1980            match segment {
1981                StaticFileSegment::AccountChangeSets => {
1982                    writer.prune_account_changesets(checkpoint_block_number)?;
1983                }
1984                StaticFileSegment::StorageChangeSets => {
1985                    writer.prune_storage_changesets(checkpoint_block_number)?;
1986                }
1987                _ => unreachable!("invalid segment for changeset invariants"),
1988            }
1989            writer.commit()?;
1990        }
1991
1992        Ok(None)
1993    }
1994
1995    /// Returns the highest block accounted for in this segment, either through data
1996    /// present in static files or through data intentionally removed by pruning.
1997    ///
1998    /// Data below a segment's prune checkpoint has been intentionally deleted, so its
1999    /// absence from static files is not an inconsistency. Without this, a pruned segment
2000    /// whose stage checkpoint is ahead of its (empty) static files is treated as data
2001    /// corruption and triggers an unwind to block 0, which aborts the node on startup.
2002    /// See <https://github.com/paradigmxyz/reth/issues/23463>.
2003    fn effective_coverage_block<Provider>(
2004        provider: &Provider,
2005        segment: StaticFileSegment,
2006        highest_static_file_block: BlockNumber,
2007    ) -> ProviderResult<BlockNumber>
2008    where
2009        Provider: PruneCheckpointReader,
2010    {
2011        let Some(prune_segment) = Self::prune_segment_for_static_file(segment) else {
2012            return Ok(highest_static_file_block)
2013        };
2014
2015        let prune_checkpoint_block = provider
2016            .get_prune_checkpoint(prune_segment)?
2017            .and_then(|checkpoint| checkpoint.block_number)
2018            .unwrap_or_default();
2019
2020        Ok(highest_static_file_block.max(prune_checkpoint_block))
2021    }
2022
2023    /// Returns the prune segment that governs data availability for a static file segment,
2024    /// or `None` if the segment is never pruned.
2025    const fn prune_segment_for_static_file(segment: StaticFileSegment) -> Option<PruneSegment> {
2026        match segment {
2027            StaticFileSegment::Receipts => Some(PruneSegment::Receipts),
2028            StaticFileSegment::TransactionSenders => Some(PruneSegment::SenderRecovery),
2029            StaticFileSegment::AccountChangeSets => Some(PruneSegment::AccountHistory),
2030            StaticFileSegment::StorageChangeSets => Some(PruneSegment::StorageHistory),
2031            StaticFileSegment::Headers | StaticFileSegment::Transactions => None,
2032        }
2033    }
2034
2035    /// Returns the earliest available block number that has not been expired and is still
2036    /// available.
2037    ///
2038    /// This means that the highest expired block (or expired block height) is
2039    /// `earliest_history_height.saturating_sub(1)`.
2040    ///
2041    /// Returns `0` if no history has been expired.
2042    pub fn earliest_history_height(&self) -> BlockNumber {
2043        self.earliest_history_height.load(std::sync::atomic::Ordering::Relaxed)
2044    }
2045
2046    /// Sets the earliest available block number, matching what [`Self::initialize_index`] derives.
2047    pub(crate) fn set_earliest_history_height(&self, block: BlockNumber) {
2048        self.earliest_history_height.store(block, std::sync::atomic::Ordering::Relaxed);
2049    }
2050
2051    /// Gets the lowest static file's block range if it exists for a static file segment.
2052    ///
2053    /// If there is nothing on disk for the given segment, this will return [`None`].
2054    pub fn get_lowest_range(&self, segment: StaticFileSegment) -> Option<SegmentRangeInclusive> {
2055        self.indexes.read().get(segment).and_then(|index| index.min_block_range)
2056    }
2057
2058    /// Gets the lowest static file's block range start if it exists for a static file segment.
2059    ///
2060    /// For example if the lowest static file has blocks 0-499, this will return 0.
2061    ///
2062    /// If there is nothing on disk for the given segment, this will return [`None`].
2063    pub fn get_lowest_range_start(&self, segment: StaticFileSegment) -> Option<BlockNumber> {
2064        self.get_lowest_range(segment).map(|range| range.start())
2065    }
2066
2067    /// Gets the lowest static file's block range end if it exists for a static file segment.
2068    ///
2069    /// For example if the static file has blocks 0-499, this will return 499.
2070    ///
2071    /// If there is nothing on disk for the given segment, this will return [`None`].
2072    pub fn get_lowest_range_end(&self, segment: StaticFileSegment) -> Option<BlockNumber> {
2073        self.get_lowest_range(segment).map(|range| range.end())
2074    }
2075
2076    /// Gets the highest static file's block height if it exists for a static file segment.
2077    ///
2078    /// If there is nothing on disk for the given segment, this will return [`None`].
2079    pub fn get_highest_static_file_block(&self, segment: StaticFileSegment) -> Option<BlockNumber> {
2080        self.indexes.read().get(segment).map(|index| index.max_block)
2081    }
2082
2083    /// Converts a range to a bounded `RangeInclusive` capped to the highest static file block.
2084    ///
2085    /// This is necessary because static file iteration beyond the tip would loop forever:
2086    /// blocks beyond the static file tip return `Ok(empty)` which is indistinguishable from
2087    /// blocks with no changes. We cap the end to the highest available block regardless of
2088    /// whether the input was unbounded or an explicit large value like `BlockNumber::MAX`.
2089    fn bound_range(
2090        &self,
2091        range: impl RangeBounds<BlockNumber>,
2092        segment: StaticFileSegment,
2093    ) -> RangeInclusive<BlockNumber> {
2094        changeset_block_range(range, self.get_highest_static_file_block(segment).unwrap_or(0))
2095    }
2096
2097    /// Gets the highest static file transaction.
2098    ///
2099    /// If there is nothing on disk for the given segment, this will return [`None`].
2100    pub fn get_highest_static_file_tx(&self, segment: StaticFileSegment) -> Option<TxNumber> {
2101        self.indexes
2102            .read()
2103            .get(segment)
2104            .and_then(|index| index.available_block_ranges_by_max_tx.as_ref())
2105            .and_then(|index| index.last_key_value().map(|(last_tx, _)| *last_tx))
2106    }
2107
2108    /// Reconciles an older downloader's tip checkpoint with a continuous transaction-file suffix.
2109    /// The caller supplies the first selected block and the tip those files cover. Verified
2110    /// checkpoints, incomplete transaction coverage and ambiguous pruning progress are preserved.
2111    pub fn snapshot_bodies_checkpoint(
2112        &self,
2113        tx: &impl DbTx,
2114        mut checkpoint: PruneCheckpoint,
2115        first: BlockNumber,
2116        tip: BlockNumber,
2117    ) -> ProviderResult<PruneCheckpoint> {
2118        if let Some(block) = checkpoint.block_number &&
2119            (first..=tip).contains(&block) &&
2120            !checkpoint.prune_mode.should_prune(block, tip) &&
2121            tx.get::<tables::Metadata>(keys::VERIFIED_SNAPSHOT_BODIES.to_owned())?.is_none() &&
2122            let Some(last) = tx.get::<tables::BlockBodyIndices>(block)? &&
2123            checkpoint.tx_number == Some(last.last_tx_num()) &&
2124            let Some(indices) = tx.get::<tables::BlockBodyIndices>(first)?
2125        {
2126            // After the chain advances, require another checkpoint written at the old download
2127            // tip. A retained jar can legitimately overlap a stricter source checkpoint.
2128            if block != tip &&
2129                !tx.get::<tables::PruneCheckpoints>(PruneSegment::SenderRecovery)?.is_some_and(
2130                    |sender| {
2131                        sender.block_number == Some(block) &&
2132                            sender.tx_number == checkpoint.tx_number
2133                    },
2134                )
2135            {
2136                return Ok(checkpoint)
2137            }
2138            // A tip-only empty anchor cannot establish that the tip body was restored.
2139            let mut next = indices.first_tx_num();
2140            let end = last.next_tx_num();
2141            if next > end || (first == block && next == end) {
2142                return Ok(checkpoint)
2143            }
2144            while next < end {
2145                let Some(file) =
2146                    self.get_maybe_segment_provider(StaticFileSegment::Transactions, next)?
2147                else {
2148                    return Ok(checkpoint)
2149                };
2150                let header = file.user_header();
2151                let Some(range) = header.tx_range() else { return Ok(checkpoint) };
2152                if !range.contains(next) ||
2153                    range.len() != file.rows() as u64 ||
2154                    !header
2155                        .block_range()
2156                        .is_some_and(|blocks| blocks.end() >= first && blocks.start() <= block)
2157                {
2158                    return Ok(checkpoint)
2159                }
2160                next = range.end().saturating_add(1);
2161            }
2162            checkpoint.block_number = first.checked_sub(1);
2163            checkpoint.tx_number = indices.first_tx_num().checked_sub(1);
2164        }
2165        Ok(checkpoint)
2166    }
2167
2168    /// Returns the last transaction accounted for by the files or the verified snapshot prefix.
2169    /// Used during startup and staged sync. An empty suffix may follow older, disconnected jars.
2170    pub fn highest_transaction_for_consistency(
2171        &self,
2172        tx: &impl DbTx,
2173        highest_block: Option<BlockNumber>,
2174    ) -> ProviderResult<Option<TxNumber>> {
2175        let stored = self.get_highest_static_file_tx(StaticFileSegment::Transactions);
2176        if let Some(highest) = highest_block &&
2177            let Some(pruned) = tx.get::<tables::PruneCheckpoints>(PruneSegment::Bodies)? &&
2178            pruned.block_number.is_some_and(|block| block <= highest) &&
2179            pruned.tx_number > stored &&
2180            tx.get::<tables::Metadata>(keys::VERIFIED_SNAPSHOT_BODIES.to_owned())?.is_some()
2181        {
2182            return Ok(pruned.tx_number)
2183        }
2184        Ok(stored)
2185    }
2186
2187    /// Gets the highest static file block for all segments.
2188    pub fn get_highest_static_files(&self) -> HighestStaticFiles {
2189        HighestStaticFiles {
2190            receipts: self.get_highest_static_file_block(StaticFileSegment::Receipts),
2191        }
2192    }
2193
2194    /// Iterates through segment `static_files` in reverse order, executing a function until it
2195    /// returns some object. Useful for finding objects by [`TxHash`] or [`BlockHash`].
2196    pub fn find_static_file<T>(
2197        &self,
2198        segment: StaticFileSegment,
2199        func: impl Fn(StaticFileJarProvider<'_, N>) -> ProviderResult<Option<T>>,
2200    ) -> ProviderResult<Option<T>> {
2201        if let Some(ranges) =
2202            self.indexes.read().get(segment).map(|index| &index.expected_block_ranges_by_max_block)
2203        {
2204            // Iterate through all ranges in reverse order (highest to lowest)
2205            for range in ranges.values().rev() {
2206                if let Some(res) = func(self.get_or_create_jar_provider(segment, range)?)? {
2207                    return Ok(Some(res));
2208                }
2209            }
2210        }
2211
2212        Ok(None)
2213    }
2214
2215    /// Fetches data within a specified range across multiple static files.
2216    ///
2217    /// This function iteratively retrieves data using `get_fn` for each item in the given range.
2218    /// It continues fetching until the end of the range is reached or the provided `predicate`
2219    /// returns false.
2220    pub fn fetch_range_with_predicate<T, F, P>(
2221        &self,
2222        segment: StaticFileSegment,
2223        range: Range<u64>,
2224        mut get_fn: F,
2225        mut predicate: P,
2226    ) -> ProviderResult<Vec<T>>
2227    where
2228        F: FnMut(&mut StaticFileCursor<'_>, u64) -> ProviderResult<Option<T>>,
2229        P: FnMut(&T) -> bool,
2230    {
2231        let mut result = Vec::with_capacity((range.end - range.start).min(100) as usize);
2232
2233        /// Resolves to the provider for the given block or transaction number.
2234        ///
2235        /// If the static file is missing, the `result` is returned.
2236        macro_rules! get_provider {
2237            ($number:expr) => {{
2238                match self.get_segment_provider(segment, $number) {
2239                    Ok(provider) => provider,
2240                    Err(
2241                        ProviderError::MissingStaticFileBlock(_, _) |
2242                        ProviderError::MissingStaticFileTx(_, _),
2243                    ) => return Ok(result),
2244                    Err(err) => return Err(err),
2245                }
2246            }};
2247        }
2248
2249        let mut provider = get_provider!(range.start);
2250        let mut cursor = provider.cursor()?;
2251
2252        // advances number in range
2253        'outer: for number in range {
2254            // The `retrying` flag ensures a single retry attempt per `number`. If `get_fn` fails to
2255            // access data in two different static files, it halts further attempts by returning
2256            // an error, effectively preventing infinite retry loops.
2257            let mut retrying = false;
2258
2259            // advances static files if `get_fn` returns None
2260            'inner: loop {
2261                match get_fn(&mut cursor, number)? {
2262                    Some(res) => {
2263                        if !predicate(&res) {
2264                            break 'outer;
2265                        }
2266                        result.push(res);
2267                        break 'inner;
2268                    }
2269                    None => {
2270                        if retrying {
2271                            return Ok(result);
2272                        }
2273                        // There is a very small chance of hitting a deadlock if two consecutive
2274                        // static files share the same bucket in the
2275                        // internal dashmap and we don't drop the current provider
2276                        // before requesting the next one.
2277                        drop(cursor);
2278                        drop(provider);
2279                        provider = get_provider!(number);
2280                        cursor = provider.cursor()?;
2281                        retrying = true;
2282                    }
2283                }
2284            }
2285        }
2286
2287        result.shrink_to_fit();
2288
2289        Ok(result)
2290    }
2291
2292    /// Fetches data within a specified range across multiple static files.
2293    ///
2294    /// Returns an iterator over the data. Yields [`None`] if the data for the specified number is
2295    /// not found.
2296    pub fn fetch_range_iter<'a, T, F>(
2297        &'a self,
2298        segment: StaticFileSegment,
2299        range: Range<u64>,
2300        get_fn: F,
2301    ) -> ProviderResult<impl Iterator<Item = ProviderResult<Option<T>>> + 'a>
2302    where
2303        F: Fn(&mut StaticFileCursor<'_>, u64) -> ProviderResult<Option<T>> + 'a,
2304        T: std::fmt::Debug,
2305    {
2306        let mut provider = self.get_maybe_segment_provider(segment, range.start)?;
2307        Ok(range.map(move |number| {
2308            match provider
2309                .as_ref()
2310                .map(|provider| get_fn(&mut provider.cursor()?, number))
2311                .and_then(|result| result.transpose())
2312            {
2313                Some(result) => result.map(Some),
2314                None => {
2315                    // There is a very small chance of hitting a deadlock if two consecutive
2316                    // static files share the same bucket in the internal dashmap and we don't drop
2317                    // the current provider before requesting the next one.
2318                    provider.take();
2319                    provider = self.get_maybe_segment_provider(segment, number)?;
2320                    provider
2321                        .as_ref()
2322                        .map(|provider| get_fn(&mut provider.cursor()?, number))
2323                        .and_then(|result| result.transpose())
2324                        .transpose()
2325                }
2326            }
2327        }))
2328    }
2329
2330    /// Returns directory where `static_files` are located.
2331    pub fn directory(&self) -> &Path {
2332        &self.path
2333    }
2334
2335    /// Retrieves data from the database or static file, wherever it's available.
2336    ///
2337    /// # Arguments
2338    /// * `segment` - The segment of the static file to check against.
2339    /// * `index_key` - Requested index key, usually a block or transaction number.
2340    /// * `fetch_from_static_file` - A closure that defines how to fetch the data from the static
2341    ///   file provider.
2342    /// * `fetch_from_database` - A closure that defines how to fetch the data from the database
2343    ///   when the static file doesn't contain the required data or is not available.
2344    pub fn get_with_static_file_or_database<T, FS, FD>(
2345        &self,
2346        segment: StaticFileSegment,
2347        number: u64,
2348        fetch_from_static_file: FS,
2349        fetch_from_database: FD,
2350    ) -> ProviderResult<Option<T>>
2351    where
2352        FS: Fn(&Self) -> ProviderResult<Option<T>>,
2353        FD: Fn() -> ProviderResult<Option<T>>,
2354    {
2355        // If there is, check the maximum block or transaction number of the segment.
2356        let static_file_upper_bound = if segment.is_block_or_change_based() {
2357            self.get_highest_static_file_block(segment)
2358        } else {
2359            self.get_highest_static_file_tx(segment)
2360        };
2361
2362        if static_file_upper_bound
2363            .is_some_and(|static_file_upper_bound| static_file_upper_bound >= number)
2364        {
2365            return fetch_from_static_file(self);
2366        }
2367        fetch_from_database()
2368    }
2369
2370    /// Gets data within a specified range, potentially spanning different `static_files` and
2371    /// database.
2372    ///
2373    /// # Arguments
2374    /// * `segment` - The segment of the static file to query.
2375    /// * `block_or_tx_range` - The range of data to fetch.
2376    /// * `fetch_from_static_file` - A function to fetch data from the `static_file`.
2377    /// * `fetch_from_database` - A function to fetch data from the database.
2378    /// * `predicate` - A function used to evaluate each item in the fetched data. Fetching is
2379    ///   terminated when this function returns false, thereby filtering the data based on the
2380    ///   provided condition.
2381    pub fn get_range_with_static_file_or_database<T, P, FS, FD>(
2382        &self,
2383        segment: StaticFileSegment,
2384        mut block_or_tx_range: Range<u64>,
2385        fetch_from_static_file: FS,
2386        mut fetch_from_database: FD,
2387        mut predicate: P,
2388    ) -> ProviderResult<Vec<T>>
2389    where
2390        FS: Fn(&Self, Range<u64>, &mut P) -> ProviderResult<Vec<T>>,
2391        FD: FnMut(Range<u64>, P) -> ProviderResult<Vec<T>>,
2392        P: FnMut(&T) -> bool,
2393    {
2394        let mut data = Vec::new();
2395
2396        // If there is, check the maximum block or transaction number of the segment.
2397        if let Some(static_file_upper_bound) = if segment.is_block_or_change_based() {
2398            self.get_highest_static_file_block(segment)
2399        } else {
2400            self.get_highest_static_file_tx(segment)
2401        } && block_or_tx_range.start <= static_file_upper_bound
2402        {
2403            let end = block_or_tx_range.end.min(static_file_upper_bound + 1);
2404            data.extend(fetch_from_static_file(
2405                self,
2406                block_or_tx_range.start..end,
2407                &mut predicate,
2408            )?);
2409            block_or_tx_range.start = end;
2410        }
2411
2412        if block_or_tx_range.end > block_or_tx_range.start {
2413            data.extend(fetch_from_database(block_or_tx_range, predicate)?)
2414        }
2415
2416        Ok(data)
2417    }
2418
2419    /// Returns static files directory
2420    #[cfg(any(test, feature = "test-utils"))]
2421    pub fn path(&self) -> &Path {
2422        &self.path
2423    }
2424
2425    /// Returns transaction index
2426    #[cfg(any(test, feature = "test-utils"))]
2427    pub fn tx_index(&self, segment: StaticFileSegment) -> Option<SegmentRanges> {
2428        self.indexes
2429            .read()
2430            .get(segment)
2431            .and_then(|index| index.available_block_ranges_by_max_tx.as_ref())
2432            .cloned()
2433    }
2434
2435    /// Returns expected block index
2436    #[cfg(any(test, feature = "test-utils"))]
2437    pub fn expected_block_index(&self, segment: StaticFileSegment) -> Option<SegmentRanges> {
2438        self.indexes
2439            .read()
2440            .get(segment)
2441            .map(|index| &index.expected_block_ranges_by_max_block)
2442            .cloned()
2443    }
2444}
2445
2446#[derive(Debug)]
2447struct StaticFileSegmentIndex {
2448    /// Min static file block range.
2449    ///
2450    /// This index is initialized on launch to keep track of the lowest, non-expired static file
2451    /// per segment and gets updated on [`StaticFileProvider::update_index`].
2452    ///
2453    /// This tracks the lowest static file per segment together with the block range in that
2454    /// file. E.g. static file is batched in 500k block intervals then the lowest static file
2455    /// is [0..499K], and the block range is start = 0, end = 499K.
2456    ///
2457    /// This index is mainly used for history expiry, which targets transactions, e.g. pre-merge
2458    /// history expiry would lead to removing all static files below the merge height.
2459    min_block_range: Option<SegmentRangeInclusive>,
2460    /// Max static file block.
2461    max_block: u64,
2462    /// Expected static file block ranges indexed by max expected blocks.
2463    ///
2464    /// For example, a static file for expected block range `0..=499_000` may have only block range
2465    /// `0..=1000` contained in it, as it's not fully filled yet. This index maps the max expected
2466    /// block to the expected range, i.e. block `499_000` to block range `0..=499_000`.
2467    expected_block_ranges_by_max_block: SegmentRanges,
2468    /// Available on disk static file block ranges indexed by max transactions.
2469    ///
2470    /// For example, a static file for block range `0..=499_000` may only have block range
2471    /// `0..=1000` and transaction range `0..=2000` contained in it. This index maps the max
2472    /// available transaction to the available block range, i.e. transaction `2000` to block range
2473    /// `0..=1000`.
2474    available_block_ranges_by_max_tx: Option<SegmentRanges>,
2475}
2476
2477/// Helper trait to manage different [`StaticFileProviderRW`] of an `Arc<StaticFileProvider`
2478pub trait StaticFileWriter {
2479    /// The primitives type used by the static file provider.
2480    type Primitives: Send + Sync + 'static;
2481
2482    /// Returns a mutable reference to a [`StaticFileProviderRW`] of a [`StaticFileSegment`].
2483    fn get_writer(
2484        &self,
2485        block: BlockNumber,
2486        segment: StaticFileSegment,
2487    ) -> ProviderResult<StaticFileProviderRWRefMut<'_, Self::Primitives>>;
2488
2489    /// Returns a mutable reference to a [`StaticFileProviderRW`] of the latest
2490    /// [`StaticFileSegment`].
2491    fn latest_writer(
2492        &self,
2493        segment: StaticFileSegment,
2494    ) -> ProviderResult<StaticFileProviderRWRefMut<'_, Self::Primitives>>;
2495
2496    /// Commits all changes of all [`StaticFileProviderRW`] of all [`StaticFileSegment`].
2497    fn commit(&self) -> ProviderResult<()>;
2498
2499    /// Returns `true` if the static file provider has unwind queued.
2500    fn has_unwind_queued(&self) -> bool;
2501
2502    /// Finalizes all static file writers by committing their configuration to disk.
2503    ///
2504    /// Returns an error if prune is queued (use [`Self::commit`] instead).
2505    fn finalize(&self) -> ProviderResult<()>;
2506}
2507
2508impl<N: NodePrimitives> StaticFileWriter for StaticFileProvider<N> {
2509    type Primitives = N;
2510
2511    fn get_writer(
2512        &self,
2513        block: BlockNumber,
2514        segment: StaticFileSegment,
2515    ) -> ProviderResult<StaticFileProviderRWRefMut<'_, Self::Primitives>> {
2516        if self.access.is_read_only() {
2517            return Err(ProviderError::ReadOnlyStaticFileAccess);
2518        }
2519
2520        trace!(target: "providers::static_file", ?block, ?segment, "Getting static file writer.");
2521        self.writers.get_or_create(segment, || {
2522            StaticFileProviderRW::new(segment, block, Arc::downgrade(&self.0), self.metrics.clone())
2523        })
2524    }
2525
2526    fn latest_writer(
2527        &self,
2528        segment: StaticFileSegment,
2529    ) -> ProviderResult<StaticFileProviderRWRefMut<'_, Self::Primitives>> {
2530        let genesis_number = self.0.as_ref().genesis_block_number();
2531        self.get_writer(
2532            self.get_highest_static_file_block(segment).unwrap_or(genesis_number),
2533            segment,
2534        )
2535    }
2536
2537    fn commit(&self) -> ProviderResult<()> {
2538        self.writers.commit()
2539    }
2540
2541    fn has_unwind_queued(&self) -> bool {
2542        self.writers.has_unwind_queued()
2543    }
2544
2545    fn finalize(&self) -> ProviderResult<()> {
2546        self.writers.finalize()
2547    }
2548}
2549
2550impl<N: NodePrimitives> ChangeSetReader for StaticFileProvider<N> {
2551    fn account_block_changeset(
2552        &self,
2553        block_number: BlockNumber,
2554    ) -> ProviderResult<Vec<reth_db::models::AccountBeforeTx>> {
2555        let provider = match self.get_segment_provider_for_block(
2556            StaticFileSegment::AccountChangeSets,
2557            block_number,
2558            None,
2559        ) {
2560            Ok(provider) => provider,
2561            Err(ProviderError::MissingStaticFileBlock(_, _)) => return Ok(Vec::new()),
2562            Err(err) => return Err(err),
2563        };
2564
2565        if let Some(offset) = provider.read_changeset_offset(block_number)? {
2566            let mut cursor = provider.cursor()?;
2567            let mut changeset = Vec::with_capacity(offset.num_changes() as usize);
2568
2569            for i in offset.changeset_range() {
2570                if let Some(change) =
2571                    cursor.get_one::<reth_db::static_file::AccountChangesetMask>(i.into())?
2572                {
2573                    changeset.push(change)
2574                }
2575            }
2576            Ok(changeset)
2577        } else {
2578            Ok(Vec::new())
2579        }
2580    }
2581
2582    fn get_account_before_block(
2583        &self,
2584        block_number: BlockNumber,
2585        address: Address,
2586    ) -> ProviderResult<Option<reth_db::models::AccountBeforeTx>> {
2587        let provider = match self.get_segment_provider_for_block(
2588            StaticFileSegment::AccountChangeSets,
2589            block_number,
2590            None,
2591        ) {
2592            Ok(provider) => provider,
2593            Err(ProviderError::MissingStaticFileBlock(_, _)) => return Ok(None),
2594            Err(err) => return Err(err),
2595        };
2596
2597        let Some(offset) = provider.read_changeset_offset(block_number)? else {
2598            return Ok(None);
2599        };
2600
2601        let mut cursor = provider.cursor()?;
2602        let range = offset.changeset_range();
2603        let mut low = range.start;
2604        let mut high = range.end;
2605
2606        while low < high {
2607            let mid = low + (high - low) / 2;
2608            if let Some(change) =
2609                cursor.get_one::<reth_db::static_file::AccountChangesetMask>(mid.into())?
2610            {
2611                if change.address < address {
2612                    low = mid + 1;
2613                } else {
2614                    high = mid;
2615                }
2616            } else {
2617                // This is not expected but means we are out of the range / file somehow, and can't
2618                // continue
2619                debug!(
2620                    target: "providers::static_file",
2621                    ?low,
2622                    ?mid,
2623                    ?high,
2624                    ?range,
2625                    ?block_number,
2626                    ?address,
2627                    "Cannot continue binary search for account changeset fetch"
2628                );
2629                low = range.end;
2630                break;
2631            }
2632        }
2633
2634        if low < range.end &&
2635            let Some(change) = cursor
2636                .get_one::<reth_db::static_file::AccountChangesetMask>(low.into())?
2637                .filter(|change| change.address == address)
2638        {
2639            return Ok(Some(change));
2640        }
2641
2642        Ok(None)
2643    }
2644
2645    fn account_changesets_range(
2646        &self,
2647        range: impl core::ops::RangeBounds<BlockNumber>,
2648    ) -> ProviderResult<Vec<(BlockNumber, reth_db::models::AccountBeforeTx)>> {
2649        let mut changesets = Vec::new();
2650        self.for_each_account_changeset(range, |block_number, changeset| {
2651            changesets.push((block_number, changeset))
2652        })?;
2653        Ok(changesets)
2654    }
2655
2656    fn for_each_account_changeset(
2657        &self,
2658        range: impl RangeBounds<BlockNumber>,
2659        mut f: impl FnMut(BlockNumber, AccountBeforeTx),
2660    ) -> ProviderResult<()> {
2661        let range = self.bound_range(range, StaticFileSegment::AccountChangeSets);
2662        for entry in self.walk_account_changeset_range(range) {
2663            let (block_number, changeset) = entry?;
2664            f(block_number, changeset);
2665        }
2666        Ok(())
2667    }
2668}
2669
2670impl<N: NodePrimitives> StorageChangeSetReader for StaticFileProvider<N> {
2671    fn storage_changeset(
2672        &self,
2673        block_number: BlockNumber,
2674    ) -> ProviderResult<Vec<(BlockNumberAddress, StorageEntry)>> {
2675        let provider = match self.get_segment_provider_for_block(
2676            StaticFileSegment::StorageChangeSets,
2677            block_number,
2678            None,
2679        ) {
2680            Ok(provider) => provider,
2681            Err(ProviderError::MissingStaticFileBlock(_, _)) => return Ok(Vec::new()),
2682            Err(err) => return Err(err),
2683        };
2684
2685        if let Some(offset) = provider.read_changeset_offset(block_number)? {
2686            let mut cursor = provider.cursor()?;
2687            let mut changeset = Vec::with_capacity(offset.num_changes() as usize);
2688
2689            for i in offset.changeset_range() {
2690                if let Some(change) = cursor.get_one::<StorageChangesetMask>(i.into())? {
2691                    let block_address = BlockNumberAddress((block_number, change.address));
2692                    let entry = StorageEntry { key: change.key, value: change.value };
2693                    changeset.push((block_address, entry));
2694                }
2695            }
2696            Ok(changeset)
2697        } else {
2698            Ok(Vec::new())
2699        }
2700    }
2701
2702    fn get_storage_before_block(
2703        &self,
2704        block_number: BlockNumber,
2705        address: Address,
2706        storage_key: B256,
2707    ) -> ProviderResult<Option<StorageEntry>> {
2708        let provider = match self.get_segment_provider_for_block(
2709            StaticFileSegment::StorageChangeSets,
2710            block_number,
2711            None,
2712        ) {
2713            Ok(provider) => provider,
2714            Err(ProviderError::MissingStaticFileBlock(_, _)) => return Ok(None),
2715            Err(err) => return Err(err),
2716        };
2717
2718        let Some(offset) = provider.read_changeset_offset(block_number)? else {
2719            return Ok(None);
2720        };
2721
2722        let mut cursor = provider.cursor()?;
2723        let range = offset.changeset_range();
2724        let mut low = range.start;
2725        let mut high = range.end;
2726
2727        while low < high {
2728            let mid = low + (high - low) / 2;
2729            if let Some(change) = cursor.get_one::<StorageChangesetMask>(mid.into())? {
2730                match (change.address, change.key).cmp(&(address, storage_key)) {
2731                    std::cmp::Ordering::Less => low = mid + 1,
2732                    _ => high = mid,
2733                }
2734            } else {
2735                debug!(
2736                    target: "providers::static_file",
2737                    ?low,
2738                    ?mid,
2739                    ?high,
2740                    ?range,
2741                    ?block_number,
2742                    ?address,
2743                    ?storage_key,
2744                    "Cannot continue binary search for storage changeset fetch"
2745                );
2746                low = range.end;
2747                break;
2748            }
2749        }
2750
2751        if low < range.end &&
2752            let Some(change) = cursor
2753                .get_one::<StorageChangesetMask>(low.into())?
2754                .filter(|change| change.address == address && change.key == storage_key)
2755        {
2756            return Ok(Some(StorageEntry { key: change.key, value: change.value }));
2757        }
2758
2759        Ok(None)
2760    }
2761
2762    fn storage_changesets_range(
2763        &self,
2764        range: impl RangeBounds<BlockNumber>,
2765    ) -> ProviderResult<Vec<(BlockNumberAddress, StorageEntry)>> {
2766        let mut changesets = Vec::new();
2767        self.for_each_storage_changeset(range, |block_address, entry| {
2768            changesets.push((block_address, entry))
2769        })?;
2770        Ok(changesets)
2771    }
2772
2773    fn for_each_storage_changeset(
2774        &self,
2775        range: impl RangeBounds<BlockNumber>,
2776        mut f: impl FnMut(BlockNumberAddress, StorageEntry),
2777    ) -> ProviderResult<()> {
2778        let range = self.bound_range(range, StaticFileSegment::StorageChangeSets);
2779        for entry in self.walk_storage_changeset_range(range) {
2780            let (block_address, storage_entry) = entry?;
2781            f(block_address, storage_entry);
2782        }
2783        Ok(())
2784    }
2785}
2786
2787impl<N: NodePrimitives> StaticFileProvider<N> {
2788    /// Creates an iterator for walking through account changesets in the specified block range.
2789    ///
2790    /// This returns a lazy iterator that fetches changesets block by block to avoid loading
2791    /// everything into memory at once.
2792    ///
2793    /// Accepts any range type that implements `RangeBounds<BlockNumber>`, including:
2794    /// - `Range<BlockNumber>` (e.g., `0..100`)
2795    /// - `RangeInclusive<BlockNumber>` (e.g., `0..=99`)
2796    /// - `RangeFrom<BlockNumber>` (e.g., `0..`) - iterates until exhausted
2797    pub fn walk_account_changeset_range(
2798        &self,
2799        range: impl RangeBounds<BlockNumber>,
2800    ) -> StaticFileAccountChangesetWalker<Self> {
2801        StaticFileAccountChangesetWalker::new(self.clone(), range)
2802    }
2803
2804    /// Creates an iterator for walking through storage changesets in the specified block range.
2805    pub fn walk_storage_changeset_range(
2806        &self,
2807        range: impl RangeBounds<BlockNumber>,
2808    ) -> StaticFileStorageChangesetWalker<Self> {
2809        StaticFileStorageChangesetWalker::new(self.clone(), range)
2810    }
2811}
2812
2813impl<N: NodePrimitives<BlockHeader: Value>> HeaderProvider for StaticFileProvider<N> {
2814    type Header = N::BlockHeader;
2815
2816    fn header(&self, block_hash: BlockHash) -> ProviderResult<Option<Self::Header>> {
2817        self.find_static_file(StaticFileSegment::Headers, |jar_provider| {
2818            Ok(jar_provider
2819                .cursor()?
2820                .get_two::<HeaderWithHashMask<Self::Header>>((&block_hash).into())?
2821                .and_then(|(header, hash)| {
2822                    if hash == block_hash {
2823                        return Some(header);
2824                    }
2825                    None
2826                }))
2827        })
2828    }
2829
2830    fn header_by_number(&self, num: BlockNumber) -> ProviderResult<Option<Self::Header>> {
2831        self.get_segment_provider_for_block(StaticFileSegment::Headers, num, None)
2832            .and_then(|provider| provider.header_by_number(num))
2833            .or_else(|err| {
2834                if let ProviderError::MissingStaticFileBlock(_, _) = err {
2835                    Ok(None)
2836                } else {
2837                    Err(err)
2838                }
2839            })
2840    }
2841
2842    fn headers_range(
2843        &self,
2844        range: impl RangeBounds<BlockNumber>,
2845    ) -> ProviderResult<Vec<Self::Header>> {
2846        self.fetch_range_with_predicate(
2847            StaticFileSegment::Headers,
2848            to_range(range),
2849            |cursor, number| cursor.get_one::<HeaderMask<Self::Header>>(number.into()),
2850            |_| true,
2851        )
2852    }
2853
2854    fn sealed_header(
2855        &self,
2856        num: BlockNumber,
2857    ) -> ProviderResult<Option<SealedHeader<Self::Header>>> {
2858        self.get_segment_provider_for_block(StaticFileSegment::Headers, num, None)
2859            .and_then(|provider| provider.sealed_header(num))
2860            .or_else(|err| {
2861                if let ProviderError::MissingStaticFileBlock(_, _) = err {
2862                    Ok(None)
2863                } else {
2864                    Err(err)
2865                }
2866            })
2867    }
2868
2869    fn sealed_headers_while(
2870        &self,
2871        range: impl RangeBounds<BlockNumber>,
2872        predicate: impl FnMut(&SealedHeader<Self::Header>) -> bool,
2873    ) -> ProviderResult<Vec<SealedHeader<Self::Header>>> {
2874        self.fetch_range_with_predicate(
2875            StaticFileSegment::Headers,
2876            to_range(range),
2877            |cursor, number| {
2878                Ok(cursor
2879                    .get_two::<HeaderWithHashMask<Self::Header>>(number.into())?
2880                    .map(|(header, hash)| SealedHeader::new(header, hash)))
2881            },
2882            predicate,
2883        )
2884    }
2885}
2886
2887impl<N: NodePrimitives> BlockHashReader for StaticFileProvider<N> {
2888    fn block_hash(&self, num: u64) -> ProviderResult<Option<B256>> {
2889        self.get_segment_provider_for_block(StaticFileSegment::Headers, num, None)
2890            .and_then(|provider| provider.block_hash(num))
2891            .or_else(|err| {
2892                if let ProviderError::MissingStaticFileBlock(_, _) = err {
2893                    Ok(None)
2894                } else {
2895                    Err(err)
2896                }
2897            })
2898    }
2899
2900    fn canonical_hashes_range(
2901        &self,
2902        start: BlockNumber,
2903        end: BlockNumber,
2904    ) -> ProviderResult<Vec<B256>> {
2905        self.fetch_range_with_predicate(
2906            StaticFileSegment::Headers,
2907            start..end,
2908            |cursor, number| cursor.get_one::<BlockHashMask>(number.into()),
2909            |_| true,
2910        )
2911    }
2912}
2913
2914impl<N: NodePrimitives<SignedTx: Value + SignedTransaction, Receipt: Value>> ReceiptProvider
2915    for StaticFileProvider<N>
2916{
2917    type Receipt = N::Receipt;
2918
2919    fn receipt(&self, num: TxNumber) -> ProviderResult<Option<Self::Receipt>> {
2920        self.get_segment_provider_for_transaction(StaticFileSegment::Receipts, num, None)
2921            .and_then(|provider| provider.receipt(num))
2922            .or_else(|err| {
2923                if let ProviderError::MissingStaticFileTx(_, _) = err {
2924                    Ok(None)
2925                } else {
2926                    Err(err)
2927                }
2928            })
2929    }
2930
2931    fn receipt_by_hash(&self, hash: TxHash) -> ProviderResult<Option<Self::Receipt>> {
2932        if let Some(num) = self.transaction_id(hash)? {
2933            return self.receipt(num);
2934        }
2935        Ok(None)
2936    }
2937
2938    fn receipts_by_block(
2939        &self,
2940        _block: BlockHashOrNumber,
2941    ) -> ProviderResult<Option<Vec<Self::Receipt>>> {
2942        unreachable!()
2943    }
2944
2945    fn receipts_by_tx_range(
2946        &self,
2947        range: impl RangeBounds<TxNumber>,
2948    ) -> ProviderResult<Vec<Self::Receipt>> {
2949        self.fetch_range_with_predicate(
2950            StaticFileSegment::Receipts,
2951            to_range(range),
2952            |cursor, number| cursor.get_one::<ReceiptMask<Self::Receipt>>(number.into()),
2953            |_| true,
2954        )
2955    }
2956
2957    fn receipts_by_block_range(
2958        &self,
2959        _block_range: RangeInclusive<BlockNumber>,
2960    ) -> ProviderResult<Vec<Vec<Self::Receipt>>> {
2961        Err(ProviderError::UnsupportedProvider)
2962    }
2963}
2964
2965impl<N: NodePrimitives<SignedTx: Value, Receipt: Value, BlockHeader: Value>> TransactionsProviderExt
2966    for StaticFileProvider<N>
2967{
2968    fn transaction_hashes_by_range(
2969        &self,
2970        tx_range: Range<TxNumber>,
2971    ) -> ProviderResult<Vec<(TxHash, TxNumber)>> {
2972        let tx_range_size = (tx_range.end - tx_range.start) as usize;
2973
2974        // Transactions are different size, so chunks will not all take the same processing time. If
2975        // chunks are too big, there will be idle threads waiting for work. Choosing an
2976        // arbitrary smaller value to make sure it doesn't happen.
2977        let chunk_size = 100;
2978
2979        // iterator over the chunks
2980        let chunks = tx_range
2981            .clone()
2982            .step_by(chunk_size)
2983            .map(|start| start..std::cmp::min(start + chunk_size as u64, tx_range.end));
2984        let mut channels = Vec::with_capacity(tx_range_size.div_ceil(chunk_size));
2985
2986        for chunk_range in chunks {
2987            let (channel_tx, channel_rx) = mpsc::channel();
2988            channels.push(channel_rx);
2989
2990            let manager = self.clone();
2991
2992            // Spawn the task onto the global rayon pool
2993            // This task will send the cached transaction hash through the channel.
2994            rayon::spawn(move || {
2995                let _ = manager.fetch_range_with_predicate(
2996                    StaticFileSegment::Transactions,
2997                    chunk_range,
2998                    |cursor, number| {
2999                        Ok(cursor
3000                            .get_one::<TransactionMask<Self::Transaction>>(number.into())?
3001                            .map(|transaction| {
3002                                let _ = channel_tx.send(transaction_hash((number, transaction)));
3003                            }))
3004                    },
3005                    |_| true,
3006                );
3007            });
3008        }
3009
3010        let mut tx_list = Vec::with_capacity(tx_range_size);
3011
3012        // Iterate over channels and append the tx hashes unsorted
3013        for channel in channels {
3014            while let Ok(tx) = channel.recv() {
3015                let (tx_hash, tx_id) = tx.map_err(|boxed| *boxed)?;
3016                tx_list.push((tx_hash, tx_id));
3017            }
3018        }
3019
3020        Ok(tx_list)
3021    }
3022}
3023
3024impl<N: NodePrimitives<SignedTx: Decompress + SignedTransaction>> TransactionsProvider
3025    for StaticFileProvider<N>
3026{
3027    type Transaction = N::SignedTx;
3028
3029    fn transaction_id(&self, tx_hash: TxHash) -> ProviderResult<Option<TxNumber>> {
3030        self.find_static_file(StaticFileSegment::Transactions, |jar_provider| {
3031            let mut cursor = jar_provider.cursor()?;
3032            if cursor
3033                .get_one::<TransactionMask<Self::Transaction>>((&tx_hash).into())?
3034                .and_then(|tx| (*tx.tx_hash() == tx_hash).then_some(tx))
3035                .is_some()
3036            {
3037                Ok(cursor.number())
3038            } else {
3039                Ok(None)
3040            }
3041        })
3042    }
3043
3044    fn transaction_by_id(&self, num: TxNumber) -> ProviderResult<Option<Self::Transaction>> {
3045        self.get_segment_provider_for_transaction(StaticFileSegment::Transactions, num, None)
3046            .and_then(|provider| provider.transaction_by_id(num))
3047            .or_else(|err| {
3048                if let ProviderError::MissingStaticFileTx(_, _) = err {
3049                    Ok(None)
3050                } else {
3051                    Err(err)
3052                }
3053            })
3054    }
3055
3056    fn transaction_by_id_unhashed(
3057        &self,
3058        num: TxNumber,
3059    ) -> ProviderResult<Option<Self::Transaction>> {
3060        self.get_segment_provider_for_transaction(StaticFileSegment::Transactions, num, None)
3061            .and_then(|provider| provider.transaction_by_id_unhashed(num))
3062            .or_else(|err| {
3063                if let ProviderError::MissingStaticFileTx(_, _) = err {
3064                    Ok(None)
3065                } else {
3066                    Err(err)
3067                }
3068            })
3069    }
3070
3071    fn transaction_by_hash(&self, hash: TxHash) -> ProviderResult<Option<Self::Transaction>> {
3072        self.find_static_file(StaticFileSegment::Transactions, |jar_provider| {
3073            Ok(jar_provider
3074                .cursor()?
3075                .get_one::<TransactionMask<Self::Transaction>>((&hash).into())?
3076                .and_then(|tx| (*tx.tx_hash() == hash).then_some(tx)))
3077        })
3078    }
3079
3080    fn transaction_by_hash_with_meta(
3081        &self,
3082        _hash: TxHash,
3083    ) -> ProviderResult<Option<(Self::Transaction, TransactionMeta)>> {
3084        // Required data not present in static_files
3085        Err(ProviderError::UnsupportedProvider)
3086    }
3087
3088    fn transactions_by_block(
3089        &self,
3090        _block_id: BlockHashOrNumber,
3091    ) -> ProviderResult<Option<Vec<Self::Transaction>>> {
3092        // Required data not present in static_files
3093        Err(ProviderError::UnsupportedProvider)
3094    }
3095
3096    fn transactions_by_block_range(
3097        &self,
3098        _range: impl RangeBounds<BlockNumber>,
3099    ) -> ProviderResult<Vec<Vec<Self::Transaction>>> {
3100        // Required data not present in static_files
3101        Err(ProviderError::UnsupportedProvider)
3102    }
3103
3104    fn transactions_by_tx_range(
3105        &self,
3106        range: impl RangeBounds<TxNumber>,
3107    ) -> ProviderResult<Vec<Self::Transaction>> {
3108        self.fetch_range_with_predicate(
3109            StaticFileSegment::Transactions,
3110            to_range(range),
3111            |cursor, number| cursor.get_one::<TransactionMask<Self::Transaction>>(number.into()),
3112            |_| true,
3113        )
3114    }
3115
3116    fn senders_by_tx_range(
3117        &self,
3118        range: impl RangeBounds<TxNumber>,
3119    ) -> ProviderResult<Vec<Address>> {
3120        self.fetch_range_with_predicate(
3121            StaticFileSegment::TransactionSenders,
3122            to_range(range),
3123            |cursor, number| cursor.get_one::<TransactionSenderMask>(number.into()),
3124            |_| true,
3125        )
3126    }
3127
3128    fn transaction_sender(&self, id: TxNumber) -> ProviderResult<Option<Address>> {
3129        self.get_segment_provider_for_transaction(StaticFileSegment::TransactionSenders, id, None)
3130            .and_then(|provider| provider.transaction_sender(id))
3131            .or_else(|err| {
3132                if let ProviderError::MissingStaticFileTx(_, _) = err {
3133                    Ok(None)
3134                } else {
3135                    Err(err)
3136                }
3137            })
3138    }
3139}
3140
3141impl<N: NodePrimitives> BlockNumReader for StaticFileProvider<N> {
3142    fn chain_info(&self) -> ProviderResult<ChainInfo> {
3143        // Required data not present in static_files
3144        Err(ProviderError::UnsupportedProvider)
3145    }
3146
3147    fn best_block_number(&self) -> ProviderResult<BlockNumber> {
3148        // Required data not present in static_files
3149        Err(ProviderError::UnsupportedProvider)
3150    }
3151
3152    fn last_block_number(&self) -> ProviderResult<BlockNumber> {
3153        Ok(self.get_highest_static_file_block(StaticFileSegment::Headers).unwrap_or_default())
3154    }
3155
3156    fn block_number(&self, _hash: B256) -> ProviderResult<Option<BlockNumber>> {
3157        // Required data not present in static_files
3158        Err(ProviderError::UnsupportedProvider)
3159    }
3160}
3161
3162/* Cannot be successfully implemented but must exist for trait requirements */
3163
3164impl<N: NodePrimitives<SignedTx: Value, Receipt: Value, BlockHeader: Value>> BlockReader
3165    for StaticFileProvider<N>
3166{
3167    type Block = N::Block;
3168
3169    fn find_block_by_hash(
3170        &self,
3171        _hash: B256,
3172        _source: BlockSource,
3173    ) -> ProviderResult<Option<Self::Block>> {
3174        // Required data not present in static_files
3175        Err(ProviderError::UnsupportedProvider)
3176    }
3177
3178    fn block(&self, _id: BlockHashOrNumber) -> ProviderResult<Option<Self::Block>> {
3179        // Required data not present in static_files
3180        Err(ProviderError::UnsupportedProvider)
3181    }
3182
3183    fn pending_block(&self) -> ProviderResult<Option<Arc<RecoveredBlock<Self::Block>>>> {
3184        // Required data not present in static_files
3185        Err(ProviderError::UnsupportedProvider)
3186    }
3187
3188    fn pending_block_and_receipts(
3189        &self,
3190    ) -> ProviderResult<Option<RecoveredBlockAndExecutionOutput<Self::Block, Self::Receipt>>> {
3191        // Required data not present in static_files
3192        Err(ProviderError::UnsupportedProvider)
3193    }
3194
3195    fn recovered_block(
3196        &self,
3197        _id: BlockHashOrNumber,
3198        _transaction_kind: TransactionVariant,
3199    ) -> ProviderResult<Option<RecoveredBlock<Self::Block>>> {
3200        // Required data not present in static_files
3201        Err(ProviderError::UnsupportedProvider)
3202    }
3203
3204    fn sealed_block_with_senders(
3205        &self,
3206        _id: BlockHashOrNumber,
3207        _transaction_kind: TransactionVariant,
3208    ) -> ProviderResult<Option<RecoveredBlock<Self::Block>>> {
3209        // Required data not present in static_files
3210        Err(ProviderError::UnsupportedProvider)
3211    }
3212
3213    fn block_range(&self, _range: RangeInclusive<BlockNumber>) -> ProviderResult<Vec<Self::Block>> {
3214        // Required data not present in static_files
3215        Err(ProviderError::UnsupportedProvider)
3216    }
3217
3218    fn block_with_senders_range(
3219        &self,
3220        _range: RangeInclusive<BlockNumber>,
3221    ) -> ProviderResult<Vec<RecoveredBlock<Self::Block>>> {
3222        Err(ProviderError::UnsupportedProvider)
3223    }
3224
3225    fn recovered_block_range(
3226        &self,
3227        _range: RangeInclusive<BlockNumber>,
3228    ) -> ProviderResult<Vec<RecoveredBlock<Self::Block>>> {
3229        Err(ProviderError::UnsupportedProvider)
3230    }
3231
3232    fn block_by_transaction_id(&self, _id: TxNumber) -> ProviderResult<Option<BlockNumber>> {
3233        Err(ProviderError::UnsupportedProvider)
3234    }
3235}
3236
3237impl<N: NodePrimitives> BlockBodyIndicesProvider for StaticFileProvider<N> {
3238    fn block_body_indices(&self, _num: u64) -> ProviderResult<Option<StoredBlockBodyIndices>> {
3239        Err(ProviderError::UnsupportedProvider)
3240    }
3241
3242    fn block_body_indices_range(
3243        &self,
3244        _range: RangeInclusive<BlockNumber>,
3245    ) -> ProviderResult<Vec<StoredBlockBodyIndices>> {
3246        Err(ProviderError::UnsupportedProvider)
3247    }
3248}
3249
3250impl<N: NodePrimitives> StatsReader for StaticFileProvider<N> {
3251    fn count_entries<T: Table>(&self) -> ProviderResult<usize> {
3252        match T::NAME {
3253            tables::CanonicalHeaders::NAME |
3254            tables::Headers::<Header>::NAME |
3255            tables::HeaderTerminalDifficulties::NAME => Ok(self
3256                .get_highest_static_file_block(StaticFileSegment::Headers)
3257                .map(|block| block + 1)
3258                .unwrap_or_default()
3259                as usize),
3260            tables::Receipts::<Receipt>::NAME => Ok(self
3261                .get_highest_static_file_tx(StaticFileSegment::Receipts)
3262                .map(|receipts| receipts + 1)
3263                .unwrap_or_default() as usize),
3264            tables::Transactions::<TransactionSigned>::NAME => Ok(self
3265                .get_highest_static_file_tx(StaticFileSegment::Transactions)
3266                .map(|txs| txs + 1)
3267                .unwrap_or_default()
3268                as usize),
3269            tables::TransactionSenders::NAME => Ok(self
3270                .get_highest_static_file_tx(StaticFileSegment::TransactionSenders)
3271                .map(|txs| txs + 1)
3272                .unwrap_or_default() as usize),
3273            _ => Err(ProviderError::UnsupportedProvider),
3274        }
3275    }
3276}
3277
3278/// Returns the tx hash for the given transaction and its id.
3279#[inline]
3280fn transaction_hash<T>(entry: (TxNumber, T)) -> Result<(B256, TxNumber), Box<ProviderError>>
3281where
3282    T: TxHashRef,
3283{
3284    let (tx_id, tx) = entry;
3285    Ok((*tx.tx_hash(), tx_id))
3286}
3287
3288#[cfg(test)]
3289mod tests {
3290    use std::{
3291        collections::BTreeMap,
3292        sync::{atomic::Ordering, mpsc},
3293        thread,
3294        time::{Duration, Instant},
3295    };
3296
3297    use alloy_consensus::Header;
3298    use alloy_primitives::B256;
3299    use reth_chain_state::EthPrimitives;
3300    use reth_db::test_utils::create_test_static_files_dir;
3301    use reth_static_file_types::{SegmentRangeInclusive, StaticFileSegment};
3302
3303    use super::StaticFileWriter;
3304    use crate::{providers::StaticFileProvider, BlockHashReader, StaticFileProviderBuilder};
3305    use alloy_consensus::{SignableTransaction, TxLegacy};
3306    use alloy_primitives::Signature;
3307    use reth_db::{tables, transaction::DbTxMut};
3308
3309    #[test]
3310    fn recovery_prunes_transaction_zero_at_empty_genesis() -> eyre::Result<()> {
3311        use crate::{
3312            test_utils::create_test_provider_factory, StaticFileProviderFactory,
3313            TransactionsProvider,
3314        };
3315
3316        let factory = create_test_provider_factory();
3317        let provider = factory.provider_rw()?;
3318        provider.tx_ref().put::<tables::BlockBodyIndices>(0, Default::default())?;
3319        provider.commit()?;
3320
3321        let static_files = factory.static_file_provider();
3322        let segment = StaticFileSegment::Transactions;
3323        let tx = TxLegacy::default().into_signed(Signature::test_signature()).into();
3324        {
3325            let mut writer = static_files.latest_writer(segment)?;
3326            writer.increment_block(0)?;
3327            writer.increment_block(1)?;
3328            writer.append_transaction(0, &tx)?;
3329            writer.commit()?;
3330        }
3331        assert!(static_files.transaction_by_id(0)?.is_some());
3332
3333        assert_eq!(static_files.check_consistency(&factory.provider()?)?, None);
3334        assert_eq!(static_files.get_highest_static_file_block(segment), Some(0));
3335        assert!(static_files.transaction_by_id(0)?.is_none());
3336
3337        let mut writer = static_files.latest_writer(segment)?;
3338        writer.increment_block(1)?;
3339        writer.append_transaction(0, &tx)?;
3340        writer.commit()?;
3341        Ok(())
3342    }
3343
3344    #[test]
3345    fn stale_cache_fill_does_not_survive_index_reinitialization() -> eyre::Result<()> {
3346        let (static_dir, _) = create_test_static_files_dir();
3347        let static_files: StaticFileProvider<EthPrimitives> =
3348            StaticFileProviderBuilder::read_write(&static_dir)
3349                .with_blocks_per_file_for_segment(StaticFileSegment::Headers, 10)
3350                .with_blocks_per_file_for_segment(StaticFileSegment::Receipts, 2)
3351                .build()?;
3352
3353        let hash_0 = B256::repeat_byte(0x10);
3354        let header_0 = Header { number: 0, ..Default::default() };
3355        {
3356            let mut writer = static_files.latest_writer(StaticFileSegment::Headers)?;
3357            writer.append_header(&header_0, &hash_0)?;
3358            writer.commit()?;
3359        }
3360
3361        // Create two receipt jars. Deleting either one reinitializes every segment index and
3362        // invalidates the shared jar cache, matching the pruning path from the incidents.
3363        {
3364            let mut writer = static_files.latest_writer(StaticFileSegment::Receipts)?;
3365            for block in 0..=3 {
3366                writer.increment_block(block)?;
3367            }
3368            writer.commit()?;
3369        }
3370        static_files.delete_jar(StaticFileSegment::Receipts, 0)?;
3371
3372        let (loaded_tx, loaded_rx) = mpsc::sync_channel(0);
3373        let (resume_tx, resume_rx) = mpsc::sync_channel(0);
3374        static_files.before_cache_insert.set(move |segment| {
3375            assert_eq!(segment, StaticFileSegment::Headers);
3376            loaded_tx.send(()).expect("test controller dropped");
3377            resume_rx
3378                .recv_timeout(Duration::from_secs(10))
3379                .expect("test controller did not resume");
3380        });
3381
3382        // Pause a cache fill after it loads the header jar containing only block 0.
3383        let reader_static_files = static_files.clone();
3384        let reader = thread::spawn(move || reader_static_files.block_hash(0));
3385        loaded_rx
3386            .recv_timeout(Duration::from_secs(10))
3387            .expect("reader did not reach cache-fill hook");
3388
3389        // Publish a newer snapshot of the same header jar, then simulate unrelated segment
3390        // pruning invalidating the whole cache while the old load remains in flight.
3391        let hash_1 = B256::repeat_byte(0x11);
3392        let header_1 = Header { number: 1, ..Default::default() };
3393        {
3394            let mut writer = static_files.latest_writer(StaticFileSegment::Headers)?;
3395            writer.append_header(&header_1, &hash_1)?;
3396            writer.commit()?;
3397        }
3398        static_files.delete_jar(StaticFileSegment::Receipts, 2)?;
3399
3400        resume_tx.send(()).expect("reader dropped before cache publication");
3401        assert_eq!(reader.join().expect("reader panicked")?, Some(hash_0));
3402        assert_eq!(
3403            static_files.block_hash(1)?,
3404            Some(hash_1),
3405            "cache fill started before reinitialization repopulated an invalidated jar"
3406        );
3407
3408        Ok(())
3409    }
3410
3411    #[test]
3412    fn cache_fill_validation_is_serialized_with_index_reinitialization() -> eyre::Result<()> {
3413        let (static_dir, _) = create_test_static_files_dir();
3414        let static_files: StaticFileProvider<EthPrimitives> =
3415            StaticFileProviderBuilder::read_write(&static_dir).with_blocks_per_file(10).build()?;
3416        let hash = B256::repeat_byte(0x10);
3417        {
3418            let mut writer = static_files.latest_writer(StaticFileSegment::Headers)?;
3419            writer.append_header(&Header::default(), &hash)?;
3420            writer.commit()?;
3421        }
3422        static_files.remove_cached_provider(StaticFileSegment::Headers, 9);
3423
3424        let generation = static_files.cache_generation.load(Ordering::Acquire);
3425        let (validated_tx, validated_rx) = mpsc::sync_channel(0);
3426        let (resume_tx, resume_rx) = mpsc::sync_channel(0);
3427        static_files.after_cache_validation.set(move |segment| {
3428            assert_eq!(segment, StaticFileSegment::Headers);
3429            validated_tx.send(()).expect("test controller dropped");
3430            resume_rx
3431                .recv_timeout(Duration::from_secs(10))
3432                .expect("test controller did not resume");
3433        });
3434
3435        let reader_static_files = static_files.clone();
3436        let reader = thread::spawn(move || reader_static_files.block_hash(0));
3437        validated_rx
3438            .recv_timeout(Duration::from_secs(10))
3439            .expect("reader did not reach cache validation");
3440
3441        // The shard must remain locked between checking the generation and inserting the jar.
3442        // Otherwise a clear can finish here and the reader can repopulate the cache afterward.
3443        assert!(static_files.map.try_get(&(9, StaticFileSegment::Headers)).is_locked());
3444        let invalidator_static_files = static_files.clone();
3445        let invalidator = thread::spawn(move || invalidator_static_files.initialize_index());
3446        let deadline = Instant::now() + Duration::from_secs(10);
3447        while static_files.cache_generation.load(Ordering::Acquire) == generation {
3448            assert!(Instant::now() < deadline, "reinitialization did not invalidate the cache");
3449            thread::sleep(Duration::from_millis(1));
3450        }
3451
3452        // Invalidation has started, but clearing this shard must wait for publication and the
3453        // reader's guard to be released. The published snapshot must not survive that clear.
3454        resume_tx.send(()).expect("reader dropped before cache publication");
3455        assert_eq!(reader.join().expect("reader panicked")?, Some(hash));
3456        invalidator.join().expect("invalidator panicked")?;
3457        assert!(static_files.map.is_empty());
3458        assert_eq!(static_files.block_hash(0)?, Some(hash));
3459
3460        Ok(())
3461    }
3462
3463    /// The first changeset file of a chain whose genesis is not at a file boundary starts at the
3464    /// genesis block (`SegmentHeader::set_expected_block_start`) but keeps its fixed-range name.
3465    /// An index rebuilt from disk must find it under that name.
3466    #[test]
3467    fn index_finds_file_whose_header_starts_after_its_name() -> eyre::Result<()> {
3468        let (static_dir, _) = create_test_static_files_dir();
3469        let segment = StaticFileSegment::AccountChangeSets;
3470        let genesis = 510;
3471        {
3472            let static_files: StaticFileProvider<EthPrimitives> =
3473                StaticFileProviderBuilder::read_write(&static_dir)
3474                    .with_blocks_per_file(100)
3475                    .build()?;
3476            let mut writer = static_files.get_writer(genesis, segment)?;
3477            writer.user_header_mut().set_expected_block_start(genesis);
3478            writer.append_account_changeset(Vec::new(), genesis)?;
3479            writer.commit()?;
3480        }
3481
3482        let static_files: StaticFileProvider<EthPrimitives> =
3483            StaticFileProviderBuilder::read_write(&static_dir).with_blocks_per_file(100).build()?;
3484        assert_eq!(
3485            static_files.find_fixed_range(segment, genesis),
3486            SegmentRangeInclusive::new(500, 599)
3487        );
3488        assert_eq!(static_files.get_highest_static_file_block(segment), Some(genesis));
3489        assert_eq!(static_files.latest_writer(segment)?.next_block_number(), genesis + 1);
3490
3491        // Also when opened without a genesis number and with another `blocks_per_file`, as
3492        // `db stats` opens it: the name is the source of the range, not the configuration.
3493        let static_files: StaticFileProvider<EthPrimitives> =
3494            StaticFileProvider::read_only(&static_dir)?;
3495        assert_eq!(
3496            static_files.find_fixed_range(segment, genesis),
3497            SegmentRangeInclusive::new(500, 599)
3498        );
3499        assert_eq!(static_files.get_highest_static_file_block(segment), Some(genesis));
3500        Ok(())
3501    }
3502
3503    #[test]
3504    fn test_find_fixed_range_with_block_index() -> eyre::Result<()> {
3505        let (static_dir, _) = create_test_static_files_dir();
3506        let sf_rw: StaticFileProvider<EthPrimitives> =
3507            StaticFileProviderBuilder::read_write(&static_dir).with_blocks_per_file(100).build()?;
3508
3509        let segment = StaticFileSegment::Headers;
3510
3511        // Test with None - should use default behavior
3512        assert_eq!(
3513            sf_rw.find_fixed_range_with_block_index(segment, None, 0),
3514            SegmentRangeInclusive::new(0, 99)
3515        );
3516        assert_eq!(
3517            sf_rw.find_fixed_range_with_block_index(segment, None, 250),
3518            SegmentRangeInclusive::new(200, 299)
3519        );
3520
3521        // Test with empty index - should fall back to default behavior
3522        assert_eq!(
3523            sf_rw.find_fixed_range_with_block_index(segment, Some(&BTreeMap::new()), 150),
3524            SegmentRangeInclusive::new(100, 199)
3525        );
3526
3527        // Create block index with existing ranges
3528        let block_index = BTreeMap::from_iter([
3529            (99, SegmentRangeInclusive::new(0, 99)),
3530            (199, SegmentRangeInclusive::new(100, 199)),
3531            (299, SegmentRangeInclusive::new(200, 299)),
3532        ]);
3533
3534        // Test blocks within existing ranges - should return the matching range
3535        assert_eq!(
3536            sf_rw.find_fixed_range_with_block_index(segment, Some(&block_index), 0),
3537            SegmentRangeInclusive::new(0, 99)
3538        );
3539        assert_eq!(
3540            sf_rw.find_fixed_range_with_block_index(segment, Some(&block_index), 50),
3541            SegmentRangeInclusive::new(0, 99)
3542        );
3543        assert_eq!(
3544            sf_rw.find_fixed_range_with_block_index(segment, Some(&block_index), 99),
3545            SegmentRangeInclusive::new(0, 99)
3546        );
3547        assert_eq!(
3548            sf_rw.find_fixed_range_with_block_index(segment, Some(&block_index), 100),
3549            SegmentRangeInclusive::new(100, 199)
3550        );
3551        assert_eq!(
3552            sf_rw.find_fixed_range_with_block_index(segment, Some(&block_index), 150),
3553            SegmentRangeInclusive::new(100, 199)
3554        );
3555        assert_eq!(
3556            sf_rw.find_fixed_range_with_block_index(segment, Some(&block_index), 199),
3557            SegmentRangeInclusive::new(100, 199)
3558        );
3559
3560        // Test blocks beyond existing ranges - should derive new ranges from the last range
3561        // Block 300 is exactly one segment after the last range
3562        assert_eq!(
3563            sf_rw.find_fixed_range_with_block_index(segment, Some(&block_index), 300),
3564            SegmentRangeInclusive::new(300, 399)
3565        );
3566        assert_eq!(
3567            sf_rw.find_fixed_range_with_block_index(segment, Some(&block_index), 350),
3568            SegmentRangeInclusive::new(300, 399)
3569        );
3570
3571        // Block 500 skips one segment (300-399)
3572        assert_eq!(
3573            sf_rw.find_fixed_range_with_block_index(segment, Some(&block_index), 500),
3574            SegmentRangeInclusive::new(500, 599)
3575        );
3576
3577        // Block 1000 skips many segments
3578        assert_eq!(
3579            sf_rw.find_fixed_range_with_block_index(segment, Some(&block_index), 1000),
3580            SegmentRangeInclusive::new(1000, 1099)
3581        );
3582
3583        // Test with block index having different sizes than blocks_per_file setting
3584        // This simulates the scenario where blocks_per_file was changed between runs
3585        let mixed_size_index = BTreeMap::from_iter([
3586            (49, SegmentRangeInclusive::new(0, 49)),     // 50 blocks
3587            (149, SegmentRangeInclusive::new(50, 149)),  // 100 blocks
3588            (349, SegmentRangeInclusive::new(150, 349)), // 200 blocks
3589        ]);
3590
3591        // Blocks within existing ranges should return those ranges regardless of size
3592        assert_eq!(
3593            sf_rw.find_fixed_range_with_block_index(segment, Some(&mixed_size_index), 25),
3594            SegmentRangeInclusive::new(0, 49)
3595        );
3596        assert_eq!(
3597            sf_rw.find_fixed_range_with_block_index(segment, Some(&mixed_size_index), 100),
3598            SegmentRangeInclusive::new(50, 149)
3599        );
3600        assert_eq!(
3601            sf_rw.find_fixed_range_with_block_index(segment, Some(&mixed_size_index), 200),
3602            SegmentRangeInclusive::new(150, 349)
3603        );
3604
3605        // Block after the last range should derive using current blocks_per_file (100)
3606        // from the end of the last range (349)
3607        assert_eq!(
3608            sf_rw.find_fixed_range_with_block_index(segment, Some(&mixed_size_index), 350),
3609            SegmentRangeInclusive::new(350, 449)
3610        );
3611        assert_eq!(
3612            sf_rw.find_fixed_range_with_block_index(segment, Some(&mixed_size_index), 450),
3613            SegmentRangeInclusive::new(450, 549)
3614        );
3615        assert_eq!(
3616            sf_rw.find_fixed_range_with_block_index(segment, Some(&mixed_size_index), 550),
3617            SegmentRangeInclusive::new(550, 649)
3618        );
3619
3620        Ok(())
3621    }
3622}